file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
./partial_match/100/0x21cd73a7f09032689F833624e2840CBB958d9181/sources/RandomAuRa.sol
|
Returns the cipher of the validator's number for the specified collection round and the specified validator stored by the validator through the `commitHash` function. For the past collection rounds the cipher is empty as it's erased by the internal `_clearOldCiphers` function. _collectRound The serial number of the collection round for which the cipher should be retrieved. _miningAddress The mining address of validator.
|
function getCipher(uint256 _collectRound, address _miningAddress) public view returns(bytes memory) {
address stakingAddress = validatorSetContract.stakingByMiningAddress(_miningAddress);
return _ciphers[_collectRound][stakingAddress];
}
| 16,647,070
|
./full_match/42161/0xF83675ac64a142D92234681B7AfB6Ba00fa38dFF/sources/project_/contracts/core/LfgSwapRouter.sol
|
refund dust eth, if any
|
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,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = LfgSwapLibrary.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = ILfgSwapPair(pair).mint(to);
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
| 16,301,487
|
// File: contracts/external/govblocks-protocol/interfaces/IProposalCategory.sol
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract IProposalCategory {
event Category(
uint indexed categoryId,
string categoryName,
string actionHash
);
mapping(uint256 => bytes) public categoryActionHashes;
/**
* @dev Adds new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function newCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives,
string calldata _functionHash
)
external;
/** @dev gets category details
*/
function category(uint _categoryId)
external
view
returns(
uint categoryId,
uint memberRoleToVote,
uint majorityVotePerc,
uint quorumPerc,
uint[] memory allowedToCreateProposal,
uint closingTime,
uint minStake
);
/**@dev gets category action details
*/
function categoryAction(uint _categoryId)
external
view
returns(
uint categoryId,
address contractAddress,
bytes2 contractName,
uint defaultIncentive
);
/** @dev Gets Total number of categories added till now
*/
function totalCategories() external view returns(uint numberOfCategories);
/**
* @dev Gets the category acion details of a category id
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
* @return action function hash
*/
function categoryActionDetails(uint256 _categoryId)
external
view
returns (
uint256,
address,
bytes2,
uint256,
bytes memory
);
/**
* @dev Updates category details
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function editCategory(
uint _categoryId,
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives,
string calldata _functionHash
)
external;
}
// File: contracts/external/govblocks-protocol/interfaces/IMemberRoles.sol
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract IMemberRoles {
event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription);
enum Role {UnAssigned, AdvisoryBoard, TokenHolder, DisputeResolution}
function setInititorAddress(address _initiator) external;
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function addRole(bytes32 _roleName, string memory _roleDescription, address _authorized) public;
/// @dev Assign or Delete a member from specific role.
/// @param _memberAddress Address of Member
/// @param _roleId RoleId to update
/// @param _active active is set to be True if we want to assign this role to member, False otherwise!
function updateRole(address _memberAddress, uint _roleId, bool _active) public;
/// @dev Change Member Address who holds the authority to Add/Delete any member from specific role.
/// @param _roleId roleId to update its Authorized Address
/// @param _authorized New authorized address against role id
function changeAuthorized(uint _roleId, address _authorized) public;
/// @dev Return number of member roles
function totalRoles() public view returns(uint256);
/// @dev Gets the member addresses assigned by a specific role
/// @param _memberRoleId Member role id
/// @return roleId Role id
/// @return allMemberAddress Member addresses of specified role id
function members(uint _memberRoleId) public view returns(uint, address[] memory allMemberAddress);
/// @dev Gets all members' length
/// @param _memberRoleId Member role id
/// @return memberRoleData[_memberRoleId].memberAddress.length Member length
function numberOfMembers(uint _memberRoleId) public view returns(uint);
/// @dev Return member address who holds the right to add/remove any member from specific role.
function authorized(uint _memberRoleId) public view returns(address);
/// @dev Get All role ids array that has been assigned to a member so far.
function roles(address _memberAddress) public view returns(uint[] memory assignedRoles);
/// @dev Returns true if the given role id is assigned to a member.
/// @param _memberAddress Address of member
/// @param _roleId Checks member's authenticity with the roleId.
/// i.e. Returns true if this roleId is assigned to member
function checkRole(address _memberAddress, uint _roleId) public view returns(bool);
}
// File: contracts/external/proxy/Proxy.sol
pragma solidity 0.5.7;
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
contract Proxy {
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
function () external payable {
address _impl = implementation();
require(_impl != address(0));
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) }
}
}
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() public view returns (address);
}
// File: contracts/external/proxy/UpgradeabilityProxy.sol
pragma solidity 0.5.7;
/**
* @title UpgradeabilityProxy
* @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded
*/
contract UpgradeabilityProxy is Proxy {
/**
* @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);
// Storage position of the address of the current implementation
bytes32 private constant IMPLEMENTATION_POSITION = keccak256("org.govblocks.proxy.implementation");
/**
* @dev Constructor function
*/
constructor() public {}
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public view returns (address impl) {
bytes32 position = IMPLEMENTATION_POSITION;
assembly {
impl := sload(position)
}
}
/**
* @dev Sets the address of the current implementation
* @param _newImplementation address representing the new implementation to be set
*/
function _setImplementation(address _newImplementation) internal {
bytes32 position = IMPLEMENTATION_POSITION;
assembly {
sstore(position, _newImplementation)
}
}
/**
* @dev Upgrades the implementation address
* @param _newImplementation representing the address of the new implementation to be set
*/
function _upgradeTo(address _newImplementation) internal {
address currentImplementation = implementation();
require(currentImplementation != _newImplementation);
_setImplementation(_newImplementation);
emit Upgraded(_newImplementation);
}
}
// File: contracts/external/proxy/OwnedUpgradeabilityProxy.sol
pragma solidity 0.5.7;
/**
* @title OwnedUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with basic authorization control functionalities
*/
contract OwnedUpgradeabilityProxy is UpgradeabilityProxy {
/**
* @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);
// Storage position of the owner of the contract
bytes32 private constant PROXY_OWNER_POSITION = keccak256("org.govblocks.proxy.owner");
/**
* @dev the constructor sets the original owner of the contract to the sender account.
*/
constructor(address _implementation) public {
_setUpgradeabilityOwner(msg.sender);
_upgradeTo(_implementation);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner());
_;
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function proxyOwner() public view returns (address owner) {
bytes32 position = PROXY_OWNER_POSITION;
assembly {
owner := sload(position)
}
}
/**
* @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));
_setUpgradeabilityOwner(_newOwner);
emit ProxyOwnershipTransferred(proxyOwner(), _newOwner);
}
/**
* @dev Allows the proxy owner to upgrade the current version of the proxy.
* @param _implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address _implementation) public onlyProxyOwner {
_upgradeTo(_implementation);
}
/**
* @dev Sets the address of the owner
*/
function _setUpgradeabilityOwner(address _newProxyOwner) internal {
bytes32 position = PROXY_OWNER_POSITION;
assembly {
sstore(position, _newProxyOwner)
}
}
}
// File: contracts/external/govblocks-protocol/Governed.sol
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract IMaster {
mapping(address => bool) public whitelistedSponsor;
function dAppToken() public view returns(address);
function isInternal(address _address) public view returns(bool);
function getLatestAddress(bytes2 _module) public view returns(address);
function isAuthorizedToGovern(address _toCheck) public view returns(bool);
}
contract Governed {
address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract
/// @dev modifier that allows only the authorized addresses to execute the function
modifier onlyAuthorizedToGovern() {
IMaster ms = IMaster(masterAddress);
require(ms.getLatestAddress("GV") == msg.sender, "Not authorized");
_;
}
/// @dev checks if an address is authorized to govern
function isAuthorizedToGovern(address _toCheck) public view returns(bool) {
IMaster ms = IMaster(masterAddress);
return (ms.getLatestAddress("GV") == _toCheck);
}
}
// File: contracts/interfaces/Iupgradable.sol
pragma solidity 0.5.7;
contract Iupgradable {
/**
* @dev change master address
*/
function setMasterAddress() public;
}
// File: contracts/ProposalCategory.sol
/* Copyright (C) 2020 PlotX.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity 0.5.7;
contract ProposalCategory is Governed, IProposalCategory, Iupgradable {
bool public constructorCheck;
IMemberRoles internal mr;
struct CategoryStruct {
uint256 memberRoleToVote;
uint256 majorityVotePerc;
uint256 quorumPerc;
uint256[] allowedToCreateProposal;
uint256 closingTime;
uint256 minStake;
}
struct CategoryAction {
uint256 defaultIncentive;
address contractAddress;
bytes2 contractName;
}
CategoryStruct[] internal allCategory;
mapping(uint256 => CategoryAction) internal categoryActionData;
mapping(uint256 => bytes) public categoryActionHashes;
bool public initiated;
/**
* @dev Initiates Default settings for Proposal Category contract (Adding default categories)
*/
function proposalCategoryInitiate() external {
//solhint-disable-line
require(!initiated, "Category action hashes already updated");
initiated = true;
uint256 advisoryBoardRole = uint256(IMemberRoles.Role.AdvisoryBoard);
uint256 tokenHolder = uint256(IMemberRoles.Role.TokenHolder);
uint256 disputeResolutionBoard = uint256(IMemberRoles.Role.DisputeResolution);
_addInitialCategories("Uncategorized", "", "EX", "", 0, 0);
_addInitialCategories(
"Add new member role",
"QmQFnBep7AyMYU3LJDuHSpTYatnw65XjHzzirrghtZoR8U",
"MR",
"addRole(bytes32,string,address)",
50,
advisoryBoardRole
); //1
_addInitialCategories(
"Update member role",
"QmXMzSViLBJ22P9oj51Zz7isKTRnXWPHZcQ5hzGvvWD3UV",
"MR",
"updateRole(address,uint256,bool)",
50,
advisoryBoardRole
); // 2
_addInitialCategories(
"Add new category",
"QmaVtv7NDR36X2ZEBjCmh1ny4UXKYSHPMfg8peuPLnNc3f",
"PC",
"newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)",
50,
advisoryBoardRole
); // 3
_addInitialCategories(
"Edit category",
"QmdmQhGo6hU5HzrNLuoyq2TUh1N3DQ7pT2SkPUhZvnsBYZ",
"PC",
"editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)",
50,
advisoryBoardRole
); //4
_addInitialCategories(
"Update Market Implementations",
"QmbyrHnGgTU9WWFq7DgtRTdpExLg9MqcFRYpWNpo7Ezjd5",
"PL",
"updateMarketImplementations(uint256[],address[])",
60,
tokenHolder
); // 5
_addInitialCategories(
"Update contract's Implementation",
"QmesiuX929bJHmgH8E58L6FWPazcLdgcdjmFzinEdsMfre",
"PL",
"upgradeContractImplementation(address,address)",
60,
tokenHolder
); // 6
_addInitialCategories(
"Upgrade multiple contract Implementations",
"QmcL1jUk7oda2cumSUTCrF6vTSeQN7qd1bYDFdz3v7BbUH",
"MS",
"upgradeMultipleImplementations(bytes2[],address[])",
50,
tokenHolder
); // 7
_addInitialCategories(
"Update master Implementation",
"QmPrGbWA4cuWzZbc9ZmqFmSRSFJnp5sa747wKsJnQkkj4t",
"MS",
"upgradeTo(address)",
50,
tokenHolder
); // 8
_addInitialCategories(
"Add new contract",
"QmXq5Jb4oeNzD2NHBLuWqy2m9J4N1KtkwyirBjkPBRNHii",
"MS",
"addNewContract(bytes2,address)",
50,
tokenHolder
);
_addInitialCategories(
"Raise Dispute",
"QmQLKazba2dL8nTtGaoon6DsPv5FcpKqWZPRdxLv2tfUQW",
"PL",
"resolveDispute(address,uint256)",
60,
disputeResolutionBoard
);
_addInitialCategories(
"Burn Dispute Resolution Member Tokens",
"QmTV2xSz5R5LVi9VozCyvNgnguq6xEsfVx7JaFbSatVVvQ",
"TC",
"burnLockedTokens(address,bytes32,uint256)",
60,
tokenHolder
); //11
_addInitialCategories(
"Swap AB member",
"QmV5HJMmhkEiHWt5qdNp6AbCqcn9Lw9ASA9efHDKGm8mdh",
"MR",
"swapABMember(address,address)",
60,
tokenHolder
);
_addInitialCategories(
"Update governance parameters",
"QmTzKKxzpp1E4b8N3ch1kumetYRieEpN7ecTd3MNg4V1T9",
"GV",
"updateUintParameters(bytes8,uint256)",
60,
tokenHolder
);
_addInitialCategories(
"Update Token Controller parameters",
"QmdVH5FdXbiGbqsj17643KVEEBQ3ciBZnjn9Mj24ehsrGm",
"TC",
"updateUintParameters(bytes8,uint256)",
60,
tokenHolder
);
_addInitialCategories(
"Add new market type",
"QmPwAdEj6quzB65JWr6hDz6HrLtjTfbezwUiAe6mBq2sxY",
"PL",
"addNewMarketType(uint64,uint64,uint64)",
60,
tokenHolder
); //15
_addInitialCategories(
"Add new market currency",
"QmTu2FnkqUWhhNbeQraSrtbdA4DfGLavTsLRKRCeLV51x1",
"PL",
"addNewMarketCurrency(address,uint64)",
60,
tokenHolder
);
_addInitialCategories(
"Pause Market Creation",
"QmamFs4k5ZbzajipsbWb4LCaKtyxDUwb9U5dYiNFqExb2W",
"PL",
"pauseMarketCreation()",
60,
tokenHolder
);
_addInitialCategories(
"Resume Market Creation",
"QmZ9W1gHTJjSnt3ieiNv1Ux6ooX7ngU4Jrpvk3QiiBeP5r",
"PL",
"resumeMarketCreation()",
60,
tokenHolder
);
_addInitialCategories(
"Transfer Market Registry Assets",
"QmeRCfGJuA6oTqY8a7nuVxdHih2SmZUTaZLVrttGv6yKy5",
"PL",
"transferAssets(address,address,uint256)",
60,
tokenHolder
);
_addInitialCategories(
"Update Market Uint parameters",
"QmXPXBkSKfidTgbDcRBLqokqAa9SU2wwErTyedPAZPfr5z",
"PL",
"updateUintParameters(bytes8,uint256)",
60,
tokenHolder
); //20
_addInitialCategories(
"Update Market Address parameters",
"QmbbNRchZHMULBbKFT8qjCWgCRPa4qdkst8mE8A2Kffy7N",
"PL",
"updateConfigAddressParameters(bytes8,address)",
60,
tokenHolder
);
_addInitialCategories(
"Update Member roles parameters",
"QmcG8KXLMTDL5CtiKed12bJxE4ioL7Wn7oXLdW1zYWpf62",
"MR",
"updateUintParameters(bytes8,uint256)",
60,
tokenHolder
); //22
_addInitialCategories(
"Whitelist Sponsor",
"QmRB2twfkzjox4ZAStnZTvtqr7Tr7ByGVdjTziWnpxXmWw",
"MS",
"whitelistSponsor(address)",
60,
tokenHolder
);
_addInitialCategories(
"Any other item",
"",
"EX",
"",
60,
tokenHolder
);
}
/**
* @dev Gets Total number of categories added till now
*/
function totalCategories() external view returns (uint256) {
return allCategory.length;
}
/**
* @dev Gets category details
*/
function category(uint256 _categoryId)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256[] memory,
uint256,
uint256
)
{
return (
_categoryId,
allCategory[_categoryId].memberRoleToVote,
allCategory[_categoryId].majorityVotePerc,
allCategory[_categoryId].quorumPerc,
allCategory[_categoryId].allowedToCreateProposal,
allCategory[_categoryId].closingTime,
allCategory[_categoryId].minStake
);
}
/**
* @dev Gets the category action details
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
*/
function categoryAction(uint256 _categoryId)
external
view
returns (
uint256,
address,
bytes2,
uint256
)
{
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive
);
}
/**
* @dev Gets the category action details of a category id
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
* @return action function hash
*/
function categoryActionDetails(uint256 _categoryId)
external
view
returns (
uint256,
address,
bytes2,
uint256,
bytes memory
)
{
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive,
categoryActionHashes[_categoryId]
);
}
/**
* @dev Changes the master address and update it's instance
*/
function setMasterAddress() public {
OwnedUpgradeabilityProxy proxy = OwnedUpgradeabilityProxy(
address(uint160(address(this)))
);
require(msg.sender == proxy.proxyOwner(), "Sender is not proxy owner.");
require(masterAddress == address(0), "Master address already set");
masterAddress = msg.sender;
mr = IMemberRoles(IMaster(masterAddress).getLatestAddress("MR"));
}
/**
* @dev Adds new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function newCategory(
string memory _name,
uint256 _memberRoleToVote,
uint256 _majorityVotePerc,
uint256 _quorumPerc,
uint256[] memory _allowedToCreateProposal,
uint256 _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint256[] memory _incentives,
string memory _functionHash
) public onlyAuthorizedToGovern {
require(
_quorumPerc <= 100 && _majorityVotePerc <= 100,
"Invalid percentage"
);
require(
(_contractName == "EX" && _contractAddress == address(0)) ||
bytes(_functionHash).length > 0,
"Wrong parameters passed"
);
_addCategory(
_name,
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_actionHash,
_contractAddress,
_contractName,
_incentives
);
bytes memory _encodedHash = abi.encodeWithSignature(_functionHash);
if (
bytes(_functionHash).length > 0 &&
_encodedHash.length == 4
) {
if(keccak256(_encodedHash) == keccak256(abi.encodeWithSignature("resolveDispute(address,uint256)"))) {
require(_memberRoleToVote == uint256(IMemberRoles.Role.DisputeResolution));
}
categoryActionHashes[allCategory.length - 1] = _encodedHash;
}
}
/**
* @dev Updates category details
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function editCategory(
uint256 _categoryId,
string memory _name,
uint256 _memberRoleToVote,
uint256 _majorityVotePerc,
uint256 _quorumPerc,
uint256[] memory _allowedToCreateProposal,
uint256 _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint256[] memory _incentives,
string memory _functionHash
) public onlyAuthorizedToGovern {
require(
_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal),
"Invalid Role"
);
require(
_quorumPerc <= 100 && _majorityVotePerc <= 100,
"Invalid percentage"
);
require(
(_contractName == "EX" && _contractAddress == address(0)) ||
bytes(_functionHash).length > 0,
"Wrong parameters passed"
);
delete categoryActionHashes[_categoryId];
if (
bytes(_functionHash).length > 0 &&
abi.encodeWithSignature(_functionHash).length == 4
) {
if(keccak256(abi.encodeWithSignature(_functionHash)) == keccak256(abi.encodeWithSignature("resolveDispute(address,uint256)"))) {
require(_memberRoleToVote == uint256(IMemberRoles.Role.DisputeResolution));
}
categoryActionHashes[_categoryId] = abi.encodeWithSignature(
_functionHash
);
}
allCategory[_categoryId].memberRoleToVote = _memberRoleToVote;
allCategory[_categoryId].majorityVotePerc = _majorityVotePerc;
allCategory[_categoryId].closingTime = _closingTime;
allCategory[_categoryId]
.allowedToCreateProposal = _allowedToCreateProposal;
allCategory[_categoryId].minStake = _incentives[0];
allCategory[_categoryId].quorumPerc = _quorumPerc;
categoryActionData[_categoryId].defaultIncentive = _incentives[1];
categoryActionData[_categoryId].contractName = _contractName;
categoryActionData[_categoryId].contractAddress = _contractAddress;
emit Category(_categoryId, _name, _actionHash);
}
/**
* @dev Internal call to add new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function _addCategory(
string memory _name,
uint256 _memberRoleToVote,
uint256 _majorityVotePerc,
uint256 _quorumPerc,
uint256[] memory _allowedToCreateProposal,
uint256 _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint256[] memory _incentives
) internal {
require(
_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal),
"Invalid Role"
);
allCategory.push(
CategoryStruct(
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_incentives[0]
)
);
uint256 categoryId = allCategory.length - 1;
categoryActionData[categoryId] = CategoryAction(
_incentives[1],
_contractAddress,
_contractName
);
emit Category(categoryId, _name, _actionHash);
}
/**
* @dev Internal call to check if given roles are valid or not
*/
function _verifyMemberRoles(
uint256 _memberRoleToVote,
uint256[] memory _allowedToCreateProposal
) internal view returns (bool) {
uint256 totalRoles = mr.totalRoles();
if (_memberRoleToVote >= totalRoles) {
return false;
}
for (uint256 i = 0; i < _allowedToCreateProposal.length; i++) {
if (_allowedToCreateProposal[i] >= totalRoles) {
return false;
}
}
return true;
}
/**
* @dev to add the initial categories
* @param _name is category name
* @param _actionHash hash of category action
* @param _contractName is the name of contract
* @param _majorityVotePerc percentage of majority vote
* @param _memberRoleToVote is the member role the category can vote on
*/
function _addInitialCategories(
string memory _name,
string memory _solutionHash,
bytes2 _contractName,
string memory _actionHash,
uint256 _majorityVotePerc,
uint256 _memberRoleToVote
) internal {
uint256[] memory allowedToCreateProposal = new uint256[](1);
uint256[] memory stakeIncentive = new uint256[](2);
uint256 closingTime = 3 days;
allowedToCreateProposal[0] = _memberRoleToVote;
stakeIncentive[0] = 0;
stakeIncentive[1] = 0;
if (_memberRoleToVote == uint256(IMemberRoles.Role.DisputeResolution)) {
stakeIncentive[1] = 100 ether;
allowedToCreateProposal[0] = uint256(IMemberRoles.Role.TokenHolder);
closingTime = 2 days;
}
if (bytes(_actionHash).length > 0) {
categoryActionHashes[allCategory.length] = abi.encodeWithSignature(
_actionHash
);
}
_addCategory(
_name,
_memberRoleToVote,
_majorityVotePerc,
10,
allowedToCreateProposal,
closingTime,
_solutionHash,
address(0),
_contractName,
stakeIncentive
);
}
}
|
Changes the master address and update it's instance/
|
function setMasterAddress() public {
OwnedUpgradeabilityProxy proxy = OwnedUpgradeabilityProxy(
address(uint160(address(this)))
);
require(msg.sender == proxy.proxyOwner(), "Sender is not proxy owner.");
require(masterAddress == address(0), "Master address already set");
masterAddress = msg.sender;
mr = IMemberRoles(IMaster(masterAddress).getLatestAddress("MR"));
}
| 14,744,350
|
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.7;
/*
██████ ██████ ██ ██ ███ ██ ██████
██ ██ ██ ██ ██ ████ ██ ██ ██
███████ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
███████ ██████ ██████ ██ ████ ██████
*/
import {IERC2981Upgradeable, IERC165Upgradeable} from '@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol';
import {ERC721Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol';
import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import {LibUintToString} from './LibUintToString.sol';
import {CountersUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol';
import {ArtistCreator} from './ArtistCreator.sol';
import {ECDSA} from '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
/// @title Artist
/// @author SoundXYZ - @gigamesh & @vigneshka
/// @notice This contract is used to create & sell song NFTs for the artist who owns the contract.
/// @dev Started as a fork of Mirror's Editions.sol https://github.com/mirror-xyz/editions-v1/blob/main/contracts/Editions.sol
contract ArtistV3 is ERC721Upgradeable, IERC2981Upgradeable, OwnableUpgradeable {
// ================================
// TYPES
// ================================
using LibUintToString for uint256;
using CountersUpgradeable for CountersUpgradeable.Counter;
using ECDSA for bytes32;
enum TimeType {
START,
END
}
// ============ Structs ============
struct Edition {
// The account that will receive sales revenue.
address payable fundingRecipient;
// The price at which each token will be sold, in ETH.
uint256 price;
// The number of tokens sold so far.
uint32 numSold;
// The maximum number of tokens that can be sold.
uint32 quantity;
// Royalty amount in bps
uint32 royaltyBPS;
// start timestamp of auction (in seconds since unix epoch)
uint32 startTime;
// end timestamp of auction (in seconds since unix epoch)
uint32 endTime;
// quantity of permissioned tokens
uint32 permissionedQuantity;
// whitelist signer address
address signerAddress;
}
// ================================
// STORAGE
// ================================
string internal baseURI;
CountersUpgradeable.Counter private atTokenId; // DEPRECATED IN V3
CountersUpgradeable.Counter private atEditionId;
// Mapping of edition id to descriptive data.
mapping(uint256 => Edition) public editions;
// <DEPRECATED IN V3> Mapping of token id to edition id.
mapping(uint256 => uint256) private _tokenToEdition;
// The amount of funds that have been deposited for a given edition.
mapping(uint256 => uint256) public depositedForEdition;
// The amount of funds that have already been withdrawn for a given edition.
mapping(uint256 => uint256) public withdrawnForEdition;
// The permissioned typehash (used for checking signature validity)
bytes32 private constant PERMISSIONED_SALE_TYPEHASH =
keccak256('EditionInfo(address contractAddress,address buyerAddress,uint256 editionId)');
bytes32 private immutable DOMAIN_SEPARATOR;
// ================================
// EVENTS
// ================================
event EditionCreated(
uint256 indexed editionId,
address fundingRecipient,
uint256 price,
uint32 quantity,
uint32 royaltyBPS,
uint32 startTime,
uint32 endTime,
uint32 permissionedQuantity,
address signerAddress
);
event EditionPurchased(
uint256 indexed editionId,
uint256 indexed tokenId,
// `numSold` at time of purchase represents the "serial number" of the NFT.
uint32 numSold,
// The account that paid for and received the NFT.
address indexed buyer
);
event AuctionTimeSet(TimeType timeType, uint256 editionId, uint32 indexed newTime);
event SignerAddressSet(uint256 editionId, address indexed signerAddress);
event PermissionedQuantitySet(uint256 editionId, uint32 permissionedQuantity);
// ================================
// PUBLIC & EXTERNAL WRITABLE FUNCTIONS
// ================================
/// @notice Contract constructor
constructor() {
DOMAIN_SEPARATOR = keccak256(abi.encode(keccak256('EIP712Domain(uint256 chainId)'), block.chainid));
}
/// @notice Initializes the contract
/// @param _owner Owner of edition
/// @param _name Name of artist
function initialize(
address _owner,
uint256 _artistId,
string memory _name,
string memory _symbol,
string memory _baseURI
) public initializer {
__ERC721_init(_name, _symbol);
__Ownable_init();
// Set ownership to original sender of contract call
transferOwnership(_owner);
// E.g. https://sound.xyz/api/metadata/[artistId]/
baseURI = string(abi.encodePacked(_baseURI, _artistId.toString(), '/'));
// Set edition id start to be 1 not 0
atEditionId.increment();
}
/// @notice Creates a new edition.
/// @param _fundingRecipient The account that will receive sales revenue.
/// @param _price The price at which each token will be sold, in ETH.
/// @param _quantity The maximum number of tokens that can be sold.
/// @param _royaltyBPS The royalty amount in bps.
/// @param _startTime The start time of the auction, in seconds since unix epoch.
/// @param _endTime The end time of the auction, in seconds since unix epoch.
/// @param _permissionedQuantity The quantity of tokens that require a signature to buy.
/// @param _signerAddress signer address.
function createEdition(
address payable _fundingRecipient,
uint256 _price,
uint32 _quantity,
uint32 _royaltyBPS,
uint32 _startTime,
uint32 _endTime,
uint32 _permissionedQuantity,
address _signerAddress
) external onlyOwner {
require(_permissionedQuantity < _quantity + 1, 'Permissioned quantity too big');
require(_quantity > 0, 'Must set quantity');
require(_fundingRecipient != address(0), 'Must set fundingRecipient');
require(_endTime > _startTime, 'End time must be greater than start time');
if (_permissionedQuantity > 0) {
require(_signerAddress != address(0), 'Signer address cannot be 0');
}
editions[atEditionId.current()] = Edition({
fundingRecipient: _fundingRecipient,
price: _price,
numSold: 0,
quantity: _quantity,
royaltyBPS: _royaltyBPS,
startTime: _startTime,
endTime: _endTime,
permissionedQuantity: _permissionedQuantity,
signerAddress: _signerAddress
});
emit EditionCreated(
atEditionId.current(),
_fundingRecipient,
_price,
_quantity,
_royaltyBPS,
_startTime,
_endTime,
_permissionedQuantity,
_signerAddress
);
atEditionId.increment();
}
/// @notice Creates a new token for the given edition, and assigns it to the buyer
/// @param _editionId The id of the edition to purchase
/// @param _signature A signed message for authorizing permissioned purchases
function buyEdition(uint256 _editionId, bytes calldata _signature) external payable {
// Caching variables locally to reduce reads
uint256 price = editions[_editionId].price;
uint32 quantity = editions[_editionId].quantity;
uint32 numSold = editions[_editionId].numSold;
uint32 startTime = editions[_editionId].startTime;
uint32 endTime = editions[_editionId].endTime;
uint32 permissionedQuantity = editions[_editionId].permissionedQuantity;
// Check that the edition exists. Note: this is redundant
// with the next check, but it is useful for clearer error messaging.
require(quantity > 0, 'Edition does not exist');
// Check that there are still tokens available to purchase.
require(numSold < quantity, 'This edition is already sold out.');
// Check that the sender is paying the correct amount.
require(msg.value >= price, 'Must send enough to purchase the edition.');
// If the open auction hasn't started...
if (startTime > block.timestamp) {
// Check that permissioned tokens are still available
require(
permissionedQuantity > 0 && numSold < permissionedQuantity,
'No permissioned tokens available & open auction not started'
);
// Check that the signature is valid.
require(getSigner(_signature, _editionId) == editions[_editionId].signerAddress, 'Invalid signer');
}
// Don't allow purchases after the end time
require(endTime > block.timestamp, 'Auction has ended');
// Create the token id by packing editionId in the top bits
uint256 tokenId;
unchecked {
tokenId = (_editionId << 128) | (numSold + 1);
// Increment the number of tokens sold for this edition.
editions[_editionId].numSold = numSold + 1;
}
// If fundingRecipient is the owner (artist's wallet), update the edition's balance & don't send the funds
if (editions[_editionId].fundingRecipient == owner()) {
// Update the deposited total for the edition
depositedForEdition[_editionId] += msg.value;
} else {
// Send funds to the funding recipient.
_sendFunds(editions[_editionId].fundingRecipient, msg.value);
}
// Mint a new token for the sender, using the `tokenId`.
_mint(msg.sender, tokenId);
emit EditionPurchased(_editionId, tokenId, editions[_editionId].numSold, msg.sender);
}
function withdrawFunds(uint256 _editionId) external {
// Compute the amount available for withdrawing from this edition.
uint256 remainingForEdition = depositedForEdition[_editionId] - withdrawnForEdition[_editionId];
// Set the amount withdrawn to the amount deposited.
withdrawnForEdition[_editionId] = depositedForEdition[_editionId];
// Send the amount that was remaining for the edition, to the funding recipient.
_sendFunds(editions[_editionId].fundingRecipient, remainingForEdition);
}
/// @notice Sets the start time for an edition
function setStartTime(uint256 _editionId, uint32 _startTime) external onlyOwner {
editions[_editionId].startTime = _startTime;
emit AuctionTimeSet(TimeType.START, _editionId, _startTime);
}
/// @notice Sets the end time for an edition
function setEndTime(uint256 _editionId, uint32 _endTime) external onlyOwner {
editions[_editionId].endTime = _endTime;
emit AuctionTimeSet(TimeType.END, _editionId, _endTime);
}
/// @notice Sets the signature address of an edition
function setSignerAddress(uint256 _editionId, address _newSignerAddress) external onlyOwner {
require(_newSignerAddress != address(0), 'Signer address cannot be 0');
editions[_editionId].signerAddress = _newSignerAddress;
emit SignerAddressSet(_editionId, _newSignerAddress);
}
/// @notice Sets the permissioned quantity for an edition
function setPermissionedQuantity(uint256 _editionId, uint32 _permissionedQuantity) external onlyOwner {
// Check that the permissioned quantity is less than the total quantity
require(_permissionedQuantity < editions[_editionId].quantity + 1, 'Must not exceed quantity');
// Prevent setting to permissioned quantity when there is no signer address
require(editions[_editionId].signerAddress != address(0), 'Edition must have a signer');
editions[_editionId].permissionedQuantity = _permissionedQuantity;
emit PermissionedQuantitySet(_editionId, _permissionedQuantity);
}
// ================================
// VIEW FUNCTIONS
// ================================
/// @notice Returns token URI (metadata URL). e.g. https://sound.xyz/api/metadata/[artistId]/[editionId]/[tokenId]
/// @dev Concatenate the baseURI, editionId and tokenId, to create URI.
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token');
uint256 editionId = tokenToEdition(_tokenId);
return string(abi.encodePacked(baseURI, editionId.toString(), '/', _tokenId.toString()));
}
/// @notice Returns contract URI used by Opensea. e.g. https://sound.xyz/api/metadata/[artistId]/storefront
function contractURI() public view returns (string memory) {
return string(abi.encodePacked(baseURI, 'storefront'));
}
/// @notice Get royalty information for token
/// @param _tokenId token id
/// @param _salePrice Sale price for the token
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
override
returns (address fundingRecipient, uint256 royaltyAmount)
{
uint256 editionId = tokenToEdition(_tokenId);
Edition memory edition = editions[editionId];
if (edition.fundingRecipient == address(0x0)) {
return (edition.fundingRecipient, 0);
}
uint256 royaltyBPS = uint256(edition.royaltyBPS);
return (edition.fundingRecipient, (_salePrice * royaltyBPS) / 10_000);
}
/// @notice The total number of tokens created by this contract
function totalSupply() external view returns (uint256) {
uint256 total = 0;
for (uint256 id = 1; id < atEditionId.current(); id++) {
total += editions[id].numSold;
}
return total;
}
/// @notice Informs other contracts which interfaces this contract supports
/// @dev https://eips.ethereum.org/EIPS/eip-165
function supportsInterface(bytes4 _interfaceId)
public
view
override(ERC721Upgradeable, IERC165Upgradeable)
returns (bool)
{
return
type(IERC2981Upgradeable).interfaceId == _interfaceId || ERC721Upgradeable.supportsInterface(_interfaceId);
}
/// @notice returns the number of editions for this artist
function editionCount() external view returns (uint256) {
return atEditionId.current() - 1; // because atEditionId is incremented after each edition is created
}
function tokenToEdition(uint256 _tokenId) public view returns (uint256) {
// Check the top bits to see if the edition id is there
uint256 editionId = _tokenId >> 128;
// If edition ID is 0, then this edition was created before the V3 upgrade
if (editionId == 0) {
// get edition ID from storage
return _tokenToEdition[_tokenId];
}
return editionId;
}
function ownersOfTokenIds(uint256[] calldata _tokenIds) external view returns (address[] memory) {
address[] memory owners = new address[](_tokenIds.length);
for (uint256 i = 0; i < _tokenIds.length; i++) {
owners[i] = ownerOf(_tokenIds[i]);
}
return owners;
}
// ================================
// FUNCTIONS - PRIVATE
// ================================
/// @notice Sends funds to an address
/// @param _recipient The address to send funds to
/// @param _amount The amount of funds to send
function _sendFunds(address payable _recipient, uint256 _amount) private {
require(address(this).balance >= _amount, 'Insufficient balance for send');
(bool success, ) = _recipient.call{value: _amount}('');
require(success, 'Unable to send value: recipient may have reverted');
}
/// @notice Gets signer address to validate permissioned purchase
/// @param _signature signed message
/// @param _editionId edition id
/// @return address of signer
/// @dev https://eips.ethereum.org/EIPS/eip-712
function getSigner(bytes calldata _signature, uint256 _editionId) private view returns (address) {
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMISSIONED_SALE_TYPEHASH, address(this), msg.sender, _editionId))
)
);
address recoveredAddress = digest.recover(_signature);
return recoveredAddress;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981Upgradeable is IERC165Upgradeable {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
library LibUintToString {
uint256 private constant MAX_UINT256_STRING_LENGTH = 78;
uint8 private constant ASCII_DIGIT_OFFSET = 48;
/// @dev Converts a `uint256` value to a string.
/// @param n The integer to convert.
/// @return nstr `n` as a decimal string.
function toString(uint256 n) internal pure returns (string memory nstr) {
if (n == 0) {
return '0';
}
// Overallocate memory
nstr = new string(MAX_UINT256_STRING_LENGTH);
uint256 k = MAX_UINT256_STRING_LENGTH;
// Populate string from right to left (lsb to msb).
while (n != 0) {
assembly {
let char := add(ASCII_DIGIT_OFFSET, mod(n, 10))
mstore(add(nstr, k), char)
k := sub(k, 1)
n := div(n, 10)
}
}
assembly {
// Shift pointer over to actual start of string.
nstr := add(nstr, k)
// Store actual string length.
mstore(nstr, sub(MAX_UINT256_STRING_LENGTH, k))
}
return nstr;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.7;
/*
██████ ██████ ██ ██ ███ ██ ██████
██ ██ ██ ██ ██ ████ ██ ██ ██
███████ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
███████ ██████ ██████ ██ ████ ██████
*/
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
import '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol';
import '@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol';
import '@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol';
import './Artist.sol';
contract ArtistCreator is Initializable, UUPSUpgradeable, OwnableUpgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
using ECDSAUpgradeable for bytes32;
// ============ Storage ============
bytes32 public constant MINTER_TYPEHASH = keccak256('Deployer(address artistWallet)');
CountersUpgradeable.Counter private atArtistId;
// address used for signature verification, changeable by owner
address public admin;
bytes32 public DOMAIN_SEPARATOR;
address public beaconAddress;
// registry of created contracts
address[] public artistContracts;
// ============ Events ============
/// Emitted when an Artist is created
event CreatedArtist(uint256 artistId, string name, string symbol, address indexed artistAddress);
// ============ Functions ============
/// Initializes factory
function initialize() public initializer {
__Ownable_init_unchained();
// set admin for artist deployment authorization
admin = msg.sender;
DOMAIN_SEPARATOR = keccak256(abi.encode(keccak256('EIP712Domain(uint256 chainId)'), block.chainid));
// set up beacon with msg.sender as the owner
UpgradeableBeacon _beacon = new UpgradeableBeacon(address(new Artist()));
_beacon.transferOwnership(msg.sender);
beaconAddress = address(_beacon);
// Set artist id start to be 1 not 0
atArtistId.increment();
}
/// Creates a new artist contract as a factory with a deterministic address
/// Important: None of these fields (except the Url fields with the same hash) can be changed after calling
/// @param _name Name of the artist
function createArtist(
bytes calldata signature,
string memory _name,
string memory _symbol,
string memory _baseURI
) public returns (address) {
require((getSigner(signature) == admin), 'invalid authorization signature');
BeaconProxy proxy = new BeaconProxy(
beaconAddress,
abi.encodeWithSelector(
Artist(address(0)).initialize.selector,
msg.sender,
atArtistId.current(),
_name,
_symbol,
_baseURI
)
);
// add to registry
artistContracts.push(address(proxy));
emit CreatedArtist(atArtistId.current(), _name, _symbol, address(proxy));
atArtistId.increment();
return address(proxy);
}
/// Get signer address of signature
function getSigner(bytes calldata signature) public view returns (address) {
require(admin != address(0), 'whitelist not enabled');
// Verify EIP-712 signature by recreating the data structure
// that we signed on the client side, and then using that to recover
// the address that signed the signature for this data.
bytes32 digest = keccak256(
abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(MINTER_TYPEHASH, msg.sender)))
);
// Use the recover method to see what address was used to create
// the signature on this data.
// Note that if the digest doesn't exactly match what was signed we'll
// get a random recovered address.
address recoveredAddress = digest.recover(signature);
return recoveredAddress;
}
/// Sets the admin for authorizing artist deployment
/// @param _newAdmin address of new admin
function setAdmin(address _newAdmin) external {
require(owner() == _msgSender() || admin == _msgSender(), 'invalid authorization');
admin = _newAdmin;
}
function _authorizeUpgrade(address) internal override onlyOwner {}
}
// 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 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165Upgradeable.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.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 ECDSAUpgradeable {
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", StringsUpgradeable.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 (proxy/beacon/BeaconProxy.sol)
pragma solidity ^0.8.0;
import "./IBeacon.sol";
import "../Proxy.sol";
import "../ERC1967/ERC1967Upgrade.sol";
/**
* @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}.
*
* The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't
* conflict with the storage layout of the implementation behind the proxy.
*
* _Available since v3.4._
*/
contract BeaconProxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the proxy with `beacon`.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
* will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity
* constructor.
*
* Requirements:
*
* - `beacon` must be a contract with the interface {IBeacon}.
*/
constructor(address beacon, bytes memory data) payable {
assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1));
_upgradeBeaconToAndCall(beacon, data, false);
}
/**
* @dev Returns the current beacon address.
*/
function _beacon() internal view virtual returns (address) {
return _getBeacon();
}
/**
* @dev Returns the current implementation address of the associated beacon.
*/
function _implementation() internal view virtual override returns (address) {
return IBeacon(_getBeacon()).implementation();
}
/**
* @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.
*
* Requirements:
*
* - `beacon` must be a contract.
* - The implementation returned by `beacon` must be a contract.
*/
function _setBeacon(address beacon, bytes memory data) internal virtual {
_upgradeBeaconToAndCall(beacon, data, false);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol)
pragma solidity ^0.8.0;
import "./IBeacon.sol";
import "../../access/Ownable.sol";
import "../../utils/Address.sol";
/**
* @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their
* implementation contract, which is where they will delegate all function calls.
*
* An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.
*/
contract UpgradeableBeacon is IBeacon, Ownable {
address private _implementation;
/**
* @dev Emitted when the implementation returned by the beacon is changed.
*/
event Upgraded(address indexed implementation);
/**
* @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the
* beacon.
*/
constructor(address implementation_) {
_setImplementation(implementation_);
}
/**
* @dev Returns the current implementation address.
*/
function implementation() public view virtual override returns (address) {
return _implementation;
}
/**
* @dev Upgrades the beacon to a new implementation.
*
* Emits an {Upgraded} event.
*
* Requirements:
*
* - msg.sender must be the owner of the contract.
* - `newImplementation` must be a contract.
*/
function upgradeTo(address newImplementation) public virtual onlyOwner {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation contract address for this beacon
*
* Requirements:
*
* - `newImplementation` must be a contract.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract");
_implementation = newImplementation;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.7;
/*
██████ ██████ ██ ██ ███ ██ ██████
██ ██ ██ ██ ██ ████ ██ ██ ██
███████ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
███████ ██████ ██████ ██ ████ ██████
*/
import {IERC2981Upgradeable, IERC165Upgradeable} from '@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol';
import {ERC721Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol';
import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import {Strings} from './Strings.sol';
import {CountersUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol';
// This contract is a combination of Mirror.xyz's Editions.sol and Zora's SingleEditionMintable.sol
/**
* @title Artist
* @author SoundXYZ
*/
contract Artist is ERC721Upgradeable, IERC2981Upgradeable, OwnableUpgradeable {
// todo (optimization): link Strings as a deployed library
using Strings for uint256;
using CountersUpgradeable for CountersUpgradeable.Counter;
// ============ Structs ============
struct Edition {
// The account that will receive sales revenue.
address payable fundingRecipient;
// The price at which each token will be sold, in ETH.
uint256 price;
// The number of tokens sold so far.
uint32 numSold;
// The maximum number of tokens that can be sold.
uint32 quantity;
// Royalty amount in bps
uint32 royaltyBPS;
// start timestamp of auction (in seconds since unix epoch)
uint32 startTime;
// end timestamp of auction (in seconds since unix epoch)
uint32 endTime;
}
// ============ Storage ============
string internal baseURI;
CountersUpgradeable.Counter private atTokenId;
CountersUpgradeable.Counter private atEditionId;
// Mapping of edition id to descriptive data.
mapping(uint256 => Edition) public editions;
// Mapping of token id to edition id.
mapping(uint256 => uint256) public tokenToEdition;
// The amount of funds that have been deposited for a given edition.
mapping(uint256 => uint256) public depositedForEdition;
// The amount of funds that have already been withdrawn for a given edition.
mapping(uint256 => uint256) public withdrawnForEdition;
// ============ Events ============
event EditionCreated(
uint256 indexed editionId,
address fundingRecipient,
uint256 price,
uint32 quantity,
uint32 royaltyBPS,
uint32 startTime,
uint32 endTime
);
event EditionPurchased(
uint256 indexed editionId,
uint256 indexed tokenId,
// `numSold` at time of purchase represents the "serial number" of the NFT.
uint32 numSold,
// The account that paid for and received the NFT.
address indexed buyer
);
// ============ Methods ============
/**
@param _owner Owner of edition
@param _name Name of artist
*/
function initialize(
address _owner,
uint256 _artistId,
string memory _name,
string memory _symbol,
string memory _baseURI
) public initializer {
__ERC721_init(_name, _symbol);
__Ownable_init();
// Set ownership to original sender of contract call
transferOwnership(_owner);
// E.g. https://sound.xyz/api/metadata/[artistId]/
baseURI = string(abi.encodePacked(_baseURI, _artistId.toString(), '/'));
// Set token id start to be 1 not 0
atTokenId.increment();
// Set edition id start to be 1 not 0
atEditionId.increment();
}
function createEdition(
address payable _fundingRecipient,
uint256 _price,
uint32 _quantity,
uint32 _royaltyBPS,
uint32 _startTime,
uint32 _endTime
) external onlyOwner {
editions[atEditionId.current()] = Edition({
fundingRecipient: _fundingRecipient,
price: _price,
numSold: 0,
quantity: _quantity,
royaltyBPS: _royaltyBPS,
startTime: _startTime,
endTime: _endTime
});
emit EditionCreated(
atEditionId.current(),
_fundingRecipient,
_price,
_quantity,
_royaltyBPS,
_startTime,
_endTime
);
atEditionId.increment();
}
function buyEdition(uint256 _editionId) external payable {
// Check that the edition exists. Note: this is redundant
// with the next check, but it is useful for clearer error messaging.
require(editions[_editionId].quantity > 0, 'Edition does not exist');
// Check that there are still tokens available to purchase.
require(editions[_editionId].numSold < editions[_editionId].quantity, 'This edition is already sold out.');
// Check that the sender is paying the correct amount.
require(msg.value >= editions[_editionId].price, 'Must send enough to purchase the edition.');
// Don't allow purchases before the start time
require(editions[_editionId].startTime < block.timestamp, "Auction hasn't started");
// Don't allow purchases after the end time
require(editions[_editionId].endTime > block.timestamp, 'Auction has ended');
// Mint a new token for the sender, using the `tokenId`.
_mint(msg.sender, atTokenId.current());
// Update the deposited total for the edition
depositedForEdition[_editionId] += msg.value;
// Increment the number of tokens sold for this edition.
editions[_editionId].numSold++;
// Store the mapping of token id to the edition being purchased.
tokenToEdition[atTokenId.current()] = _editionId;
emit EditionPurchased(_editionId, atTokenId.current(), editions[_editionId].numSold, msg.sender);
atTokenId.increment();
}
// ============ Operational Methods ============
function withdrawFunds(uint256 _editionId) external {
// Compute the amount available for withdrawing from this edition.
uint256 remainingForEdition = depositedForEdition[_editionId] - withdrawnForEdition[_editionId];
// Set the amount withdrawn to the amount deposited.
withdrawnForEdition[_editionId] = depositedForEdition[_editionId];
// Send the amount that was remaining for the edition, to the funding recipient.
_sendFunds(editions[_editionId].fundingRecipient, remainingForEdition);
}
function setStartTime(uint256 _editionId, uint32 _startTime) external onlyOwner {
editions[_editionId].startTime = _startTime;
}
function setEndTime(uint256 _editionId, uint32 _endTime) external onlyOwner {
editions[_editionId].endTime = _endTime;
}
// ============ NFT Methods ============
// Returns e.g. https://sound.xyz/api/metadata/[artistId]/[editionId]/[tokenId]
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token');
// Concatenate the components, baseURI, editionId and tokenId, to create URI.
return string(abi.encodePacked(baseURI, tokenToEdition[_tokenId].toString(), '/', _tokenId.toString()));
}
// Returns e.g. https://sound.xyz/api/metadata/[artistId]/storefront
function contractURI() public view returns (string memory) {
// Concatenate the components, baseURI, editionId and tokenId, to create URI.
return string(abi.encodePacked(baseURI, 'storefront'));
}
// ============ Extensions =================
/**
@dev Get token ids for a given edition id
@param _editionId edition id
*/
function getTokenIdsOfEdition(uint256 _editionId) public view returns (uint256[] memory) {
uint256[] memory tokenIdsOfEdition = new uint256[](editions[_editionId].numSold);
uint256 index = 0;
for (uint256 id = 1; id < atTokenId.current(); id++) {
if (tokenToEdition[id] == _editionId) {
tokenIdsOfEdition[index] = id;
index++;
}
}
return tokenIdsOfEdition;
}
/**
@dev Get owners of a given edition id
@param _editionId edition id
*/
function getOwnersOfEdition(uint256 _editionId) public view returns (address[] memory) {
address[] memory ownersOfEdition = new address[](editions[_editionId].numSold);
uint256 index = 0;
for (uint256 id = 1; id < atTokenId.current(); id++) {
if (tokenToEdition[id] == _editionId) {
ownersOfEdition[index] = ERC721Upgradeable.ownerOf(id);
index++;
}
}
return ownersOfEdition;
}
/**
@dev Get royalty information for token
@param _editionId edition id
@param _salePrice Sale price for the token
*/
function royaltyInfo(uint256 _editionId, uint256 _salePrice)
external
view
override
returns (address fundingRecipient, uint256 royaltyAmount)
{
Edition memory edition = editions[_editionId];
if (edition.fundingRecipient == address(0x0)) {
return (edition.fundingRecipient, 0);
}
uint256 royaltyBPS = uint256(edition.royaltyBPS);
return (edition.fundingRecipient, (_salePrice * royaltyBPS) / 10_000);
}
function totalSupply() external view returns (uint256) {
return atTokenId.current() - 1; // because atTokenId is 1-indexed
}
function supportsInterface(bytes4 _interfaceId)
public
view
override(ERC721Upgradeable, IERC165Upgradeable)
returns (bool)
{
return
type(IERC2981Upgradeable).interfaceId == _interfaceId || ERC721Upgradeable.supportsInterface(_interfaceId);
}
// ============ Private Methods ============
function _sendFunds(address payable _recipient, uint256 _amount) private {
require(address(this).balance >= _amount, 'Insufficient balance for send');
(bool success, ) = _recipient.call{value: _amount}('');
require(success, 'Unable to send value: recipient may have reverted');
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
Address.functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
// 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/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.7;
// This contract is a combination of Mirror.xyz's Editions.sol and Zora's SingleEditionMintable.sol
/**
* @title Utils
* @author SoundXYZ
*/
library Strings {
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol
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);
}
}
// 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);
}
}
|
Returns token URI (metadata URL). e.g. https://sound.xyz/api/metadata/[artistId]/[editionId]/[tokenId] Concatenate the baseURI, editionId and tokenId, to create URI.
|
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token');
uint256 editionId = tokenToEdition(_tokenId);
return string(abi.encodePacked(baseURI, editionId.toString(), '/', _tokenId.toString()));
}
| 5,724,107
|
./partial_match/1/0xd27c12d2b7749280057592BF03eC2a63158F4716/sources/contracts/MMPRESALE.sol
|
To update the payout address _id Presale id to update _newAddress payout address/
|
function changePayoutAddress(uint256 _id, address _newAddress) external checkPresaleId(_id) onlyOwner {
require(_newAddress != address(0), "Zero token address");
address prevValue = presale[_id].payout;
presale[_id].payout = _newAddress;
emit PresalePayoutAddressUpdated(prevValue, _newAddress, block.timestamp);
}
| 4,151,573
|
pragma solidity >=0.4.22 <0.6.0;
//-----------------------------------------------------------------------------
/// @title Ownable
/// @dev The Ownable contract has an owner address, and provides basic
/// authorization control functions, this simplifies the implementation of
/// "user permissions".
//-----------------------------------------------------------------------------
contract Ownable {
//-------------------------------------------------------------------------
/// @dev Emits when owner address changes by any mechanism.
//-------------------------------------------------------------------------
event OwnershipTransfer (address previousOwner, address newOwner);
// Wallet address that can sucessfully execute onlyOwner functions
address owner;
//-------------------------------------------------------------------------
/// @dev Sets the owner of the contract to the sender account.
//-------------------------------------------------------------------------
constructor() public {
owner = msg.sender;
emit OwnershipTransfer(address(0), owner);
}
//-------------------------------------------------------------------------
/// @dev Throws if called by any account other than `owner`.
//-------------------------------------------------------------------------
modifier onlyOwner() {
require(
msg.sender == owner,
"Function can only be called by contract owner"
);
_;
}
//-------------------------------------------------------------------------
/// @notice Transfer control of the contract to a newOwner.
/// @dev Throws if `_newOwner` is zero address.
/// @param _newOwner The address to transfer ownership to.
//-------------------------------------------------------------------------
function transferOwnership(address _newOwner) public onlyOwner {
// for safety, new owner parameter must not be 0
require (
_newOwner != address(0),
"New owner address cannot be zero"
);
// define local variable for old owner
address oldOwner = owner;
// set owner to new owner
owner = _newOwner;
// emit ownership transfer event
emit OwnershipTransfer(oldOwner, _newOwner);
}
}
//-----------------------------------------------------------------------------
/// @title VIP 181 Interface - VIP 181-compliant view functions
//-----------------------------------------------------------------------------
interface VIP181 {
function ownerOf(uint256 _tokenId) external view returns (address);
function getApproved(uint256 _tokenId) external view returns (address);
function isApprovedForAll(
address _owner,
address _operator
) external view returns (bool);
}
interface VIP180 {
function transferFrom(address _from, address _to, uint _tokens) external returns (bool);
}
interface LockedTokenManager {
function lockFrom(
address _tokenHolder,
address _tokenAddress,
uint _tokens,
uint _numberOfMonths
) external returns(bool);
function transferFromAndLock(
address _from,
address _to,
address _tokenAddress,
uint _tokens,
uint _numberOfMonths
) external returns (bool);
}
contract SegmentedTransfer is Ownable {
struct TransferSettings {
uint burnedPercent;
uint lockedPercent;
uint transferredThenLockedPercent;
uint lockedMonths;
}
// Lock contract to interface with
LockedTokenManager public lockContract;
//-------------------------------------------------------------------------
/// @dev Throws if parameter is zero
//-------------------------------------------------------------------------
modifier notZero(uint _param) {
require(_param != 0, "Parameter cannot be zero");
_;
}
//-------------------------------------------------------------------------
/// @notice Set the address of the lock interface to `_lockAddress`.
/// @dev Throws if aacAddress is the zero address.
/// @param _lockAddress The address of the lock interface.
//-------------------------------------------------------------------------
function setLockContract (address _lockAddress)
external
notZero(uint(_lockAddress))
onlyOwner
{
// initialize contract to lockAddress
lockContract = LockedTokenManager(_lockAddress);
}
//-------------------------------------------------------------------------
/// @notice (1)Burn (2)Lock (3)TransferThenLock (4)Transfer
//-------------------------------------------------------------------------
function segmentedTransfer(
address _tokenContractAddress,
address _to,
uint _totalTokens,
TransferSettings storage _transfer
) internal {
uint tokensLeft = _totalTokens;
uint amount;
// burn
if (_transfer.burnedPercent > 0) {
amount = _totalTokens * _transfer.burnedPercent / 100;
VIP180(_tokenContractAddress).transferFrom(msg.sender, address(0), amount);
tokensLeft -= amount;
}
// Lock
if (_transfer.lockedPercent > 0) {
amount = _totalTokens * _transfer.lockedPercent / 100;
lockContract.lockFrom(
msg.sender,
_tokenContractAddress,
_transfer.lockedMonths,
amount
);
tokensLeft -= amount;
}
// Transfer Then Lock
if (_transfer.transferredThenLockedPercent > 0) {
amount = _totalTokens * _transfer.transferredThenLockedPercent / 100;
lockContract.transferFromAndLock(
msg.sender,
address(_to),
_tokenContractAddress,
_transfer.lockedMonths,
amount
);
tokensLeft -= amount;
}
// Transfer
if (tokensLeft > 0) {
VIP180(_tokenContractAddress).transferFrom(msg.sender, _to, tokensLeft);
}
}
}
//-----------------------------------------------------------------------------
/// @title AAC Colored Token Contract
/// @notice defines colored token registration, creation, and spending
/// functionality.
//-----------------------------------------------------------------------------
contract AacColoredTokens is SegmentedTransfer {
//-------------------------------------------------------------------------
/// @dev Emits when a new colored token is created.
//-------------------------------------------------------------------------
event NewColor(address indexed _creator, string _name);
//-------------------------------------------------------------------------
/// @dev Emits when colored tokens are deposited into AACs.
//-------------------------------------------------------------------------
event DepositColor(uint indexed _to, uint indexed _colorIndex, uint _tokens);
//-------------------------------------------------------------------------
/// @dev Emits when colored tokens are spent by any mechanism.
//-------------------------------------------------------------------------
event SpendColor(
uint indexed _from,
uint indexed _color,
uint _amount
);
// Colored token data
struct ColoredToken {
address creator;
string name;
mapping (uint => uint) balances;
mapping (address => uint) depositAllowances;
}
// array containing all colored token data
ColoredToken[] coloredTokens;
// required locked tokens needed to register a color
uint public priceToRegisterColor = 100000 * 10**18;
// AAC contract to interface with
VIP181 public aacContract;
// Contract address whose tokens we accept
address public ehrtAddress;
// transfer percentages for colored token registration
TransferSettings public colorRegistrationTransfer = TransferSettings({
burnedPercent: 50,
lockedPercent: 0,
transferredThenLockedPercent: 0,
lockedMonths: 24
});
// transfer percentages for colored token minting/depositing
TransferSettings public colorDepositTransfer = TransferSettings({
burnedPercent: 50,
lockedPercent: 0,
transferredThenLockedPercent: 0,
lockedMonths: 24
});
uint constant UID_MAX = 0xFFFFFFFFFFFFFF;
//-------------------------------------------------------------------------
/// @notice Set the address of the AAC interface to `_aacAddress`.
/// @dev Throws if aacAddress is the zero address.
/// @param _aacAddress The address of the AAC interface.
//-------------------------------------------------------------------------
function setAacContract (address _aacAddress)
external
notZero(uint(_aacAddress))
onlyOwner
{
// initialize contract to aacAddress
aacContract = VIP181(_aacAddress);
}
//-------------------------------------------------------------------------
/// @notice Set the address of the VIP180 to `_newAddress`.
/// @dev Throws if ehrtAddress is the zero address.
/// @param _newAddress The address of the Eight Hours Token.
//-------------------------------------------------------------------------
function setEhrtContractAddress (address _newAddress)
external
notZero(uint(_newAddress))
onlyOwner
{
// initialize ehrtAddress to new address
ehrtAddress = _newAddress;
}
//-------------------------------------------------------------------------
/// @notice Set required total locked tokens to
/// `(newAmount/1000000000000000000).fixed(0,18)`.
/// @dev Throws if the sender is not the contract owner. Throws if new
/// amount is zero.
/// @param _newAmount The new required locked token amount.
//-------------------------------------------------------------------------
function setPriceToRegisterColor(uint _newAmount)
external
onlyOwner
notZero(_newAmount)
{
priceToRegisterColor = _newAmount;
}
function setTransferSettingsForColoredTokenCreation(
uint _burnPercent,
uint _lockPercent,
uint _transferLockPercent,
uint _lockedMonths
) external onlyOwner {
require(_burnPercent + _lockPercent + _transferLockPercent <= 100);
colorRegistrationTransfer = TransferSettings(
_burnPercent,
_lockPercent,
_transferLockPercent,
_lockedMonths
);
}
function setTransferSettingsForColoredTokenDeposits(
uint _burnPercent,
uint _lockPercent,
uint _transferLockPercent,
uint _lockedMonths
) external onlyOwner {
require(_burnPercent + _lockPercent + _transferLockPercent <= 100);
colorDepositTransfer = TransferSettings(
_burnPercent,
_lockPercent,
_transferLockPercent,
_lockedMonths
);
}
//-------------------------------------------------------------------------
/// @notice Registers `_colorName` as a new colored token. Costs
/// `priceToRegisterColor` tokens.
/// @dev Throws if `msg.sender` has insufficient tokens. Throws if colorName
/// is empty or is longer than 32 characters.
/// @param _colorName The name for the new colored token.
/// @return Index number for the new colored token.
//-------------------------------------------------------------------------
function registerNewColor(string calldata _colorName) external returns (uint) {
// colorName must be a valid length
require (
bytes(_colorName).length > 0 && bytes(_colorName).length < 32,
"Invalid color name length"
);
// send Eight Hours tokens
segmentedTransfer(ehrtAddress, owner, priceToRegisterColor, colorRegistrationTransfer);
// push new colored token to colored token array and store the index
uint index = coloredTokens.push(ColoredToken(msg.sender, _colorName));
return index;
}
//-------------------------------------------------------------------------
/// @notice Allow `_spender` to deposit colored token #`_colorIndex`
/// multiple times, up to `(_tokens/1000000000000000000).fixed(0,18)`.
/// Calling this function overwrites the previous allowance of spender.
/// @param _colorIndex The index of the color to approve.
/// @param _spender The address to authorize as a spender
/// @param _tokens The new token allowance of spender (in wei).
//-------------------------------------------------------------------------
function approve(uint _colorIndex, address _spender, uint _tokens) external {
require(msg.sender == coloredTokens[_colorIndex].creator);
// set the spender's allowance to token amount
coloredTokens[_colorIndex].depositAllowances[_spender] = _tokens;
}
//-------------------------------------------------------------------------
/// @notice Deposits colored tokens with index `colorIndex` into AAC #`uid`.
/// Costs `_tokens` tokens.
/// @dev Throws if tokens to deposit is zero. Throws if colorIndex is
/// greater than number of colored tokens. Throws if `msg.sender` has
/// insufficient balance. Throws if AAC does not have an owner. Throws if
/// sender does not have enough deposit allowance (creator has unlimited).
/// @param _to The Unique Identifier of the AAC receiving tokens.
/// @param _colorIndex The index of the color to deposit.
/// @param _tokens The number of colored tokens to deposit.
//-------------------------------------------------------------------------
function deposit (uint _colorIndex, uint _to, uint _tokens)
external
notZero(_tokens)
{
// colorIndex must be valid color
require (_colorIndex < coloredTokens.length, "Invalid color index");
// sender must be colored token creator
require (
msg.sender == coloredTokens[_colorIndex].creator ||
coloredTokens[_colorIndex].depositAllowances[msg.sender] >= _tokens,
"Not authorized to deposit this color"
);
// If AAC #uid is not owned, it does not exist yet.
require(aacContract.ownerOf(_to) != address(0), "AAC does not exist");
// Initiate spending. Fails if sender's balance is too low.
segmentedTransfer(ehrtAddress, owner, _tokens, colorDepositTransfer);
// add tokens to AAC #UID
coloredTokens[_colorIndex].balances[_to] += _tokens;
// subtract tokens from allowance
if (msg.sender != coloredTokens[_colorIndex].creator) {
coloredTokens[_colorIndex].depositAllowances[msg.sender] -= _tokens;
}
// emit color transfer event
emit DepositColor(_to, _colorIndex, _tokens);
}
//-------------------------------------------------------------------------
/// @notice Deposits colored tokens with index `colorIndex` into multiple
/// AACs. Costs (`_tokens` * number of AACs) tokens.
/// @dev Throws if tokens to deposit is zero. Throws if colorIndex is
/// greater than number of colored tokens. Throws if sender has
/// insufficient balance. Throws if any AAC does not have an owner. Throws
/// if sender does not have enough deposit allowance (creator has unlimited).
/// @param _to The Unique Identifier of the AAC receiving tokens.
/// @param _colorIndex The index of the color to deposit.
/// @param _tokens The number of colored tokens to deposit for each AAC.
//-------------------------------------------------------------------------
function depositBulk (uint _colorIndex, uint[] calldata _to, uint _tokens)
external
notZero(_tokens)
{
// colorIndex must be valid color
require (_colorIndex < coloredTokens.length, "Invalid color index");
// sender must be colored token creator
require (
msg.sender == coloredTokens[_colorIndex].creator ||
coloredTokens[_colorIndex].depositAllowances[msg.sender] > _tokens * _to.length,
"Not authorized to deposit this color"
);
// Initiate lock. Fails if sender's balance is too low.
segmentedTransfer(ehrtAddress, owner, _tokens * _to.length, colorDepositTransfer);
for(uint i = 0; i < _to.length; ++i){
// If AAC #uid is not owned, it does not exist yet.
require(aacContract.ownerOf(_to[i]) != address(0), "AAC does not exist");
// add tokens to AAC #UID
coloredTokens[_colorIndex].balances[_to[i]] += _tokens;
// emit color transfer event
emit DepositColor(_to[i], _colorIndex, _tokens);
}
// subtract tokens from allowance
if (msg.sender != coloredTokens[_colorIndex].creator) {
coloredTokens[_colorIndex].depositAllowances[msg.sender] -= _tokens * _to.length;
}
}
//-------------------------------------------------------------------------
/// @notice Spend `(tokens/1000000000000000000).fixed(0,18)` colored
/// tokens with index `_colorIndex`.
/// @dev Throws if tokens to spend is zero. Throws if colorIndex is
/// greater than number of colored tokens. Throws if AAC with uid#`_from`
/// has insufficient balance to spend.
/// @param _colorIndex The index of the color to spend.
/// @param _from The UID of the AAC to spend from.
/// @param _tokens The number of colored tokens to spend.
/// @return True if spend successful. Throw if unsuccessful.
//-------------------------------------------------------------------------
function spend (uint _colorIndex, uint _from, uint _tokens)
external
notZero(_tokens)
returns(bool)
{
// colorIndex must be valid color
require (_colorIndex < coloredTokens.length, "Invalid color index");
// sender must own AAC
require (
msg.sender == aacContract.ownerOf(_from),
"Sender is not owner of AAC"
);
// token owner's balance must be enough to spend tokens
require (
coloredTokens[_colorIndex].balances[_from] >= _tokens,
"Insufficient tokens to spend"
);
// deduct the tokens from the sender's balance
coloredTokens[_colorIndex].balances[_from] -= _tokens;
// emit spend event
emit SpendColor(_from, _colorIndex, _tokens);
return true;
}
//-------------------------------------------------------------------------
/// @notice Spend `(tokens/1000000000000000000).fixed(0,18)` colored
/// tokens with color index `_colorIndex` from AAC with uid#`_from`.
/// @dev Throws if tokens to spend is zero. Throws if colorIndex is
/// greater than number of colored tokens. Throws if sender is not
/// an authorized operator of AAC. Throws if `from` has insufficient
/// balance to spend.
/// @param _colorIndex The index of the color to spend.
/// @param _from The address whose colored tokens are being spent.
/// @param _tokens The number of tokens to send.
/// @return True if spend successful. Throw if unsuccessful.
//-------------------------------------------------------------------------
function spendFrom(uint _colorIndex, uint _from, uint _tokens)
external
notZero(_tokens)
returns (bool)
{
// colorIndex must be valid color
require (_colorIndex < coloredTokens.length, "Invalid color index");
// sender must be authorized address or operator for AAC
require (
msg.sender == aacContract.getApproved(_from) ||
aacContract.isApprovedForAll(aacContract.ownerOf(_from), msg.sender),
"Sender is not authorized operator for AAC"
);
// token owner's balance must be enough to spend tokens
require (
coloredTokens[_colorIndex].balances[_from] >= _tokens,
"Insufficient balance to spend"
);
// deduct the tokens from token owner's balance
coloredTokens[_colorIndex].balances[_from] -= _tokens;
// emit spend event
emit SpendColor(_from, _colorIndex, _tokens);
return true;
}
//-------------------------------------------------------------------------
/// @notice Transfer balances of colored tokens to new uid. AAC contract
/// only.
/// @dev throws unless sent by AAC contract
//-------------------------------------------------------------------------
function onLink(uint _oldUid, uint _newUid) external {
require (msg.sender == address(aacContract), "Unauthorized transaction");
require (_oldUid > UID_MAX && _newUid <= UID_MAX);
for(uint i = 0; i < coloredTokens.length; ++i) {
coloredTokens[i].balances[_newUid] = coloredTokens[i].balances[_oldUid];
}
}
//-------------------------------------------------------------------------
/// @notice Get the number of colored tokens with color index `_colorIndex`
/// owned by AAC #`_uid`.
/// @param _uid The AAC with deposited color tokens.
/// @param _colorIndex Index of the colored token to query.
/// @return The number of colored tokens with color index `_colorIndex`
/// owned by AAC #`_uid`.
//-------------------------------------------------------------------------
function getColoredTokenBalance(uint _uid, uint _colorIndex)
external
view
returns(uint)
{
return coloredTokens[_colorIndex].balances[_uid];
}
//-------------------------------------------------------------------------
/// @notice Count the number of colored token types
/// @return Number of colored token types
//-------------------------------------------------------------------------
function coloredTokenCount() external view returns (uint) {
return coloredTokens.length;
}
//-------------------------------------------------------------------------
/// @notice Get the name and creator address of colored token with index
/// `_colorIndex`
/// @param _colorIndex Index of the colored token to query.
/// @return The creator address and name of colored token.
//-------------------------------------------------------------------------
function getColoredToken(uint _colorIndex)
external
view
returns(address, string memory)
{
return (
coloredTokens[_colorIndex].creator,
coloredTokens[_colorIndex].name
);
}
}
|
------------------------------------------------------------------------- Set the address of the VIP180 to `_newAddress`. Throws if ehrtAddress is the zero address. _newAddress The address of the Eight Hours Token.------------------------------------------------------------------------- initialize ehrtAddress to new address
|
function setEhrtContractAddress (address _newAddress)
external
notZero(uint(_newAddress))
onlyOwner
{
ehrtAddress = _newAddress;
}
| 13,104,894
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
/// @title BRZ token Bridge
/// @author Solange Gueiros
// Inpired on
// https://github.com/rsksmart/tokenbridge/blob/master/bridge/contracts/Bridge.sol
// https://github.com/DistributedCollective/Bridge-SC/blob/master/sovryn-token-bridge/bridge/contracts/Bridge_v3.sol
// AccessControl.sol : https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/access/AccessControl.sol
// Pausable.sol : https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/security/Pausable.sol
import "./ozeppelin/access/AccessControl.sol";
import "./ozeppelin/security/Pausable.sol";
import "./IBridge.sol";
struct BlockchainStruct {
uint256 minTokenAmount;
uint256 minBRZFee; // quoteETH_BRZ * gasAcceptTransfer * minGasPrice
uint256 minGasPrice; // in Wei
bool checkAddress; // to verify is an address is EVM compatible is this blockchain
}
/**
* @dev BRZ token Bridge
*
* Author: Solange Gueiros
*
* Smart contract to cross the BRZ token between EVM compatible blockchains.
*
* The tokens are crossed by TransferoSwiss, the company that controls the issuance of BRZs.
*
* It uses [Open Zeppelin Contracts]
* (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/)
*
*/
contract Bridge is AccessControl, IBridge, Pausable {
address private constant ZERO_ADDRESS = address(0);
bytes32 private constant NULL_HASH = bytes32(0);
bytes32 public constant MONITOR_ROLE = keccak256("MONITOR_ROLE");
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
/**
* @dev DECIMALPERCENT is the representation of 100% using (2) decimal places
* 100.00 = percentage accuracy (2) to 100%
*/
uint256 public constant DECIMALPERCENT = 10000;
IERC20 public token;
uint256 public totalFeeReceivedBridge; // fee received per Bridge, not for transaction in other blockchain
/**
* @dev Fee percentage bridge.
*
* For each amount received in the bridge, a fee percentage is discounted.
* This function returns this fee percentage bridge.
* Include 2 decimal places.
*/
uint256 public feePercentageBridge;
/**
* Estimative for function acceptTransfer: 100000 wei, it can change in EVM cost updates
*
* It is used to calculate minBRZFee in destination,
* which can not accept a BRZ fee less than minBRZFee (per blockchain).
*/
uint256 public gasAcceptTransfer;
/**
* @dev the quote of pair ETH / BRZ.
*
* (1 ETH = the amount of BRZ returned)
*
* in BRZ in minor unit (4 decimal places).
*
* It is used to calculate minBRZFee in destination
* which can not accept a BRZ fee less than minBRZFee (per blockchain).
*
*/
uint256 public quoteETH_BRZ;
mapping(bytes32 => bool) public processed;
mapping(string => uint256) private blockchainIndex;
BlockchainStruct[] private blockchainInfo;
string[] public blockchain;
/**
* @dev Function called only when the smart contract is deployed.
*
* Parameters:
* - address tokenAddress - address of BRZ token used in this blockchain network
*
* Actions:
* - the transaction's sender will be added in the DEFAULT_ADMIN_ROLE.
* - the token will be defined by the parameter tokenAddress
* - the feePercentageBridge default value is be setted in 10, which means 0.1%
*/
constructor(address tokenAddress) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
token = IERC20(tokenAddress);
feePercentageBridge = 10; //0.1%
gasAcceptTransfer = 100000; //Estimative function acceptTransfer: 100000 wei
}
/**
* @dev Modifier which verifies if the caller is an owner,
* it means he has the role `DEFAULT_ADMIN_ROLE`.
*
* The role `DEFAULT_ADMIN_ROLE` is defined by Open Zeppelin's AccessControl smart contract.
*
* By default (setted in the constructor) the account which deployed this smart contract is in this role.
*
* This owner can add / remove other owners.
*/
modifier onlyOwner() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "not owner");
_;
}
/**
* @dev Modifier which verifies if the caller is a monitor,
* it means he has the role `MONITOR_ROLE`.
*
* Role MONITOR are referred to its `bytes32` identifier,
* defined in the `public constant` called MONITOR_ROLE.
* It should be exposed in the external API and be unique.
*
* Role MONITOR is used to manage the permissions of monitor's addresses.
*/
modifier onlyMonitor() {
require(hasRole(MONITOR_ROLE, _msgSender()), "not monitor");
_;
}
/**
* @dev Modifier which verifies if the caller is a monitor,
* it means he has the role `ADMIN_ROLE`.
*
* Role ADMIN are referred to its `bytes32` identifier,
* defined in the `public constant` called ADMIN_ROLE.
* It should be exposed in the external API and be unique.
*
* Role ADMIN is used to manage the permissions for update minimum fee per blockchain.
*/
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, _msgSender()), "not admin");
_;
}
/**
* @dev Function which returns the bridge's version.
*
* This is a fixed value define in source code.
*
* Parameters: none
*
* Returns: string
*/
function version() external pure override returns (string memory) {
return "v0";
}
/**
* @dev Private function to compare two strings
* and returns `true` if the strings are equal,
* otherwise it returns false.
*
* Parameters: stringA, stringB
*
* Returns: bool
*/
function compareStrings(string memory a, string memory b)
private
pure
returns (bool)
{
return (keccak256(abi.encodePacked((a))) ==
keccak256(abi.encodePacked((b))));
}
/**
* @dev This function starts the process of crossing tokens in the Bridge.
*
* > Any account / person can call it!
*
* Can not be called if the Bridge is paused.
*
* Parameters:
* - amount - gross amount of tokens to be crossed.
* - The Bridge fee will be deducted from this amount.
* - transactionFee - array with the fees:
* - transactionFee[0] - fee in BRL - this fee will be added to amount transfered from caller's account.
* - transactionFee[1] - gas price for fee in destiny currency(minor unit) - this information will be
* used in the destination Blockchain,
* by the monitor who will create the transaction and send using this fee defined here.
* - toBlockchain - the amount will be sent to this blockchain.
* - toAddress - the amount will be sent to this address. It can be diferent from caller's address.
* This is a string because some blockchain could not have the same pattern from Ethereum / RSK / BSC.
*
* Returns: bool - true if it is sucessful.
*
* > Before call this function, the caller MUST have called function `approve` in BRZ token,
* > allowing the bridge's smart contract address to use the BRZ tokens,
* > calling the function `transferFrom`.
*
* References:
*
* ERC-20 tokens approve and transferFrom pattern:
* [eip-20#transferfrom](https://eips.ethereum.org/EIPS/eip-20#transferfrom)
*
* Requirements:
* - fee in BRZ (transactionFee[0]) must be at least (BRZFactorFee[blockchainName] * minGasPrice[toBlockchain]).
* - gasPrice (transactionFee[1]) in destiny blockchain (minor unit) greater than minGasPrice in toBlockchain.
* - toBlockchain exists.
* - toAddress is not an empty string.
* - amount must be greater than minTokenAmount in toBlockchain.
* - amount greater than zero.
*
* Actions:
* - add the blockchain fee in BRZ to amount in BRZ, in totalAmount.
* - calculate bridge's fee using the original amount to be sent.
* - discount bridge's fee from the original amount, in amountMinusFees.
* - add bridge's fee to `totalFeeReceivedBridge`, a variable to store all the fees received by the bridge.
* - BRZ transfer totalAmount from the caller's address to bridge address.
* - emit `CrossRequest` event, with the parameters:
* - from - address of the caller's function.
* - amount - the net amount to be transfered in the destination blockchain.
* - toFee - the gas price fee, which must be used to send the transfer transaction in the destination blockchain.
* - toAddress - string representing the address which will receive the tokens.
* - toBlockchain - the destination blockchain.
*
* > The `CrossRequest` event is very important because it must be listened by the monitor,
* an external program which will
* send the transaction on the destination blockchain.
*
* #### More info about fees
*
* - Blockchain / transaction fee in BRL (transactionFee[0])
* It will be transfered from user's account,
* along with the amount he would like to receive in the account.
*
* This will be spent in `toBlockchain`.
* Does not depend of amount, but of destination blockchain.
*
* It must be at least the minBRZFee per blockchain.
*
* It is used in the function acceptTransfer,
* which can not accept a BRZ fee less than minBRZFee (per blockchain).
*
* - gas price (transactionFee[1])
* It must be at least the minGasPrice per blockchain.
*
* - Bridge Fee - it is deducted from the requested amount.
* It is a percentage of the requested amount.
* Cannot include the transaction fee in order to be calculated.
*
*/
function receiveTokens(
uint256 amount,
uint256[2] memory transactionFee,
string memory toBlockchain,
string memory toAddress
) external override whenNotPaused returns (bool) {
require(existsBlockchain(toBlockchain), "toBlockchain not exists");
require(!compareStrings(toAddress, ""), "toAddress is null");
uint256 index = blockchainIndex[toBlockchain] - 1;
require(
transactionFee[0] >= blockchainInfo[index].minBRZFee,
"feeBRZ is less than minimum"
);
require(
transactionFee[1] >= blockchainInfo[index].minGasPrice,
"gasPrice is less than minimum"
);
require(amount > 0, "amount is 0");
require(
amount >= blockchainInfo[index].minTokenAmount,
"amount is less than minimum"
);
if (blockchainInfo[index].checkAddress) {
require(bytes(toAddress).length == 42, "invalid destination address");
}
//The total amount is the amount desired plus the blockchain fee to destination, in the token unit
uint256 totalAmount = amount + transactionFee[0];
//Bridge fee or service fee
uint256 bridgeFee = (amount * feePercentageBridge) / DECIMALPERCENT;
uint256 amountMinusFees = amount - bridgeFee;
totalFeeReceivedBridge += bridgeFee;
//This is the message for Monitor off-chain manage the transaction and send the tokens on the other Blockchain
emit CrossRequest(
_msgSender(),
amountMinusFees,
transactionFee[1],
toAddress,
toBlockchain
);
//Transfer the tokens on IERC20, they should be already approved for the bridge Address to use them
token.transferFrom(_msgSender(), address(this), totalAmount);
return true;
}
/**
* @dev This function calculate a transaction id hash.
*
* Any person can call it.
*
* Parameters:
* - hashes - from transaction in the origin blockchain:
* - blockHash - hash of the block where was the transaction `receiveTokens`
* - transactionHash - hash of the transaction `receiveTokens` with the event `CrossRequest`.
* - receiver - the address which will receive the tokens.
* - amount - the net amount to be transfered.
* - logIndex - the index of the event `CrossRequest` in the logs of transaction.
* - sender - address who sent the transaction `receiveTokens`, it is a string to be compatible with any blockchain.
*
* Returns: a bytes32 hash of all the information sent.
*
* Notes:
* It did not use origin blockchain and sender address
* because the possibility of having the same origin transaction from different blockchain source is minimal.
*
* It is a point to be evaluated in an audit.
*
*/
function getTransactionId(
bytes32[2] calldata hashes, //blockHash, transactionHash
address receiver,
uint256 amount,
uint32 logIndex
) public pure override returns (bytes32) {
return
keccak256(
abi.encodePacked(hashes[0], hashes[1], receiver, amount, logIndex)
);
}
/**
* @dev This function update the variable processed for a transaction
*
* > Only monitor can call it!
*
* This variable is a public mapping.
*
* Each bytes32 which represents a Transaction Id has his boolen value stored.
*
*/
function _processTransaction(
bytes32[2] calldata hashes, //blockHash, transactionHash
address receiver,
uint256 amount,
uint32 logIndex
) private {
bytes32 transactionId = getTransactionId(
hashes,
receiver,
amount,
logIndex
);
require(!processed[transactionId], "processed");
processed[transactionId] = true;
}
/**
* @dev This function transfer tokens from the the internal balance of bridge smart contract
* to the internal balance of the destination address.
*
* The token.balanceOf(bridgeAddress) must always be greather than or equal the total amount to be claimed by users,
* as there may be tokens not yet claimed.
*
* Can not be called if the Bridge is paused.
*
* > Only monitor can call it!
*
*/
function _sendToken(address to, uint256 amount) private returns (bool) {
require(token.balanceOf(address(this)) >= amount, "insufficient balance");
token.transfer(to, amount);
return true;
}
/**
* @dev This function accept the cross of token,
* which means it is called in the destination blockchain,
* who will send the tokens accepted to be crossed.
*
* > Only monitor can call it!
*
* Can not be called if the Bridge is paused.
*
* Parameters:
* - receiver - the address which will receive the tokens.
* - amount - the net amount to be transfered.
* - sender - string representing the address of the token's sender.
* - fromBlockchain - the origin blockchain.
* - hashes - from transaction in the origin blockchain:
* - blockHash - hash of the block where was the transaction `receiveTokens`.
* - transactionHash - hash of the transaction `receiveTokens` with the event `CrossRequest`.
* - logIndex - the index of the event `CrossRequest` in the transaction logs.
*
* Returns: bool - true if it is sucessful
*
* Requirements:
* - receiver is not a zero address.
* - amount greater than zero.
* - sender is not an empty string.
* - fromBlockchain exists.
* - blockHash is not null hash.
* - transactionHash is not hash.
*
* Actions:
* - processTransaction:
* - getTransactionId
* - verify if the transactionId was already processed
* - update the status processed for transactionId
* - sendToken:
* - check if the bridge has in his balance at least the amount required to do the transfer
* - transfer the amount tokens to destination address
*
*/
function acceptTransfer(
address receiver,
uint256 amount,
string calldata fromBlockchain,
bytes32[2] calldata hashes, //blockHash, transactionHash
uint32 logIndex
) external override onlyMonitor whenNotPaused returns (bool) {
require(receiver != ZERO_ADDRESS, "receiver is zero");
require(amount > 0, "amount is 0");
require(existsBlockchain(fromBlockchain), "fromBlockchain not exists");
require(hashes[0] != NULL_HASH, "blockHash is null");
require(hashes[1] != NULL_HASH, "transactionHash is null");
_processTransaction(hashes, receiver, amount, logIndex);
_sendToken(receiver, amount);
return true;
}
/**
* @dev Returns token balance in bridge.
*
* Parameters: none
*
* Returns: integer amount of tokens in bridge
*
*/
function getTokenBalance() external view override returns (uint256) {
return token.balanceOf(address(this));
}
/**
* @dev Withdraw tokens from bridge
*
* Only owner can call it.
*
* Can be called even if the Bridge is paused,
* because can happens a problem and it is necessary to withdraw tokens,
* maybe to create a new version of bridge, for example.
*
* The tokens only can be sent to the caller's function.
*
* Parameters: integer amount of tokens
*
* Returns: true if it is successful
*
* Requirements:
* - amount less or equal balance of tokens in bridge.
*
*/
function withdrawToken(uint256 amount) external onlyOwner returns (bool) {
require(amount <= token.balanceOf(address(this)), "insuficient balance");
token.transfer(_msgSender(), amount);
return true;
}
/**
* @dev This function add an address in the `MONITOR_ROLE`.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: address of monitor to be added
*
* Returns: bool - true if it is sucessful
*
*/
function addMonitor(address account)
external
onlyOwner
whenNotPaused
returns (bool)
{
require(!hasRole(ADMIN_ROLE, account), "is admin");
grantRole(MONITOR_ROLE, account);
return true;
}
/**
* @dev This function excludes an address in the `MONITOR_ROLE`.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: address of monitor to be excluded
*
* Returns: bool - true if it is sucessful
*
*/
function delMonitor(address account)
external
onlyOwner
whenNotPaused
returns (bool)
{
//Can be called only by the account defined in constructor: DEFAULT_ADMIN_ROLE
revokeRole(MONITOR_ROLE, account);
return true;
}
/**
* @dev This function add an address in the `ADMIN_ROLE`.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: address of admin to be added
*
* Returns: bool - true if it is sucessful
*
*/
function addAdmin(address account)
external
onlyOwner
whenNotPaused
returns (bool)
{
require(!hasRole(MONITOR_ROLE, account), "is monitor");
grantRole(ADMIN_ROLE, account);
return true;
}
/**
* @dev This function excludes an address in the `ADMIN_ROLE`.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: address of admin to be excluded
*
* Returns: bool - true if it is sucessful
*
*/
function delAdmin(address account)
external
onlyOwner
whenNotPaused
returns (bool)
{
//Can be called only by the account defined in constructor: DEFAULT_ADMIN_ROLE
revokeRole(ADMIN_ROLE, account);
return true;
}
/**
* @dev This function allows a user to renounce a role
*
* Parameters: bytes32 role, address account
*
* Returns: none
*
* Requirements:
*
* - An owner can not renounce the role DEFAULT_ADMIN_ROLE.
* - Can only renounce roles for your own account.
*
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(role != DEFAULT_ADMIN_ROLE, "can not renounce role owner");
require(account == _msgSender(), "can only renounce roles for self");
super.renounceRole(role, account);
}
/**
* @dev This function allows to revoke a role
*
* Parameters: bytes32 role, address account
*
* Returns: none
*
* Requirements:
*
* - An owner can not revoke yourself in the role DEFAULT_ADMIN_ROLE.
*
*/
function revokeRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
if (role == DEFAULT_ADMIN_ROLE) {
require(account != _msgSender(), "can not revoke yourself in role owner");
}
super.revokeRole(role, account);
}
/**
* @dev This function update the minimum blockchain fee - gas price - in the minor unit.
*
* It is an internal function, called when quoteETH_BRZ, gasAcceptTransfer
*
* Returns: bool - true if it is sucessful
*
* Emit the event `MinBRZFeeChanged(blockchain, oldFee, newFee)`.
*
*/
function _updateMinBRZFee() internal returns (bool) {
for (uint8 i = 0; i < blockchainInfo.length; i++) {
if (blockchainInfo[i].minGasPrice > 0) {
uint256 newFee = (gasAcceptTransfer *
blockchainInfo[i].minGasPrice *
quoteETH_BRZ) / (1 ether);
emit MinBRZFeeChanged(
blockchain[i],
blockchainInfo[i].minBRZFee,
newFee
);
blockchainInfo[i].minBRZFee = newFee;
}
}
return true;
}
/**
* @dev This function update quote of pair ETH / BRZ.
*
* (1 ETH = the amount of BRZ defined)
*
* Only admin can call it.
*
* Each time quoteETH_BRZ is updated, the MinBRZFee is updated too.
*
* Parameters: integer, the new quote
*
* Returns: bool - true if it is sucessful
*
* Emit the event `QuoteETH_BRZChanged(oldValue, newValue)`.
*
*/
function setQuoteETH_BRZ(uint256 newValue) public onlyAdmin returns (bool) {
emit QuoteETH_BRZChanged(quoteETH_BRZ, newValue);
quoteETH_BRZ = newValue;
require(_updateMinBRZFee(), "updateMinBRZFee error");
return true;
}
/**
* @dev Returns the minimum gas price to cross tokens.
*
* The function acceptTransfer can not accept less than the minimum gas price per blockchain.
*
* Parameters: string, blockchain name
*
* Returns: integer
*
*/
function getMinGasPrice(string memory blockchainName)
external
view
override
returns (uint256)
{
return blockchainInfo[blockchainIndex[blockchainName] - 1].minGasPrice;
}
/**
* @dev This function update the minimum blockchain fee - gas price - in the minor unit.
*
* Each time setMinGasPrice is updated, the MinBRZFee is updated too.
*
* Only admin can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: integer, the new fee
*
* Returns: bool - true if it is sucessful
*
* Requirements:
* - blockchain must exists.
*
* Emit the event `MinGasPriceChanged(blockchain, oldFee, newFee)`.
*
*/
function setMinGasPrice(string memory blockchainName, uint256 newFee)
public
onlyAdmin
whenNotPaused
returns (bool)
{
require(existsBlockchain(blockchainName), "blockchain not exists");
uint256 index = blockchainIndex[blockchainName] - 1;
emit MinGasPriceChanged(
blockchainName,
blockchainInfo[index].minGasPrice,
newFee
);
blockchainInfo[index].minGasPrice = newFee;
blockchainInfo[index].minBRZFee =
(gasAcceptTransfer * newFee * quoteETH_BRZ) /
(1 ether);
return true;
}
/**
* @dev Returns the minimum destination blockchain fee in BRZ,
* in minor unit (4 decimal places)
*
* It is updated when one of these itens be updated:
* - gasAcceptTransfer
* - quoteETH_BRZ
* - minGasPrice per Blockchain
*
* It is used in the function acceptTransfer,
* which can not accept a BRZ fee less than minBRZFee (per blockchain).
*
* Parameters: string, blockchain name
*
* Returns: integer
*
*/
function getMinBRZFee(string memory blockchainName)
external
view
override
returns (uint256)
{
return blockchainInfo[blockchainIndex[blockchainName] - 1].minBRZFee;
}
/**
* @dev This function update the estimative of the gas amount used in function AcceptTransfer.
*
* It will only change if happen some EVM cost update.
*
* Only owner can call it.
*
* Each time gasAcceptTransfer is updated, the MinBRZFee is updated too.
*
* Parameters: integer, the new gas amount
*
* Returns: bool - true if it is sucessful
*
* Emit the event `GasAcceptTransferChanged(oldValue, newValue)`.
*
*/
function setGasAcceptTransfer(uint256 newValue)
public
onlyOwner
returns (bool)
{
emit GasAcceptTransferChanged(gasAcceptTransfer, newValue);
gasAcceptTransfer = newValue;
require(_updateMinBRZFee(), "updateMinBRZFee error");
return true;
}
/**
* @dev Returns the minimum token amount to cross.
*
* The function acceptTransfer can not accpept less than the minimum per blockchain.
*
* Parameters: string, blockchain name
*
* Returns: integer
*
*/
function getMinTokenAmount(string memory blockchainName)
external
view
override
returns (uint256)
{
return blockchainInfo[blockchainIndex[blockchainName] - 1].minTokenAmount;
}
/**
* @dev This function update the minimum token's amount to be crossed.
*
* Only admin can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: integer, the new amount
*
* Returns: bool - true if it is sucessful
*
* Requirements:
* - blockchain must exists.
*
* Emit the event `MinTokenAmountChanged(blockchain, oldMinimumAmount, newMinimumAmount)`.
*
*/
function setMinTokenAmount(string memory blockchainName, uint256 newAmount)
public
onlyAdmin
whenNotPaused
returns (bool)
{
require(existsBlockchain(blockchainName), "blockchain not exists");
uint256 index = blockchainIndex[blockchainName] - 1;
emit MinTokenAmountChanged(
blockchainName,
blockchainInfo[index].minTokenAmount,
newAmount
);
blockchainInfo[index].minTokenAmount = newAmount;
return true;
}
/**
* @dev This function update the fee percentage bridge.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: integer, the new fee
*
* Returns: bool - true if it is sucessful
*
* Requirements:
* - The new fee must be lower than 10% .
*
* Emit the event `FeePercentageBridgeChanged(oldFee, newFee)`.
*
*/
function setFeePercentageBridge(uint256 newFee)
external
onlyOwner
whenNotPaused
returns (bool)
{
require(newFee < (DECIMALPERCENT / 10), "bigger than 10%");
emit FeePercentageBridgeChanged(feePercentageBridge, newFee);
feePercentageBridge = newFee;
return true;
}
/**
* @dev This function update the BRZ token.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: address of new BRZ token
*
* Returns: bool - true if it is sucessful
*
* Requirements:
* - The token address must not be a zero address.
*
* Emit the event `TokenChanged(tokenAddress)`.
*
*/
function setToken(address tokenAddress)
external
onlyOwner
whenNotPaused
returns (bool)
{
require(tokenAddress != ZERO_ADDRESS, "zero address");
emit TokenChanged(tokenAddress);
token = IERC20(tokenAddress);
return true;
}
/**
* @dev Returns if a blockchain is in the list of allowed blockchains to cross tokens using the bridge.
*
* Parameters: string name of blockchain
*
* Returns: boolean true if it is in the list
*
*/
function existsBlockchain(string memory name)
public
view
override
returns (bool)
{
if (blockchainIndex[name] == 0) return false;
else return true;
}
/**
* @dev List of blockchains allowed to cross tokens using the bridge.
*
* Parameters: none
*
* Returns: an array of strings containing the blockchain list
*
*/
function listBlockchain() external view override returns (string[] memory) {
return blockchain;
}
/**
* @dev This function include a new blockchain in the list of allowed blockchains used in the bridge.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters:
* - string name of blockchain to be added
* - minGasPrice
* - minTokenAmount
* - check address EVM compatible
*
* Returns: index of blockchain.
*
* Important:
* - index start in 1, not 0.
* - index 0 means that the blockchain does no exist.
* - index 1 means that it is the position 0 in the array.
*
* Requirements:
* - blockchain not exists.
* - onlyOwner
* - whenNotPaused
*/
function addBlockchain(
string memory name,
uint256 minGasPrice,
uint256 minTokenAmount,
bool checkAddress
) external onlyOwner whenNotPaused returns (uint256) {
require(!existsBlockchain(name), "blockchain exists");
BlockchainStruct memory b;
b.minGasPrice = minGasPrice;
b.minTokenAmount = minTokenAmount;
b.minBRZFee = (gasAcceptTransfer * minGasPrice * quoteETH_BRZ) / (1 ether);
b.checkAddress = checkAddress;
blockchainInfo.push(b);
blockchain.push(name);
uint256 index = blockchainInfo.length;
blockchainIndex[name] = index;
return (index);
}
/**
* @dev This function exclude a blockchain in the list of allowed blockchains used in the bridge.
*
* Only owner can call it.
*
* Can not be called if the Bridge is paused.
*
* Parameters: string name of blockchain to be excluded
*
* Returns: bool - true if it is sucessful
*
* Requirements:
* - blockchain exists.
* - there must be at least one blockchain left.
*
*/
function delBlockchain(string memory name)
external
onlyOwner
whenNotPaused
returns (bool)
{
require(existsBlockchain(name), "blockchain not exists");
require(blockchainInfo.length > 1, "requires at least 1 blockchain");
uint256 indexToDelete = blockchainIndex[name] - 1;
uint256 indexToMove = blockchainInfo.length - 1;
//string memory keyToMove = blockchainInfo[indexToMove].name;
string memory keyToMove = blockchain[indexToMove];
blockchainInfo[indexToDelete] = blockchainInfo[indexToMove];
blockchain[indexToDelete] = blockchain[indexToMove];
blockchainIndex[keyToMove] = indexToDelete + 1;
delete blockchainIndex[name];
blockchainInfo.pop();
blockchain.pop();
return true;
}
/**
* @dev This function pauses the bridge.
*
* Only owner can call it.
*
* Parameters: none
*
* Returns: none
*
* Requirements:
*
* - The contract must not be paused.
*
*/
function pause() external onlyOwner {
/**
* @dev See {Pausable-_pause}.
*
* Requirements:
*
* - The contract must not be paused.
*/
_pause();
}
/**
* @dev This function unpauses the bridge.
*
* Only owner can call it.
*
* Parameters: none
*
* Returns: none
*
* Requirements:
*
* - The contract must be paused.
*/
function unpause() external onlyOwner {
/**
* @dev See {Pausable-_unpause}.
*
* Requirements:
*
* - The contract must be paused.
*/
_unpause();
}
}
|
This function starts the process of crossing tokens in the Bridge. > Any account / person can call it! Can not be called if the Bridge is paused. Parameters: - amount - gross amount of tokens to be crossed. - The Bridge fee will be deducted from this amount. - transactionFee - array with the fees: - transactionFee[0] - fee in BRL - this fee will be added to amount transfered from caller's account. - transactionFee[1] - gas price for fee in destiny currency(minor unit) - this information will be used in the destination Blockchain, by the monitor who will create the transaction and send using this fee defined here. - toBlockchain - the amount will be sent to this blockchain. - toAddress - the amount will be sent to this address. It can be diferent from caller's address. This is a string because some blockchain could not have the same pattern from Ethereum / RSK / BSC. Returns: bool - true if it is sucessful. > Before call this function, the caller MUST have called function `approve` in BRZ token, > allowing the bridge's smart contract address to use the BRZ tokens, > calling the function `transferFrom`. References: ERC-20 tokens approve and transferFrom pattern: Requirements: - fee in BRZ (transactionFee[0]) must be at least (BRZFactorFee[blockchainName] minGasPrice[toBlockchain]). - gasPrice (transactionFee[1]) in destiny blockchain (minor unit) greater than minGasPrice in toBlockchain. - toBlockchain exists. - toAddress is not an empty string. - amount must be greater than minTokenAmount in toBlockchain. - amount greater than zero. Actions: - add the blockchain fee in BRZ to amount in BRZ, in totalAmount. - calculate bridge's fee using the original amount to be sent. - discount bridge's fee from the original amount, in amountMinusFees. - add bridge's fee to `totalFeeReceivedBridge`, a variable to store all the fees received by the bridge. - BRZ transfer totalAmount from the caller's address to bridge address. - emit `CrossRequest` event, with the parameters: - from - address of the caller's function. - amount - the net amount to be transfered in the destination blockchain. - toFee - the gas price fee, which must be used to send the transfer transaction in the destination blockchain. - toAddress - string representing the address which will receive the tokens. - toBlockchain - the destination blockchain. > The `CrossRequest` event is very important because it must be listened by the monitor, an external program which will send the transaction on the destination blockchain. More info about fees - Blockchain / transaction fee in BRL (transactionFee[0]) It will be transfered from user's account, along with the amount he would like to receive in the account. This will be spent in `toBlockchain`. Does not depend of amount, but of destination blockchain. It must be at least the minBRZFee per blockchain. It is used in the function acceptTransfer, which can not accept a BRZ fee less than minBRZFee (per blockchain). - gas price (transactionFee[1]) It must be at least the minGasPrice per blockchain. - Bridge Fee - it is deducted from the requested amount. It is a percentage of the requested amount. Cannot include the transaction fee in order to be calculated./
|
function receiveTokens(
uint256 amount,
uint256[2] memory transactionFee,
string memory toBlockchain,
string memory toAddress
) external override whenNotPaused returns (bool) {
require(existsBlockchain(toBlockchain), "toBlockchain not exists");
require(!compareStrings(toAddress, ""), "toAddress is null");
uint256 index = blockchainIndex[toBlockchain] - 1;
require(
transactionFee[0] >= blockchainInfo[index].minBRZFee,
"feeBRZ is less than minimum"
);
require(
transactionFee[1] >= blockchainInfo[index].minGasPrice,
"gasPrice is less than minimum"
);
require(amount > 0, "amount is 0");
require(
amount >= blockchainInfo[index].minTokenAmount,
"amount is less than minimum"
);
if (blockchainInfo[index].checkAddress) {
require(bytes(toAddress).length == 42, "invalid destination address");
}
uint256 amountMinusFees = amount - bridgeFee;
totalFeeReceivedBridge += bridgeFee;
_msgSender(),
amountMinusFees,
transactionFee[1],
toAddress,
toBlockchain
);
return true;
}
| 12,927,575
|
./full_match/1/0x7F6163674b6FD9c3D7238F2C5F958AC5C9A40aF8/sources/contracts/exchange/Exchange.sol
|
Call atomicMatch - Solidity ABI encoding limitation workaround, hopefully temporary./
|
function atomicMatch_(
address[14] memory addrs,
uint[18] 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
whenNotPaused
payable
{
return atomicMatch(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), callDataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, address(ERC20(addrs[6])), uints[4], uints[5], uints[6], uints[7], uints[8]),
Sig(vs[0], rssMetadata[0], rssMetadata[1]),
Order(addrs[7], addrs[8], addrs[9], uints[9], uints[10], uints[11], uints[12], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), callDataSell, replacementPatternSell, addrs[12], staticExtradataSell, address(ERC20(addrs[13])), uints[13], uints[14], uints[15], uints[16], uints[17]),
Sig(vs[1], rssMetadata[2], rssMetadata[3]),
rssMetadata[4]
);
}
| 9,770,968
|
pragma solidity ^0.5.0;
import "@studydefi/money-legos/compound/contracts/IComptroller.sol";
import "@studydefi/money-legos/compound/contracts/ICEther.sol";
import "@studydefi/money-legos/compound/contracts/ICToken.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract CompoundManager {
using SafeMath for uint256;
address constant CompoundComptrollerAddress = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
address constant CEtherAddress = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "safe-math-sub-failed");
uint256 c = a - b;
return c;
}
function _transferFromUnderlying(
address sender,
address recipient,
address cToken,
uint256 amount
) internal {
address underlying = ICToken(cToken).underlying();
require(
IERC20(underlying).transferFrom(sender, recipient, amount),
"cmpnd-mgr-transferFrom-underlying-failed"
);
}
function _transferUnderlying(
address cToken,
address recipient,
uint256 amount
) internal {
if (cToken == CEtherAddress) {
recipient.call.value(amount)("");
} else {
require(
IERC20(ICToken(cToken).underlying()).transfer(
recipient,
amount
),
"cmpnd-mgr-transfer-underlying-failed"
);
}
}
function _transfer(address token, address recipient, uint256 amount)
internal
{
require(
IERC20(token).transfer(recipient, amount),
"cmpnd-mgr-transfer-failed"
);
}
function getBorrowBalanceUnderlying(
address cToken,
address owner
)
public
view
returns (uint256)
{
(
uint256 err,
uint256 cTokenBalance,
uint256 borrowBalance,
uint256 exchangeRateMantissa
) = ICToken(cToken).getAccountSnapshot(owner);
// Source: balanceOfUnderlying from any ctoken
return cTokenBalance.mul(exchangeRateMantissa).div(1e18);
}
function enterMarkets(
address[] memory cTokens // Address of the Compound derivation token (e.g. cDAI)
) public {
// Enter the compound markets for all the specified tokens
uint256[] memory errors = IComptroller(CompoundComptrollerAddress)
.enterMarkets(cTokens);
for (uint256 i = 0; i < errors.length; i++) {
require(errors[i] == 0, "cmpnd-mgr-enter-markets-failed");
}
}
function approveCToken(address cToken, uint256 amount) public {
// Approves CToken contract to call `transferFrom`
address underlying = ICToken(cToken).underlying();
require(
IERC20(underlying).approve(cToken, amount) == true,
"cmpnd-mgr-ctoken-approved-failed"
);
}
function approveCTokens(
address[] memory cTokens // Tokens to approve
) public {
for (uint256 i = 0; i < cTokens.length; i++) {
// Don't need to approve ICEther
if (cTokens[i] != CEtherAddress) {
approveCToken(cTokens[i], uint256(-1));
}
}
}
function enterMarketsAndApproveCTokens(address[] memory cTokens) public {
enterMarkets(cTokens);
approveCTokens(cTokens);
}
function supply(address cToken, uint256 amount) public payable {
if (cToken == CEtherAddress) {
ICEther(CEtherAddress).mint.value(amount)();
} else {
// Approves CToken contract to call `transferFrom`
approveCToken(cToken, amount);
require(
ICToken(cToken).mint(amount) == 0,
"cmpnd-mgr-ctoken-supply-failed"
);
}
}
function borrow(address cToken, uint256 borrowAmount) public {
require(
ICToken(cToken).borrow(borrowAmount) == 0,
"cmpnd-mgr-ctoken-borrow-failed"
);
}
function supplyAndBorrow(
address supplyCToken,
uint256 supplyAmount,
address borrowCToken,
uint256 borrowAmount
) public payable {
supply(supplyCToken, supplyAmount);
borrow(borrowCToken, borrowAmount);
}
function repayBorrow(address cToken, uint256 amount) public payable {
if (cToken == CEtherAddress) {
ICEther(cToken).repayBorrow.value(amount)();
} else {
approveCToken(cToken, amount);
require(
ICToken(cToken).repayBorrow(amount) == 0,
"cmpnd-mgr-ctoken-repay-failed"
);
}
}
function repayBorrowBehalf(
address recipient,
address cToken,
uint256 amount
) public payable {
if (cToken == CEtherAddress) {
ICEther(cToken).repayBorrowBehalf.value(amount)(recipient);
} else {
approveCToken(cToken, amount);
require(
ICToken(cToken).repayBorrowBehalf(recipient, amount) == 0,
"cmpnd-mgr-ctoken-repaybehalf-failed"
);
}
}
function redeem(address cToken, uint256 redeemTokens) public payable {
require(
ICToken(cToken).redeem(redeemTokens) == 0,
"cmpnd-mgr-ctoken-redeem-failed"
);
}
function redeemUnderlying(address cToken, uint256 redeemTokens)
public
payable
{
require(
ICToken(cToken).redeemUnderlying(redeemTokens) == 0,
"cmpnd-mgr-ctoken-redeem-underlying-failed"
);
}
}
|
Source: balanceOfUnderlying from any ctoken
|
function getBorrowBalanceUnderlying(
address cToken,
address owner
)
public
view
returns (uint256)
{
(
uint256 err,
uint256 cTokenBalance,
uint256 borrowBalance,
uint256 exchangeRateMantissa
) = ICToken(cToken).getAccountSnapshot(owner);
return cTokenBalance.mul(exchangeRateMantissa).div(1e18);
}
| 13,034,798
|
//SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "../interfaces/IEternalFund.sol";
import "../interfaces/IEternalStorage.sol";
import "../interfaces/ITimelock.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @title The Eternal Fund contract
* @author Taken from Compound Finance (COMP) and tweaked/detailed by Nobody (me)
* @notice The Eternal Fund serves as the governing body of Eternal
*/
contract EternalFund is IEternalFund, Context {
/////–––««« Variables: Interfaces and Addresses »»»––––\\\\\
// The name of this contract
string public constant name = "Eternal Fund";
// The keccak256 hash of the Eternal Token address
bytes32 public immutable entity;
// The timelock interface
ITimelock public timelock;
// The Eternal token interface
IERC20 public eternal;
// The Eternal storage interface
IEternalStorage public eternalStorage;
// The address of the Governor Guardian
address public guardian;
/////–––««« Variable: Voting »»»––––\\\\\
// The total number of proposals
uint256 public proposalCount;
// Holds all proposal data
struct Proposal {
uint256 id; // Unique id for looking up a proposal
address proposer; // Creator of the proposal
uint256 eta; // The timestamp that the proposal will be available for execution, set once the vote succeeds
address[] targets; // The ordered list of target addresses for calls to be made
uint256[] values; // The ordered list of values (i.e. msg.value) to be passed to the calls to be made
string[] signatures; // The ordered list of function signatures to be called
bytes[] calldatas; // The ordered list of calldata to be passed to each call
uint256 startTime; // The timestamp at which voting begins: holders must delegate their votes prior to this time
uint256 endTime; // The timestamp at which voting ends: votes must be cast prior to this block
uint256 startBlock; // The block at which voting began: holders must have delegated their votes prior to this block
uint256 forVotes; // Current number of votes in favor of this proposal
uint256 againstVotes; // Current number of votes in opposition to this proposal
bool canceled; // Flag marking whether the proposal has been canceled
bool executed; // Flag marking whether the proposal has been executed
mapping (address => Receipt) receipts; // Receipts of ballots for the entire set of voters
}
// Ballot receipt record for a voter
struct Receipt {
bool hasVoted; // Whether or not a vote has been cast
bool support; // Whether or not the voter supports the proposal
uint256 votes; // The number of votes the voter had, which were cast
}
// Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
// The official record of all proposals ever proposed
mapping (uint256 => Proposal) public proposals;
// The latest proposal for each proposer
mapping (address => uint256) public latestProposalIds;
/////–––««« Variables: Voting by signature »»»––––\\\\\
// The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
// The EIP-712 typehash for the ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
/////–––««« Events »»»––––\\\\\
// Emitted when a new proposal is created
event ProposalCreated(uint256 id, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startTime, uint256 endTime, string description);
// Emitted when the first vote is cast in a proposal
event StartBlockSet(uint256 proposalId, uint256 startBlock);
// Emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes);
// Emitted when a proposal has been canceled
event ProposalCanceled(uint256 id);
// Emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint256 id, uint256 eta);
// Emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint256 id);
/////–––««« Constructor »»»––––\\\\\
constructor (address _guardian, address _eternalStorage, address _eternal, address _timelock) {
guardian = _guardian;
eternalStorage = IEternalStorage(_eternalStorage);
eternal = IERC20(_eternal);
timelock = ITimelock(_timelock);
entity = keccak256(abi.encodePacked(_eternal));
}
/////–––««« Variable state-inspection functions »»»––––\\\\\
/**
* @notice The number of votes required in order for a voter to become a proposer.
* @return 0.5 percent of the initial supply
*/
function proposalThreshold() public pure returns (uint256) {
return 5 * (10 ** 7) * (10 ** 18); // 50 000 000ETRNL = initially 0.5% (increases over time due to deflation)
}
/**
* @notice View the maximum number of operations that can be included in a proposal.
* @return The maximum number of actions per proposal
*/
function proposalMaxOperations() public pure returns (uint256) {
return 15;
}
/**
* @notice View the delay before voting on a proposal may take place, once proposed.
* @return 1 day (in seconds)
*/
function votingDelay() public pure returns (uint256) {
return 1 days;
}
/**
* @notice The duration of voting on a proposal, in blocks.
* @return 3 days (in seconds)
*/
function votingPeriod() public pure returns (uint256) {
return 3 days;
}
/////–––««« Governance logic functions »»»––––\\\\\
/**
* @notice Initiates a proposal.
* @param targets An ordered list of contract addresses used to make the calls
* @param values A list of values passed in each call
* @param signatures A list of function signatures used to make the calls
* @param calldatas A list of function parameter hashes used to make the calls
* @param description A description of the proposal
* @return The current proposal count
*
* Requirements:
*
* - Proposer must have a voting balance equal to at least 0.5 percent of the initial ETRNL supply
* - All lists must have the same length
* - Lists must contain at least one element but no more than 15 elements
* - Proposer can only have one live proposal at a time
*/
function propose(address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint256) {
require(getPriorVotes(msg.sender, block.number - 1) > proposalThreshold(), "Vote balance below threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "Arity mismatch in proposal");
require(targets.length != 0, "Must provide actions");
require(targets.length <= proposalMaxOperations(), "Too many actions");
uint256 latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active && proposersLatestProposalState != ProposalState.Pending, "One live proposal per proposer");
}
uint256 startTime = block.timestamp + votingDelay();
uint256 endTime = block.timestamp + votingPeriod() + votingDelay();
proposalCount += 1;
proposals[proposalCount].id = proposalCount;
proposals[proposalCount].proposer = msg.sender;
proposals[proposalCount].eta = 0;
proposals[proposalCount].targets = targets;
proposals[proposalCount].values = values;
proposals[proposalCount].signatures = signatures;
proposals[proposalCount].calldatas = calldatas;
proposals[proposalCount].startTime = startTime;
proposals[proposalCount].startBlock = 0;
proposals[proposalCount].endTime = endTime;
proposals[proposalCount].forVotes = 0;
proposals[proposalCount].againstVotes = 0;
proposals[proposalCount].canceled = false;
proposals[proposalCount].executed = false;
latestProposalIds[msg.sender] = proposalCount;
emit ProposalCreated(proposalCount, msg.sender, targets, values, signatures, calldatas, startTime, endTime, description);
return proposalCount;
}
/**
* @notice Queues all of a given proposal's actions into the timelock contract.
* @param proposalId The id of the specified proposal
*
* Requirements:
*
* - The proposal needs to have passed
*/
function queue(uint256 proposalId) public {
require(state(proposalId) == ProposalState.Succeeded, "Proposal state must be Succeeded");
Proposal storage proposal = proposals[proposalId];
uint256 eta = block.timestamp + timelock.viewDelay();
for (uint256 i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
/**
* @notice Queues an individual proposal action into the timelock contract.
* @param target The address of the contract whose function is being called
* @param value The amount of AVAX being transferred in this transaction
* @param signature The function signature of this proposal's action
* @param data The function parameters of this proposal's action
* @param eta The estimated minimum UNIX time (in seconds) at which this transaction is to be executed
*
* Requirements:
*
* - The transaction should not have been queued
*/
function _queueOrRevert(address target, uint256 value, string memory signature, bytes memory data, uint256 eta) private {
require(!timelock.queuedTransaction(keccak256(abi.encode(target, value, signature, data, eta))), "Proposal action already queued");
timelock.queueTransaction(target, value, signature, data, eta);
}
/**
* @notice Executes all of a given's proposal's actions.
* @param proposalId The id of the specified proposal
*
* Requirements:
*
* - The proposal must already be in queue
*/
function execute(uint256 proposalId) public payable {
require(state(proposalId) == ProposalState.Queued, "Proposal is not queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction{value: proposal.values[i]}(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
/**
* @notice Cancels all of a given proposal's actions.
* @param proposalId The id of the specified proposal
*
* Requirements:
*
* - The proposal should not have been executed
* - The proposer's vote balance should be below the threshold
*/
function cancel(uint proposalId) public {
ProposalState _state = state(proposalId);
require(_state != ProposalState.Executed, "Cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(getPriorVotes(proposal.proposer, block.number - 1) < proposalThreshold(), "Proposer above threshold");
proposal.canceled = true;
for (uint256 i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
/**
* @notice View a given proposal's lists of actions.
* @param proposalId The id of the specified proposal
* @return targets The proposal's targets
* @return values The proposal's values
* @return signatures The proposal's signatures
* @return calldatas The proposal's calldatas
*/
function getActions(uint256 proposalId) public view returns (address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
/**
* @notice View a given proposal's ballot receipt for a given voter.
* @param proposalId The id of the specified proposal
* @param voter The address of the specified voter
* @return The ballot receipt of that voter for the proposal
*/
function getReceipt(uint256 proposalId, address voter) public view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
/**
* @notice View the state of a given proposal.
* @param proposalId The id of the specified proposal
* @return The state of the proposal
*
* Requirements:
*
* - Proposal must exist
*/
function state(uint256 proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "Invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.timestamp <= proposal.startTime) {
return ProposalState.Pending;
} else if (block.timestamp <= proposal.endTime) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= proposal.eta + timelock.viewGracePeriod()) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
/**
* @notice Casts a vote for a given proposal.
* @param proposalId The id of the specified proposal
* @param support Whether the user is in support of the proposal or not
*/
function castVote(uint256 proposalId, bool support) public {
return _castVote(msg.sender, proposalId, support);
}
/**
* @notice Casts a vote through signature.
* @param proposalId The id of teh specified proposal
* @param support Whether the user is in support of the proposal or not
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*
* Requirements:
*
* - Must be a valid signature
*/
function castVoteBySig(uint256 proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public {
uint chainId;
// solhint-disable-next-line no-inline-assembly
assembly { chainId := chainid() }
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), chainId, address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Invalid signature");
return _castVote(signatory, proposalId, support);
}
/**
* @notice Casts a vote for a given voter and proposal.
* @param voter The address of the specified voter
* @param proposalId The id of the specified proposal
* @param support Whether the voter is in support of the proposal or not
*
* Requirements:
*
* - Voting period for the proposal needs to be ongoing
* - The voter must not have already voted
*/
function _castVote(address voter, uint256 proposalId, bool support) private {
require(state(proposalId) == ProposalState.Active, "Voting is closed");
Proposal storage proposal = proposals[proposalId];
if (proposal.startBlock == 0) {
proposal.startBlock = block.number - 1;
emit StartBlockSet(proposalId, block.number);
}
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "Voter already voted");
uint256 votes = getPriorVotes(voter, proposal.startBlock);
if (support) {
proposal.forVotes = proposal.forVotes + votes;
} else {
proposal.againstVotes = proposal.againstVotes + votes;
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VoteCast(voter, proposalId, support, votes);
}
/**
* @notice Allow the Eternal Fund to take over control of the timelock contract.
*
* Requirements:
*
* - Only callable by the current guardian
*/
function __acceptFund() public {
require(msg.sender == guardian, "Caller must be the guardian");
timelock.acceptFund();
}
/**
* @notice Renounce the role of guardianship.
*
* Requirements:
*
* - Only callable by the current guardian
*/
function __abdicate() public {
require(msg.sender == guardian, "Caller must be the guardian");
guardian = address(0);
}
/**
* @notice Queues the transaction which will give governing power to the Eternal Fund.
*
* Requirements:
*
* - Only callable by the current guardian
*/
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public {
require(msg.sender == guardian, "Caller must be the guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
/**
* @notice Executes the transaction which will give governing power to the Eternal Fund.
*
* Requirements:
*
* - Only callable by the current guardian
*/
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint256 eta) public {
require(msg.sender == guardian, "Caller must be the guardian");
timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
/////–––««« Governance-related functions »»»––––\\\\\
/**
* @notice Gets the current votes balance for a given account.
* @param account The address of the specified account
* @return The current number of votes of the account
*/
function getCurrentVotes(address account) public view override returns (uint256) {
uint256 nCheckpoints = eternalStorage.getUint(entity, keccak256(abi.encodePacked("numCheckpoints", account)));
return eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", account, nCheckpoints - 1)));
}
/**
* @notice Determine the number of votes of a given account prior to a given block.
* @param account The address of specified account
* @param blockNumber The number of the specified block
* @return The number of votes of the account before/by this block
*
* Requirements:
*
* - The given block must be finalized
*/
function getPriorVotes(address account, uint256 blockNumber) public view override returns (uint256) {
require(blockNumber < block.number, "Block is not yet finalized");
uint256 nCheckpoints = eternalStorage.getUint(entity, keccak256(abi.encodePacked("numCheckpoints", account)));
if (nCheckpoints == 0) {
// No checkpoints means no votes
return 0;
} else if (eternalStorage.getUint(entity, keccak256(abi.encodePacked("blocks", account, nCheckpoints - 1))) <= blockNumber) {
// Votes for the most recent checkpoint
return eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", account, nCheckpoints - 1)));
} else if (eternalStorage.getUint(entity, keccak256(abi.encodePacked("blocks", account, uint256(0)))) > blockNumber) {
// Only having checkpoints after the given block number means no votes
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
uint256 thisBlock = eternalStorage.getUint(entity, keccak256(abi.encodePacked("blocks", account, center)));
if (thisBlock == blockNumber) {
return eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", account, center)));
} else if (thisBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", account, lower)));
}
/**
* @notice Delegates the message sender's vote balance to a given user.
* @param delegatee The address of the user to whom the vote balance is being added to
*/
function delegate(address delegatee) external override {
bytes32 _delegate = keccak256(abi.encodePacked("delegates", _msgSender()));
address currentDelegate = eternalStorage.getAddress(entity, _delegate);
uint256 delegatorBalance = eternal.balanceOf(_msgSender());
eternalStorage.setAddress(entity, _delegate, delegatee);
emit DelegateChanged(_msgSender(), currentDelegate, delegatee);
moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
/**
* @notice Transfer part of a given delegates' voting balance to another new delegate.
* @param srcRep The delegate from whom we are deducting votes
* @param dstRep The delegate to whom we are transferring votes
* @param amount The specified amount of votes
*/
function moveDelegates(address srcRep, address dstRep, uint256 amount) public override {
require(_msgSender() == address(this) || _msgSender() == address(eternal), "Only callable by Eternal");
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint256 srcRepNum = eternalStorage.getUint(entity, keccak256(abi.encodePacked("numCheckpoints", srcRep)));
uint256 srcRepOld = srcRepNum > 0 ? eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", srcRep, srcRepNum - 1))) : 0;
uint256 srcRepNew = srcRepOld - amount;
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint256 dstRepNum = eternalStorage.getUint(entity, keccak256(abi.encodePacked("numCheckpoints", dstRep)));
uint256 dstRepOld = dstRepNum > 0 ? eternalStorage.getUint(entity, keccak256(abi.encodePacked("votes", dstRep, dstRepNum - 1))) : 0;
uint256 dstRepNew = dstRepOld + amount;
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
/**
* @notice Update a given user's voting balance for the current block.
* @param delegatee The address of the specified user
* @param nCheckpoints The number of times the voting balance of the user has been updated
* @param oldVotes The old voting balance of the user
* @param newVotes The new voting balance of the user
*/
function _writeCheckpoint(address delegatee, uint256 nCheckpoints, uint256 oldVotes,uint256 newVotes) private {
if (nCheckpoints > 0 && eternalStorage.getUint(entity, keccak256(abi.encodePacked("blocks", delegatee, nCheckpoints - 1))) == block.number) {
eternalStorage.setUint(entity, keccak256(abi.encodePacked("votes", delegatee, nCheckpoints - 1)), newVotes);
} else {
eternalStorage.setUint(entity, keccak256(abi.encodePacked("votes", delegatee, nCheckpoints)), newVotes);
eternalStorage.setUint(entity, keccak256(abi.encodePacked("blocks", delegatee, nCheckpoints)), block.number);
eternalStorage.setUint(entity, keccak256(abi.encodePacked("numCheckpoints", delegatee)), nCheckpoints + 1);
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
}
|
Queues an individual proposal action into the timelock contract. target The address of the contract whose function is being called value The amount of AVAX being transferred in this transaction signature The function signature of this proposal's action data The function parameters of this proposal's action eta The estimated minimum UNIX time (in seconds) at which this transaction is to be executed Requirements: - The transaction should not have been queued/
|
function _queueOrRevert(address target, uint256 value, string memory signature, bytes memory data, uint256 eta) private {
require(!timelock.queuedTransaction(keccak256(abi.encode(target, value, signature, data, eta))), "Proposal action already queued");
timelock.queueTransaction(target, value, signature, data, eta);
}
| 12,810,502
|
pragma solidity ^0.4.23;
// File: @ensdomains/dnssec-oracle/contracts/BytesUtils.sol
library BytesUtils {
/*
* @dev Returns the keccak-256 hash of a byte range.
* @param self The byte string to hash.
* @param offset The position to start hashing at.
* @param len The number of bytes to hash.
* @return The hash of the byte range.
*/
function keccak(bytes memory self, uint offset, uint len) internal pure returns (bytes32 ret) {
require(offset + len <= self.length);
assembly {
ret := sha3(add(add(self, 32), offset), len)
}
}
/*
* @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 bytes are equal.
* @param self The first bytes to compare.
* @param other The second bytes to compare.
* @return The result of the comparison.
*/
function compare(bytes memory self, bytes memory other) internal pure returns (int) {
return compare(self, 0, self.length, other, 0, other.length);
}
/*
* @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 bytes are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first bytes to compare.
* @param offset The offset of self.
* @param len The length of self.
* @param other The second bytes to compare.
* @param otheroffset The offset of the other string.
* @param otherlen The length of the other string.
* @return The result of the comparison.
*/
function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) {
uint shortest = len;
if (otherlen < len)
shortest = otherlen;
uint selfptr;
uint otherptr;
assembly {
selfptr := add(self, add(offset, 32))
otherptr := add(other, add(otheroffset, 32))
}
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
uint mask;
if (shortest > 32) {
mask = uint256(- 1); // aka 0xffffff....
} else {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(len) - int(otherlen);
}
/*
* @dev Returns true if the two byte ranges are equal.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @param otherOffset The offset into the second byte range.
* @param len The number of bytes to compare
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset, uint len) internal pure returns (bool) {
return keccak(self, offset, len) == keccak(other, otherOffset, len);
}
/*
* @dev Returns true if the two byte ranges are equal with offsets.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @param otherOffset The offset into the second byte range.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset) internal pure returns (bool) {
return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset);
}
/*
* @dev Compares a range of 'self' to all of 'other' and returns True iff
* they are equal.
* @param self The first byte range to compare.
* @param offset The offset into the first byte range.
* @param other The second byte range to compare.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, uint offset, bytes memory other) internal pure returns (bool) {
return self.length >= offset + other.length && equals(self, offset, other, 0, other.length);
}
/*
* @dev Returns true if the two byte ranges are equal.
* @param self The first byte range to compare.
* @param other The second byte range to compare.
* @return True if the byte ranges are equal, false otherwise.
*/
function equals(bytes memory self, bytes memory other) internal pure returns(bool) {
return self.length == other.length && equals(self, 0, other, 0, self.length);
}
/*
* @dev Returns the 8-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 8 bits of the string, interpreted as an integer.
*/
function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) {
require(idx + 1 <= self.length);
assembly {
ret := and(mload(add(add(self, 1), idx)), 0xFF)
}
}
/*
* @dev Returns the 16-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 16 bits of the string, interpreted as an integer.
*/
function readUint16(bytes memory self, uint idx) internal pure returns (uint16 ret) {
require(idx + 2 <= self.length);
assembly {
ret := and(mload(add(add(self, 2), idx)), 0xFFFF)
}
}
/*
* @dev Returns the 32-bit number at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bits of the string, interpreted as an integer.
*/
function readUint32(bytes memory self, uint idx) internal pure returns (uint32 ret) {
require(idx + 4 <= self.length);
assembly {
ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF)
}
}
/*
* @dev Returns the 32 byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bytes of the string.
*/
function readBytes32(bytes memory self, uint idx) internal pure returns (bytes32 ret) {
require(idx + 32 <= self.length);
assembly {
ret := mload(add(add(self, 32), idx))
}
}
/*
* @dev Returns the 32 byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes
* @return The specified 32 bytes of the string.
*/
function readBytes20(bytes memory self, uint idx) internal pure returns (bytes20 ret) {
require(idx + 20 <= self.length);
assembly {
ret := and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000)
}
}
/*
* @dev Returns the n byte value at the specified index of self.
* @param self The byte string.
* @param idx The index into the bytes.
* @param len The number of bytes.
* @return The specified 32 bytes of the string.
*/
function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes20 ret) {
require(idx + len <= self.length);
assembly {
let mask := not(sub(exp(256, sub(32, len)), 1))
ret := and(mload(add(add(self, 32), idx)), mask)
}
}
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 Copies a substring into a new byte string.
* @param self The byte string to copy from.
* @param offset The offset to start copying at.
* @param len The number of bytes to copy.
*/
function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes) {
require(offset + len <= self.length);
bytes memory ret = new bytes(len);
uint dest;
uint src;
assembly {
dest := add(ret, 32)
src := add(add(self, 32), offset)
}
memcpy(dest, src, len);
return ret;
}
// Maps characters from 0x30 to 0x7A to their base32 values.
// 0xFF represents invalid characters in that range.
bytes constant base32HexTable = hex'00010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F';
/**
* @dev Decodes unpadded base32 data of up to one word in length.
* @param self The data to decode.
* @param off Offset into the string to start at.
* @param len Number of characters to decode.
* @return The decoded data, left aligned.
*/
function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) {
require(len <= 52);
uint ret = 0;
for(uint i = 0; i < len; i++) {
byte char = self[off + i];
require(char >= 0x30 && char <= 0x7A);
uint8 decoded = uint8(base32HexTable[uint(char) - 0x30]);
require(decoded <= 0x20);
if(i == len - 1) {
break;
}
ret = (ret << 5) | decoded;
}
uint bitlen = len * 5;
if(len % 8 == 0) {
// Multiple of 8 characters, no padding
ret = (ret << 5) | decoded;
} else if(len % 8 == 2) {
// Two extra characters - 1 byte
ret = (ret << 3) | (decoded >> 2);
bitlen -= 2;
} else if(len % 8 == 4) {
// Four extra characters - 2 bytes
ret = (ret << 1) | (decoded >> 4);
bitlen -= 4;
} else if(len % 8 == 5) {
// Five extra characters - 3 bytes
ret = (ret << 4) | (decoded >> 1);
bitlen -= 1;
} else if(len % 8 == 7) {
// Seven extra characters - 4 bytes
ret = (ret << 2) | (decoded >> 3);
bitlen -= 3;
} else {
revert();
}
return bytes32(ret << (256 - bitlen));
}
}
// File: @ensdomains/dnssec-oracle/contracts/DNSSEC.sol
interface DNSSEC {
event AlgorithmUpdated(uint8 id, address addr);
event DigestUpdated(uint8 id, address addr);
event NSEC3DigestUpdated(uint8 id, address addr);
event RRSetUpdated(bytes name, bytes rrset);
function submitRRSets(bytes memory data, bytes memory proof) public returns (bytes);
function submitRRSet(bytes memory input, bytes memory sig, bytes memory proof) public returns(bytes memory rrs);
function deleteRRSet(uint16 deleteType, bytes deleteName, bytes memory nsec, bytes memory sig, bytes memory proof) public;
function rrdata(uint16 dnstype, bytes memory name) public view returns (uint32, uint64, bytes20);
}
// File: @ensdomains/buffer/contracts/Buffer.sol
/**
* @dev A library for working with mutable byte buffers in Solidity.
*
* Byte buffers are mutable and expandable, and provide a variety of primitives
* for writing to them. At any time you can fetch a bytes object containing the
* current contents of the buffer. The bytes object should not be stored between
* operations, as it may change due to resizing of the buffer.
*/
library Buffer {
/**
* @dev Represents a mutable buffer. Buffers have a current value (buf) and
* a capacity. The capacity may be longer than the current value, in
* which case it can be extended without the need to allocate more memory.
*/
struct buffer {
bytes buf;
uint capacity;
}
/**
* @dev Initializes a buffer with an initial capacity.
* @param buf The buffer to initialize.
* @param capacity The number of bytes of space to allocate the buffer.
* @return The buffer, for chaining.
*/
function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) {
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
return buf;
}
/**
* @dev Initializes a new buffer from an existing bytes object.
* Changes to the buffer may mutate the original value.
* @param b The bytes object to initialize the buffer with.
* @return A new buffer.
*/
function fromBytes(bytes b) internal pure returns(buffer memory) {
buffer memory buf;
buf.buf = b;
buf.capacity = b.length;
return buf;
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if (a > b) {
return a;
}
return b;
}
/**
* @dev Sets buffer length to 0.
* @param buf The buffer to truncate.
* @return The original buffer, for chaining..
*/
function truncate(buffer memory buf) internal pure returns (buffer memory) {
assembly {
let bufptr := mload(buf)
mstore(bufptr, 0)
}
return buf;
}
/**
* @dev Writes a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The start offset to write to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes data, uint len) internal pure returns(buffer memory) {
require(len <= data.length);
if (off + len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + offset + sizeof(buffer length)
dest := add(add(bufptr, 32), off)
// Update buffer length if we're extending it
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
// Copy word-length chunks while possible
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @param len The number of bytes to copy.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes data, uint len) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, len);
}
/**
* @dev Appends a byte string to a buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function append(buffer memory buf, bytes data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, data.length);
}
/**
* @dev Writes a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write the byte at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) {
if (off > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + sizeof(buffer length) + off
let dest := add(add(bufptr, off), 32)
mstore8(dest, data)
// Update buffer length if we extended it
if eq(off, buflen) {
mstore(bufptr, add(buflen, 1))
}
}
return buf;
}
/**
* @dev Appends a byte to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) {
return writeUint8(buf, buf.buf.length, data);
}
/**
* @dev Writes up to 32 bytes to the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (left-aligned).
* @return The original buffer, for chaining.
*/
function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
// Right-align data
data = data >> (8 * (32 - len));
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + sizeof(buffer length) + off + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
/**
* @dev Writes a bytes20 to the buffer. Resizes if doing so would exceed the
* capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) {
return write(buf, off, bytes32(data), 20);
}
/**
* @dev Appends a bytes20 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chhaining.
*/
function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, bytes32(data), 20);
}
/**
* @dev Appends a bytes32 to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer, for chaining.
*/
function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, 32);
}
/**
* @dev Writes an integer to the buffer. Resizes if doing so would exceed
* the capacity of the buffer.
* @param buf The buffer to append to.
* @param off The offset to write at.
* @param data The data to append.
* @param len The number of bytes to write (right-aligned).
* @return The original buffer, for chaining.
*/
function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Address = buffer address + off + sizeof(buffer length) + len
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length if we extended it
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
}
// File: @ensdomains/dnssec-oracle/contracts/RRUtils.sol
/**
* @dev RRUtils is a library that provides utilities for parsing DNS resource records.
*/
library RRUtils {
using BytesUtils for *;
using Buffer for *;
/**
* @dev Returns the number of bytes in the DNS name at 'offset' in 'self'.
* @param self The byte array to read a name from.
* @param offset The offset to start reading at.
* @return The length of the DNS name at 'offset', in bytes.
*/
function nameLength(bytes memory self, uint offset) internal pure returns(uint) {
uint idx = offset;
while (true) {
assert(idx < self.length);
uint labelLen = self.readUint8(idx);
idx += labelLen + 1;
if (labelLen == 0) {
break;
}
}
return idx - offset;
}
/**
* @dev Returns a DNS format name at the specified offset of self.
* @param self The byte array to read a name from.
* @param offset The offset to start reading at.
* @return The name.
*/
function readName(bytes memory self, uint offset) internal pure returns(bytes memory ret) {
uint len = nameLength(self, offset);
return self.substring(offset, len);
}
/**
* @dev Returns the number of labels in the DNS name at 'offset' in 'self'.
* @param self The byte array to read a name from.
* @param offset The offset to start reading at.
* @return The number of labels in the DNS name at 'offset', in bytes.
*/
function labelCount(bytes memory self, uint offset) internal pure returns(uint) {
uint count = 0;
while (true) {
assert(offset < self.length);
uint labelLen = self.readUint8(offset);
offset += labelLen + 1;
if (labelLen == 0) {
break;
}
count += 1;
}
return count;
}
/**
* @dev An iterator over resource records.
*/
struct RRIterator {
bytes data;
uint offset;
uint16 dnstype;
uint16 class;
uint32 ttl;
uint rdataOffset;
uint nextOffset;
}
/**
* @dev Begins iterating over resource records.
* @param self The byte string to read from.
* @param offset The offset to start reading at.
* @return An iterator object.
*/
function iterateRRs(bytes memory self, uint offset) internal pure returns (RRIterator memory ret) {
ret.data = self;
ret.nextOffset = offset;
next(ret);
}
/**
* @dev Returns true iff there are more RRs to iterate.
* @param iter The iterator to check.
* @return True iff the iterator has finished.
*/
function done(RRIterator memory iter) internal pure returns(bool) {
return iter.offset >= iter.data.length;
}
/**
* @dev Moves the iterator to the next resource record.
* @param iter The iterator to advance.
*/
function next(RRIterator memory iter) internal pure {
iter.offset = iter.nextOffset;
if (iter.offset >= iter.data.length) {
return;
}
// Skip the name
uint off = iter.offset + nameLength(iter.data, iter.offset);
// Read type, class, and ttl
iter.dnstype = iter.data.readUint16(off);
off += 2;
iter.class = iter.data.readUint16(off);
off += 2;
iter.ttl = iter.data.readUint32(off);
off += 4;
// Read the rdata
uint rdataLength = iter.data.readUint16(off);
off += 2;
iter.rdataOffset = off;
iter.nextOffset = off + rdataLength;
}
/**
* @dev Returns the name of the current record.
* @param iter The iterator.
* @return A new bytes object containing the owner name from the RR.
*/
function name(RRIterator memory iter) internal pure returns(bytes memory) {
return iter.data.substring(iter.offset, nameLength(iter.data, iter.offset));
}
/**
* @dev Returns the rdata portion of the current record.
* @param iter The iterator.
* @return A new bytes object containing the RR's RDATA.
*/
function rdata(RRIterator memory iter) internal pure returns(bytes memory) {
return iter.data.substring(iter.rdataOffset, iter.nextOffset - iter.rdataOffset);
}
/**
* @dev Checks if a given RR type exists in a type bitmap.
* @param self The byte string to read the type bitmap from.
* @param offset The offset to start reading at.
* @param rrtype The RR type to check for.
* @return True if the type is found in the bitmap, false otherwise.
*/
function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) {
uint8 typeWindow = uint8(rrtype >> 8);
uint8 windowByte = uint8((rrtype & 0xff) / 8);
uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7)));
for (uint off = offset; off < self.length;) {
uint8 window = self.readUint8(off);
uint8 len = self.readUint8(off + 1);
if (typeWindow < window) {
// We've gone past our window; it's not here.
return false;
} else if (typeWindow == window) {
// Check this type bitmap
if (len * 8 <= windowByte) {
// Our type is past the end of the bitmap
return false;
}
return (self.readUint8(off + windowByte + 2) & windowBitmask) != 0;
} else {
// Skip this type bitmap
off += len + 2;
}
}
return false;
}
function compareNames(bytes memory self, bytes memory other) internal pure returns (int) {
if (self.equals(other)) {
return 0;
}
uint off;
uint otheroff;
uint prevoff;
uint otherprevoff;
uint counts = labelCount(self, 0);
uint othercounts = labelCount(other, 0);
// Keep removing labels from the front of the name until both names are equal length
while (counts > othercounts) {
prevoff = off;
off = progress(self, off);
counts--;
}
while (othercounts > counts) {
otherprevoff = otheroff;
otheroff = progress(other, otheroff);
othercounts--;
}
// Compare the last nonequal labels to each other
while (counts > 0 && !self.equals(off, other, otheroff)) {
prevoff = off;
off = progress(self, off);
otherprevoff = otheroff;
otheroff = progress(other, otheroff);
counts -= 1;
}
if (off == 0) {
return -1;
}
if(otheroff == 0) {
return 1;
}
return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff));
}
function progress(bytes memory body, uint off) internal pure returns(uint) {
return off + 1 + body.readUint8(off);
}
}
// File: @ensdomains/ens/contracts/ENS.sol
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) public;
function setResolver(bytes32 node, address resolver) public;
function setOwner(bytes32 node, address owner) public;
function setTTL(bytes32 node, uint64 ttl) public;
function owner(bytes32 node) public view returns (address);
function resolver(bytes32 node) public view returns (address);
function ttl(bytes32 node) public view returns (uint64);
}
// File: @ensdomains/ens/contracts/ENSRegistry.sol
/**
* The ENS registry contract.
*/
contract ENSRegistry is ENS {
struct Record {
address owner;
address resolver;
uint64 ttl;
}
mapping (bytes32 => Record) records;
// Permits modifications only by the owner of the specified node.
modifier only_owner(bytes32 node) {
require(records[node].owner == msg.sender);
_;
}
/**
* @dev Constructs a new ENS registrar.
*/
function ENSRegistry() public {
records[0x0].owner = msg.sender;
}
/**
* @dev Transfers ownership of a node to a new address. May only be called by the current owner of the node.
* @param node The node to transfer ownership of.
* @param owner The address of the new owner.
*/
function setOwner(bytes32 node, address owner) public only_owner(node) {
Transfer(node, owner);
records[node].owner = owner;
}
/**
* @dev Transfers ownership of a subnode keccak256(node, label) to a new address. May only be called by the owner of the parent node.
* @param node The parent node.
* @param label The hash of the label specifying the subnode.
* @param owner The address of the new owner.
*/
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public only_owner(node) {
var subnode = keccak256(node, label);
NewOwner(node, label, owner);
records[subnode].owner = owner;
}
/**
* @dev Sets the resolver address for the specified node.
* @param node The node to update.
* @param resolver The address of the resolver.
*/
function setResolver(bytes32 node, address resolver) public only_owner(node) {
NewResolver(node, resolver);
records[node].resolver = resolver;
}
/**
* @dev Sets the TTL for the specified node.
* @param node The node to update.
* @param ttl The TTL in seconds.
*/
function setTTL(bytes32 node, uint64 ttl) public only_owner(node) {
NewTTL(node, ttl);
records[node].ttl = ttl;
}
/**
* @dev Returns the address that owns the specified node.
* @param node The specified node.
* @return address of the owner.
*/
function owner(bytes32 node) public view returns (address) {
return records[node].owner;
}
/**
* @dev Returns the address of the resolver for the specified node.
* @param node The specified node.
* @return address of the resolver.
*/
function resolver(bytes32 node) public view returns (address) {
return records[node].resolver;
}
/**
* @dev Returns the TTL of a node, and any records associated with it.
* @param node The specified node.
* @return ttl of the node.
*/
function ttl(bytes32 node) public view returns (uint64) {
return records[node].ttl;
}
}
// File: contracts/DNSRegistrar.sol
/**
* @dev An ENS registrar that allows the owner of a DNS name to claim the
* corresponding name in ENS.
*/
contract DNSRegistrar {
using BytesUtils for bytes;
using RRUtils for *;
using Buffer for Buffer.buffer;
uint16 constant CLASS_INET = 1;
uint16 constant TYPE_TXT = 16;
DNSSEC public oracle;
ENS public ens;
bytes public rootDomain;
bytes32 public rootNode;
event Claim(bytes32 indexed node, address indexed owner, bytes dnsname);
constructor(DNSSEC _dnssec, ENS _ens, bytes _rootDomain, bytes32 _rootNode) public {
oracle = _dnssec;
ens = _ens;
rootDomain = _rootDomain;
rootNode = _rootNode;
}
/**
* @dev Claims a name by proving ownership of its DNS equivalent.
* @param name The name to claim, in DNS wire format.
* @param proof A DNS RRSet proving ownership of the name. Must be verified
* in the DNSSEC oracle before calling. This RRSET must contain a TXT
* record for '_ens.' + name, with the value 'a=0x...'. Ownership of
* the name will be transferred to the address specified in the TXT
* record.
*/
function claim(bytes name, bytes proof) public {
bytes32 labelHash = getLabelHash(name);
address addr = getOwnerAddress(name, proof);
ens.setSubnodeOwner(rootNode, labelHash, addr);
emit Claim(keccak256(rootNode, labelHash), addr, name);
}
/**
* @dev Submits proofs to the DNSSEC oracle, then claims a name using those proofs.
* @param name The name to claim, in DNS wire format.
* @param input The data to be passed to the Oracle's `submitProofs` function. The last
* proof must be the TXT record required by the registrar.
* @param proof The proof record for the first element in input.
*/
function proveAndClaim(bytes name, bytes input, bytes proof) public {
proof = oracle.submitRRSets(input, proof);
claim(name, proof);
}
function getLabelHash(bytes memory name) internal view returns(bytes32) {
uint len = name.readUint8(0);
// Check this name is a direct subdomain of the one we're responsible for
require(name.equals(len + 1, rootDomain));
return name.keccak(1, len);
}
function getOwnerAddress(bytes memory name, bytes memory proof) internal view returns(address) {
// Add "_ens." to the front of the name.
Buffer.buffer memory buf;
buf.init(name.length + 5);
buf.append("\x04_ens");
buf.append(name);
bytes20 hash;
uint64 inserted;
// Check the provided TXT record has been validated by the oracle
(, inserted, hash) = oracle.rrdata(TYPE_TXT, buf.buf);
if(hash == bytes20(0) && proof.length == 0) return 0;
require(hash == bytes20(keccak256(proof)));
for(RRUtils.RRIterator memory iter = proof.iterateRRs(0); !iter.done(); iter.next()) {
require(inserted + iter.ttl >= now, "DNS record is stale; refresh or delete it before proceeding.");
address addr = parseRR(proof, iter.rdataOffset);
if(addr != 0) {
return addr;
}
}
return 0;
}
function parseRR(bytes memory rdata, uint idx) internal pure returns(address) {
while(idx < rdata.length) {
uint len = rdata.readUint8(idx); idx += 1;
address addr = parseString(rdata, idx, len);
if(addr != 0) return addr;
idx += len;
}
return 0;
}
function parseString(bytes memory str, uint idx, uint len) internal pure returns(address) {
// TODO: More robust parsing that handles whitespace and multiple key/value pairs
if(str.readUint32(idx) != 0x613d3078) return 0; // 0x613d3078 == 'a=0x'
if(len < 44) return 0;
return hexToAddress(str, idx + 4);
}
function hexToAddress(bytes memory str, uint idx) internal pure returns(address) {
if(str.length - idx < 40) return 0;
uint ret = 0;
for(uint i = idx; i < idx + 40; i++) {
ret <<= 4;
uint x = str.readUint8(i);
if(x >= 48 && x < 58) {
ret |= x - 48;
} else if(x >= 65 && x < 71) {
ret |= x - 55;
} else if(x >= 97 && x < 103) {
ret |= x - 87;
} else {
return 0;
}
}
return address(ret);
}
}
|
Transfers ownership of a node to a new address. May only be called by the current owner of the node. node The node to transfer ownership of. owner The address of the new owner./
|
function setOwner(bytes32 node, address owner) public only_owner(node) {
Transfer(node, owner);
records[node].owner = owner;
}
| 1,413,912
|
./full_match/4/0xd08F669E774Afc5E0eA0ba1D2c09f92931Ffcf12/sources/_openzeppelin/contracts_4.7.2/governance/compatibility/GovernorCompatibilityBravo.sol
|
See {Governor-_countVote}. In this module, the support follows Governor Bravo./
|
function _countVote(
uint256 proposalId,
address account,
uint8 support,
uint256 weight,
) internal virtual override {
ProposalDetails storage details = _proposalDetails[proposalId];
Receipt storage receipt = details.receipts[account];
require(!receipt.hasVoted, "GovernorCompatibilityBravo: vote already cast");
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = SafeCast.toUint96(weight);
if (support == uint8(VoteType.Against)) {
details.againstVotes += weight;
details.forVotes += weight;
details.abstainVotes += weight;
revert("GovernorCompatibilityBravo: invalid vote type");
}
}
| 707,430
|
// File: @aragon/os/contracts/common/UnstructuredStorage.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
library UnstructuredStorage {
function getStorageBool(bytes32 position) internal view returns (bool data) {
assembly { data := sload(position) }
}
function getStorageAddress(bytes32 position) internal view returns (address data) {
assembly { data := sload(position) }
}
function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
assembly { data := sload(position) }
}
function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
assembly { data := sload(position) }
}
function setStorageBool(bytes32 position, bool data) internal {
assembly { sstore(position, data) }
}
function setStorageAddress(bytes32 position, address data) internal {
assembly { sstore(position, data) }
}
function setStorageBytes32(bytes32 position, bytes32 data) internal {
assembly { sstore(position, data) }
}
function setStorageUint256(bytes32 position, uint256 data) internal {
assembly { sstore(position, data) }
}
}
// File: @aragon/os/contracts/acl/IACL.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IACL {
function initialize(address permissionsCreator) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
}
// File: @aragon/os/contracts/common/IVaultRecoverable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IVaultRecoverable {
event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
function transferToVault(address token) external;
function allowRecoverability(address token) external view returns (bool);
function getRecoveryVault() external view returns (address);
}
// File: @aragon/os/contracts/kernel/IKernel.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IKernelEvents {
event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
}
// This should be an interface, but interfaces can't inherit yet :(
contract IKernel is IKernelEvents, IVaultRecoverable {
function acl() public view returns (IACL);
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
function setApp(bytes32 namespace, bytes32 appId, address app) public;
function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
}
// File: @aragon/os/contracts/apps/AppStorage.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract AppStorage {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
*/
bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
function kernel() public view returns (IKernel) {
return IKernel(KERNEL_POSITION.getStorageAddress());
}
function appId() public view returns (bytes32) {
return APP_ID_POSITION.getStorageBytes32();
}
function setKernel(IKernel _kernel) internal {
KERNEL_POSITION.setStorageAddress(address(_kernel));
}
function setAppId(bytes32 _appId) internal {
APP_ID_POSITION.setStorageBytes32(_appId);
}
}
// File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ACLSyntaxSugar {
function arr() internal pure returns (uint256[]) {
return new uint256[](0);
}
function arr(bytes32 _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(address _a, address _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c);
}
function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c, _d);
}
function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), _c, _d, _e);
}
function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(uint256 _a) internal pure returns (uint256[] r) {
r = new uint256[](1);
r[0] = _a;
}
function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
r = new uint256[](2);
r[0] = _a;
r[1] = _b;
}
function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
r = new uint256[](3);
r[0] = _a;
r[1] = _b;
r[2] = _c;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
r = new uint256[](4);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
r = new uint256[](5);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
r[4] = _e;
}
}
contract ACLHelpers {
function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 30));
}
function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 31));
}
function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
a = uint32(_x);
b = uint32(_x >> (8 * 4));
c = uint32(_x >> (8 * 8));
}
}
// File: @aragon/os/contracts/common/Uint256Helpers.sol
pragma solidity ^0.4.24;
library Uint256Helpers {
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
return uint64(a);
}
}
// File: @aragon/os/contracts/common/TimeHelpers.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract TimeHelpers {
using Uint256Helpers for uint256;
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @dev Returns the current block number, converted to uint64.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber64() internal view returns (uint64) {
return getBlockNumber().toUint64();
}
/**
* @dev Returns the current timestamp.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp() internal view returns (uint256) {
return block.timestamp; // solium-disable-line security/no-block-members
}
/**
* @dev Returns the current timestamp, converted to uint64.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp64() internal view returns (uint64) {
return getTimestamp().toUint64();
}
}
// File: @aragon/os/contracts/common/Initializable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Initializable is TimeHelpers {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.initializable.initializationBlock")
bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
modifier onlyInit {
require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
_;
}
modifier isInitialized {
require(hasInitialized(), ERROR_NOT_INITIALIZED);
_;
}
/**
* @return Block number in which the contract was initialized
*/
function getInitializationBlock() public view returns (uint256) {
return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
}
/**
* @return Whether the contract has been initialized by the time of the current block
*/
function hasInitialized() public view returns (bool) {
uint256 initializationBlock = getInitializationBlock();
return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
}
/**
* @dev Function to be called by top level contract after initialization has finished.
*/
function initialized() internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
}
/**
* @dev Function to be called by top level contract after initialization to enable the contract
* at a future block number rather than immediately.
*/
function initializedAt(uint256 _blockNumber) internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
}
}
// File: @aragon/os/contracts/common/Petrifiable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Petrifiable is Initializable {
// Use block UINT256_MAX (which should be never) as the initializable date
uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
function isPetrified() public view returns (bool) {
return getInitializationBlock() == PETRIFIED_BLOCK;
}
/**
* @dev Function to be called by top level contract to prevent being initialized.
* Useful for freezing base contracts when they're used behind proxies.
*/
function petrify() internal onlyInit {
initializedAt(PETRIFIED_BLOCK);
}
}
// File: @aragon/os/contracts/common/Autopetrified.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract Autopetrified is Petrifiable {
constructor() public {
// Immediately petrify base (non-proxy) instances of inherited contracts on deploy.
// This renders them uninitializable (and unusable without a proxy).
petrify();
}
}
// File: @aragon/os/contracts/common/ConversionHelpers.sol
pragma solidity ^0.4.24;
library ConversionHelpers {
string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
// Force cast the uint256[] into a bytes array, by overwriting its length
// Note that the bytes array doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 byteLength = _input.length * 32;
assembly {
output := _input
mstore(output, byteLength)
}
}
function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
// Force cast the bytes array into a uint256[], by overwriting its length
// Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 intsLength = _input.length / 32;
require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
assembly {
output := _input
mstore(output, intsLength)
}
}
}
// File: @aragon/os/contracts/common/ReentrancyGuard.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract ReentrancyGuard {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex");
*/
bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb;
string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL";
modifier nonReentrant() {
// Ensure mutex is unlocked
require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT);
// Lock mutex before function call
REENTRANCY_MUTEX_POSITION.setStorageBool(true);
// Perform function call
_;
// Unlock mutex after function call
REENTRANCY_MUTEX_POSITION.setStorageBool(false);
}
}
// File: @aragon/os/contracts/lib/token/ERC20.sol
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: @aragon/os/contracts/common/EtherTokenConstant.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
// aragonOS and aragon-apps rely on address(0) to denote native ETH, in
// contracts where both tokens and ETH are accepted
contract EtherTokenConstant {
address internal constant ETH = address(0);
}
// File: @aragon/os/contracts/common/IsContract.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract IsContract {
/*
* NOTE: this should NEVER be used for authentication
* (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
*
* This is only intended to be used as a sanity check that an address is actually a contract,
* RATHER THAN an address not being a contract.
*/
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
// File: @aragon/os/contracts/common/SafeERC20.sol
// Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
// and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
pragma solidity ^0.4.24;
library SafeERC20 {
// Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
// https://github.com/ethereum/solidity/issues/3544
bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
function invokeAndCheckSuccess(address _addr, bytes memory _calldata)
private
returns (bool)
{
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
function staticInvoke(address _addr, bytes memory _calldata)
private
view
returns (bool, uint256)
{
bool success;
uint256 ret;
assembly {
let ptr := mload(0x40) // free memory pointer
success := staticcall(
gas, // forward all gas
_addr, // address
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
ret := mload(ptr)
}
}
return (success, ret);
}
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
TRANSFER_SELECTOR,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(_token, approveCallData);
}
/**
* @dev Static call into ERC20.balanceOf().
* Reverts if the call fails for some reason (should never fail).
*/
function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
bytes memory balanceOfCallData = abi.encodeWithSelector(
_token.balanceOf.selector,
_owner
);
(bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
require(success, ERROR_TOKEN_BALANCE_REVERTED);
return tokenBalance;
}
/**
* @dev Static call into ERC20.allowance().
* Reverts if the call fails for some reason (should never fail).
*/
function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
bytes memory allowanceCallData = abi.encodeWithSelector(
_token.allowance.selector,
_owner,
_spender
);
(bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
return allowance;
}
}
// File: @aragon/os/contracts/common/VaultRecoverable.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
using SafeERC20 for ERC20;
string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
/**
* @notice Send funds to recovery Vault. This contract should never receive funds,
* but in case it does, this function allows one to recover them.
* @param _token Token balance to be sent to recovery vault.
*/
function transferToVault(address _token) external {
require(allowRecoverability(_token), ERROR_DISALLOWED);
address vault = getRecoveryVault();
require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
uint256 balance;
if (_token == ETH) {
balance = address(this).balance;
vault.transfer(balance);
} else {
ERC20 token = ERC20(_token);
balance = token.staticBalanceOf(this);
require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
}
emit RecoverToVault(vault, _token, balance);
}
/**
* @dev By default deriving from AragonApp makes it recoverable
* @param token Token address that would be recovered
* @return bool whether the app allows the recovery
*/
function allowRecoverability(address token) public view returns (bool) {
return true;
}
// Cast non-implemented interface to be public so we can use it internally
function getRecoveryVault() public view returns (address);
}
// File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
interface IEVMScriptExecutor {
function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes);
function executorType() external pure returns (bytes32);
}
// File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract EVMScriptRegistryConstants {
/* Hardcoded constants to save gas
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg");
*/
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61;
}
interface IEVMScriptRegistry {
function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id);
function disableScriptExecutor(uint256 executorId) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor);
}
// File: @aragon/os/contracts/kernel/KernelConstants.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract KernelAppIds {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
*/
bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
}
contract KernelNamespaceConstants {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
*/
bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
}
// File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants {
string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE";
string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED";
/* This is manually crafted in assembly
string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN";
*/
event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData);
function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script));
}
function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) {
address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID);
return IEVMScriptRegistry(registryAddr);
}
function runScript(bytes _script, bytes _input, address[] _blacklist)
internal
isInitialized
protectState
returns (bytes)
{
IEVMScriptExecutor executor = getEVMScriptExecutor(_script);
require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE);
bytes4 sig = executor.execScript.selector;
bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist);
bytes memory output;
assembly {
let success := delegatecall(
gas, // forward all gas
executor, // address
add(data, 0x20), // calldata start
mload(data), // calldata length
0, // don't write output (we'll handle this ourselves)
0 // don't write output
)
output := mload(0x40) // free mem ptr get
switch success
case 0 {
// If the call errored, forward its full error data
returndatacopy(output, 0, returndatasize)
revert(output, returndatasize)
}
default {
switch gt(returndatasize, 0x3f)
case 0 {
// Need at least 0x40 bytes returned for properly ABI-encoded bytes values,
// revert with "EVMRUN_EXECUTOR_INVALID_RETURN"
// See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in
// this memory layout
mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length
mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason
revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Copy result
//
// Needs to perform an ABI decode for the expected `bytes` return type of
// `executor.execScript()` as solidity will automatically ABI encode the returned bytes as:
// [ position of the first dynamic length return value = 0x20 (32 bytes) ]
// [ output length (32 bytes) ]
// [ output content (N bytes) ]
//
// Perform the ABI decode by ignoring the first 32 bytes of the return data
let copysize := sub(returndatasize, 0x20)
returndatacopy(output, 0x20, copysize)
mstore(0x40, add(output, copysize)) // free mem ptr set
}
}
}
emit ScriptResult(address(executor), _script, _input, output);
return output;
}
modifier protectState {
address preKernel = address(kernel());
bytes32 preAppId = appId();
_; // exec
require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED);
require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED);
}
}
// File: @aragon/os/contracts/apps/AragonApp.sol
/*
* SPDX-License-Identitifer: MIT
*/
pragma solidity ^0.4.24;
// Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so
// that they can never be initialized.
// Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy.
// ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but
// are included so that they are automatically usable by subclassing contracts
contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar {
string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED";
modifier auth(bytes32 _role) {
require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED);
_;
}
modifier authP(bytes32 _role, uint256[] _params) {
require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED);
_;
}
/**
* @dev Check whether an action can be performed by a sender for a particular role on this app
* @param _sender Sender of the call
* @param _role Role on this app
* @param _params Permission params for the role
* @return Boolean indicating whether the sender has the permissions to perform the action.
* Always returns false if the app hasn't been initialized yet.
*/
function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) {
if (!hasInitialized()) {
return false;
}
IKernel linkedKernel = kernel();
if (address(linkedKernel) == address(0)) {
return false;
}
return linkedKernel.hasPermission(
_sender,
address(this),
_role,
ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)
);
}
/**
* @dev Get the recovery vault for the app
* @return Recovery vault address for the app
*/
function getRecoveryVault() public view returns (address) {
// Funds recovery via a vault is only available when used with a kernel
return kernel().getRecoveryVault(); // if kernel is not set, it will revert
}
}
// File: contracts/AddressBook.sol
/*
* SPDX-License-Identitifer: GPL-3.0-or-later
*/
pragma solidity 0.4.24;
/**
* @title AddressBook App
* @author Autark
* @dev Defines an address book (registry) that allows the
* association of an ethereum address with an IPFS CID pointing to JSON content
*/
contract AddressBook is AragonApp {
/// Hardcoded constants to save gas
/// bytes32 public constant ADD_ENTRY_ROLE = keccak256("ADD_ENTRY_ROLE");
bytes32 public constant ADD_ENTRY_ROLE = 0x4a167688760e93a8dd0a899c70e125af7d665ed37fd06496b8c83ce9fdac41bd;
/// bytes32 public constant REMOVE_ENTRY_ROLE = keccak256("REMOVE_ENTRY_ROLE");
bytes32 public constant REMOVE_ENTRY_ROLE = 0x4bf67e2ff5501162fc2ee020c851b17118c126a125e7f189b1c10056a35a8ed1;
/// bytes32 public constant UPDATE_ENTRY_ROLE = keccak256("UPDATE_ENTRY_ROLE");
bytes32 public constant UPDATE_ENTRY_ROLE = 0x6838798f8ade371d93fbc95e535888e5fdc0abba71f87ab7320dd9c8220b4da0;
/// Error string constants
string private constant ERROR_NOT_FOUND = "ENTRY_DOES_NOT_EXIST";
string private constant ERROR_EXISTS = "ENTRY_ALREADY_EXISTS";
string private constant ERROR_CID_MALFORMED = "CID_MALFORMED";
string private constant ERROR_CID_LENGTH = "CID_LENGTH_INCORRECT";
string private constant ERROR_NO_CID = "CID_DOES_NOT_MATCH";
struct Entry {
string data;
uint256 index;
}
/// The entries in the registry
mapping(address => Entry) public entries;
/// Array-like struct to access all addresses
mapping(uint256 => address) public entryArr;
uint256 public entryArrLength;
/// Events
event EntryAdded(address addr); /// Fired when an entry is added to the registry
event EntryRemoved(address addr); /// Fired when an entry is removed from the registry
event EntryUpdated(address addr); /// Fired when an entry is updated with a new CID.
/**
* @dev Guard to check existence of address in the registry
* @param _addr The address to enforce its existence in the registry
*/
modifier entryExists(address _addr) {
require(isEntryAdded(_addr), ERROR_NOT_FOUND);
_;
}
/**
* @dev Guard to ensure the CID is 46 chars long according to base58 encoding
* @param _cid The IPFS hash of the entry to add to the registry
*/
modifier cidIsValid(string _cid) {
bytes memory cidBytes = bytes(_cid);
require(cidBytes[0] == "Q" && cidBytes[1] == "m", ERROR_CID_MALFORMED);
require(cidBytes.length == 46, ERROR_CID_LENGTH);
_;
}
/**
* @notice Initialize AddressBook app
* @dev Initializes the app, this is the Aragon custom constructor
*/
function initialize() external onlyInit {
initialized();
}
/**
* @notice Add `_addr` to the registry with metadata `_cid`
* @dev CIDs must be base58-encoded in order to work with this function
* @param _addr The Ethereum address of the entry to add to the registry
* @param _cid The IPFS hash of the entry to add to the registry
*/
function addEntry(address _addr, string _cid) external cidIsValid(_cid) auth(ADD_ENTRY_ROLE) {
require(bytes(entries[_addr].data).length == 0, ERROR_EXISTS);
// This is auth-guarded, so it'll overflow well after the app becomes unusable
// due to the quantity of entries
uint256 entryIndex = entryArrLength++;
entryArr[entryIndex] = _addr;
entries[_addr] = Entry(_cid, entryIndex);
emit EntryAdded(_addr);
}
/**
* @notice Remove `_addr` from the registry with metadata `_cid`
* @dev this function only supports CIDs that are base58-encoded
* @param _addr The Ethereum address of the entry to remove from the registry
* @param _cid The IPFS hash of the entry to remove from the registry; used only for radspec here
*/
function removeEntry(address _addr, string _cid) external entryExists(_addr) auth(REMOVE_ENTRY_ROLE) {
require(keccak256(bytes(_cid)) == keccak256(bytes(entries[_addr].data)), ERROR_NO_CID);
uint256 rowToDelete = entries[_addr].index;
if (entryArrLength != 1) {
address entryToMove = entryArr[entryArrLength - 1];
entryArr[rowToDelete] = entryToMove;
entries[entryToMove].index = rowToDelete;
}
delete entries[_addr];
// Doesn't require underflow checking because entry existence is verified
entryArrLength--;
emit EntryRemoved(_addr);
}
/**
* @notice Update `_addr` from current metadata `_oldCid` to new metadata `_newCid`
* @dev this function only supports CIDs that are base58-encoded
* @param _addr The Ethereum address of the entry to update
* @param _oldCid The current IPFS hash containing the metadata of the entry
* @param _newCid The new IPFS hash containing the metadata of the entry
*/
function updateEntry(
address _addr,
string _oldCid,
string _newCid
) external auth(UPDATE_ENTRY_ROLE) entryExists(_addr) cidIsValid(_newCid)
{
require(keccak256(bytes(_oldCid)) == keccak256(bytes(entries[_addr].data)), ERROR_NO_CID);
entries[_addr].data = _newCid;
emit EntryUpdated(_addr);
}
/**
* @notice Get data associated to entry `_addr` from the registry.
* @dev getter for the entries mapping to IPFS data
* @param _addr The Ethereum address of the entry to get
* @return contentId pointing to the IPFS structured content object for the entry
*/
function getEntry(address _addr) external view isInitialized returns (string contentId) {
contentId = entries[_addr].data;
}
/**
* @notice Get index associated to entry `_addr` from the registry.
* @dev getter for the entries mapping for an index in entryArr
* @param _addr The Ethereum address of the entry to get
* @return contentId pointing to the IPFS structured content object for the entry
*/
function getEntryIndex(address _addr) external view isInitialized entryExists(_addr) returns (uint256 index) {
index = entries[_addr].index;
}
/**
* @notice Checks if `_entry` exists in the registry
* @param _entry the Ethereum address to check
* @return _repoId Id for entry in entryArr
*/
function isEntryAdded(address _entry) public view returns (bool isAdded) {
if (entryArrLength == 0) {
return false;
}
if (entries[_entry].index >= entryArrLength) {
return false;
}
return (entryArr[entries[_entry].index] == _entry);
}
}
|
Get index associated to entry `_addr` from the registry. getter for the entries mapping for an index in entryArr _addr The Ethereum address of the entry to get return contentId pointing to the IPFS structured content object for the entry/
|
function getEntryIndex(address _addr) external view isInitialized entryExists(_addr) returns (uint256 index) {
index = entries[_addr].index;
}
| 14,077,951
|
//Address: 0x77ceff4173a56cd22b6184fa59c668b364ae55b8
//Contract name: CarTaxiIco
//Balance: 0 Ether
//Verification Date: 9/26/2017
//Transacion Count: 3791
// CODE STARTS HERE
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
contract SafeMath {
uint constant DAY_IN_SECONDS = 86400;
uint constant BASE = 1000000000000000000;
uint constant preIcoPrice = 4101;
uint constant icoPrice = 2255;
function mul(uint256 a, uint256 b) constant internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) constant internal 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) constant internal returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) constant internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function mulByFraction(uint256 number, uint256 numerator, uint256 denominator) internal returns (uint256) {
return div(mul(number, numerator), denominator);
}
// presale volume bonus calculation
function presaleVolumeBonus(uint256 price) internal returns (uint256) {
// preCTX > ETH
uint256 val = div(price, preIcoPrice);
if(val >= 100 * BASE) return add(price, price * 1/20); // 5%
if(val >= 50 * BASE) return add(price, price * 3/100); // 3%
if(val >= 20 * BASE) return add(price, price * 1/50); // 2%
return price;
}
// ICO volume bonus calculation
function volumeBonus(uint256 etherValue) internal returns (uint256) {
if(etherValue >= 1000000000000000000000) return 15;// +15% tokens
if(etherValue >= 500000000000000000000) return 10; // +10% tokens
if(etherValue >= 300000000000000000000) return 7; // +7% tokens
if(etherValue >= 100000000000000000000) return 5; // +5% tokens
if(etherValue >= 50000000000000000000) return 3; // +3% tokens
if(etherValue >= 20000000000000000000) return 2; // +2% tokens
return 0;
}
// ICO date bonus calculation
function dateBonus(uint startIco) internal returns (uint256) {
// day from ICO start
uint daysFromStart = (now - startIco) / DAY_IN_SECONDS + 1;
if(daysFromStart == 1) return 15; // +15% tokens
if(daysFromStart == 2) return 10; // +10% tokens
if(daysFromStart == 3) return 10; // +10% tokens
if(daysFromStart == 4) return 5; // +5% tokens
if(daysFromStart == 5) return 5; // +5% tokens
if(daysFromStart == 6) return 5; // +5% tokens
// no discount
return 0;
}
}
/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20
/// @title Abstract token contract - Functions to be implemented by token contracts.
contract AbstractToken {
// This is not an abstract function, because solc won't recognize generated getter functions for public variables as functions
function totalSupply() constant returns (uint256) {}
function balanceOf(address owner) constant returns (uint256 balance);
function transfer(address to, uint256 value) returns (bool success);
function transferFrom(address from, address to, uint256 value) returns (bool success);
function approve(address spender, uint256 value) returns (bool success);
function allowance(address owner, address spender) constant returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Issuance(address indexed to, uint256 value);
}
contract StandardToken is AbstractToken {
/*
* Data structures
*/
mapping (address => uint256) balances;
mapping (address => bool) ownerAppended;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
address[] public owners;
/*
* Read and write storage functions
*/
/// @dev Transfers sender's tokens to a given address. Returns success.
/// @param _to Address of token receiver.
/// @param _value Number of tokens to transfer.
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value;
if(!ownerAppended[_to]) {
ownerAppended[_to] = true;
owners.push(_to);
}
Transfer(msg.sender, _to, _value);
return true;
}
else {
return false;
}
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success.
/// @param _from Address from where tokens are withdrawn.
/// @param _to Address to where tokens are sent.
/// @param _value Number of tokens to transfer.
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
if(!ownerAppended[_to]) {
ownerAppended[_to] = true;
owners.push(_to);
}
Transfer(_from, _to, _value);
return true;
}
else {
return false;
}
}
/// @dev Returns number of tokens owned by given address.
/// @param _owner Address of token owner.
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/// @dev Sets approved amount of tokens for spender. Returns success.
/// @param _spender Address of allowed account.
/// @param _value Number of approved tokens.
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/*
* Read storage functions
*/
/// @dev Returns number of allowed tokens for given address.
/// @param _owner Address of token owner.
/// @param _spender Address of token spender.
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract CarTaxiToken is StandardToken, SafeMath {
/*
* Token meta data
*/
string public constant name = "CarTaxi";
string public constant symbol = "CTX";
uint public constant decimals = 18;
// tottal supply
address public icoContract = 0x0;
/*
* Modifiers
*/
modifier onlyIcoContract() {
// only ICO contract is allowed to proceed
require(msg.sender == icoContract);
_;
}
/*
* Contract functions
*/
/// @dev Contract is needed in icoContract address
/// @param _icoContract Address of account which will be mint tokens
function CarTaxiToken(address _icoContract) {
assert(_icoContract != 0x0);
icoContract = _icoContract;
}
/// @dev Burns tokens from address. It's can be applied by account with address this.icoContract
/// @param _from Address of account, from which will be burned tokens
/// @param _value Amount of tokens, that will be burned
function burnTokens(address _from, uint _value) onlyIcoContract {
assert(_from != 0x0);
require(_value > 0);
balances[_from] = sub(balances[_from], _value);
}
/// @dev Adds tokens to address. It's can be applied by account with address this.icoContract
/// @param _to Address of account to which the tokens will pass
/// @param _value Amount of tokens
function emitTokens(address _to, uint _value) onlyIcoContract {
assert(_to != 0x0);
require(_value > 0);
balances[_to] = add(balances[_to], _value);
if(!ownerAppended[_to]) {
ownerAppended[_to] = true;
owners.push(_to);
}
}
function getOwner(uint index) constant returns (address, uint256) {
return (owners[index], balances[owners[index]]);
}
function getOwnerCount() constant returns (uint) {
return owners.length;
}
}
contract CarTaxiIco is SafeMath {
/*
* ICO meta data
*/
CarTaxiToken public cartaxiToken;
AbstractToken public preIcoToken;
enum State{
Pause,
Init,
Running,
Stopped,
Migrated
}
State public currentState = State.Pause;
uint public startIcoDate = 0;
// Address of account to which ethers will be tranfered in case of successful ICO
address public escrow;
// Address of manager
address public icoManager;
// Address of a account, that will transfer tokens from pre-ICO
address public tokenImporter = 0x0;
// Addresses of founders and bountyOwner
address public founder1;
address public founder2;
address public founder3;
address public founder4;
address public bountyOwner;
// 487.500.000 CTX tokens
uint public constant supplyLimit = 487500000000000000000000000;
// 12500000 CTX is token for bountyOwner
uint public constant bountyOwnersTokens = 12500000000000000000000000;
// 1 ETH = 2255 CTX
uint public constant PRICE = 2255;
// BASE = 10^18
uint constant BASE = 1000000000000000000;
// 2018.02.04 07:00 UTC
// founders' reward time
uint public foundersRewardTime = 1517727600;
// Amount of imported tokens from pre-ICO
uint public importedTokens = 0;
// Amount of sold tokens on ICO
uint public soldTokensOnIco = 0;
// Amount of issued tokens on pre-ICO = 3047.999951828165582669 * 4101
uint public constant soldTokensOnPreIco = 12499847802447308000000000;
// Tokens to founders can be sent only if sentTokensToFounders == false and time > foundersRewardTime
bool public sentTokensToFounders = false;
// Tokens to bounty owner can be sent only after ICO
bool public sentTokensToBountyOwner = false;
uint public etherRaised = 0;
/*
* Modifiers
*/
modifier whenInitialized() {
// only when contract is initialized
require(currentState >= State.Init);
_;
}
modifier onlyManager() {
// only ICO manager can do this action
require(msg.sender == icoManager);
_;
}
modifier onIcoRunning() {
// Checks, if ICO is running and has not been stopped
require(currentState == State.Running);
_;
}
modifier onIcoStopped() {
// Checks if ICO was stopped or deadline is reached
require(currentState == State.Stopped);
_;
}
modifier notMigrated() {
// Checks if base can be migrated
require(currentState != State.Migrated);
_;
}
modifier onlyImporter() {
// only importer contract is allowed to proceed
require(msg.sender == tokenImporter);
_;
}
/// @dev Constructor of ICO. Requires address of icoManager,
/// @param _icoManager Address of ICO manager
/// @param _preIcoToken Address of pre-ICO contract
function CarTaxiIco(address _icoManager, address _preIcoToken) {
assert(_preIcoToken != 0x0);
assert(_icoManager != 0x0);
cartaxiToken = new CarTaxiToken(this);
icoManager = _icoManager;
preIcoToken = AbstractToken(_preIcoToken);
}
/// @dev Initialises addresses of founders, tokens owner, escrow.
/// Initialises balances of tokens owner
/// @param _founder1 Address of founder 1
/// @param _founder2 Address of founder 2
/// @param _founder3 Address of founder 3
/// @param _founder4 Address of founder 4
/// @param _escrow Address of escrow
function init(address _founder1, address _founder2, address _founder3, address _founder4, address _escrow) onlyManager {
assert(currentState != State.Init);
assert(_founder1 != 0x0);
assert(_founder2 != 0x0);
assert(_founder3 != 0x0);
assert(_founder4 != 0x0);
assert(_escrow != 0x0);
founder1 = _founder1;
founder2 = _founder2;
founder3 = _founder3;
founder4 = _founder4;
escrow = _escrow;
currentState = State.Init;
}
/// @dev Sets new state
/// @param _newState Value of new state
function setState(State _newState) public onlyManager
{
currentState = _newState;
if(currentState == State.Running) {
startIcoDate = now;
}
}
/// @dev Sets new manager. Only manager can do it
/// @param _newIcoManager Address of new ICO manager
function setNewManager(address _newIcoManager) onlyManager {
assert(_newIcoManager != 0x0);
icoManager = _newIcoManager;
}
/// @dev Sets bounty owner. Only manager can do it
/// @param _bountyOwner Address of Bounty owner
function setBountyOwner(address _bountyOwner) onlyManager {
assert(_bountyOwner != 0x0);
bountyOwner = _bountyOwner;
}
// saves info if account's tokens were imported from pre-ICO
mapping (address => bool) private importedFromPreIco;
/// @dev Imports account's tokens from pre-ICO. It can be done only by user, ICO manager or token importer
/// @param _account Address of account which tokens will be imported
function importTokens(address _account) {
// only token holder or manager can do migration
require(msg.sender == icoManager || msg.sender == _account);
require(!importedFromPreIco[_account]);
uint preIcoBal = preIcoToken.balanceOf(_account);
uint preIcoBalance = presaleVolumeBonus(preIcoBal);
if (preIcoBalance > 0) {
cartaxiToken.emitTokens(_account, preIcoBalance);
importedTokens = add(importedTokens, preIcoBalance);
}
importedFromPreIco[_account] = true;
}
/// @dev Buy quantity of tokens depending on the amount of sent ethers.
/// @param _buyer Address of account which will receive tokens
function buyTokens(address _buyer) private {
assert(_buyer != 0x0);
require(msg.value > 0);
uint tokensToEmit = msg.value * PRICE;
//calculate date bonus
uint dateBonusPercent = dateBonus(startIcoDate);
//calculate volume bonus
uint volumeBonusPercent = volumeBonus(msg.value);
//total bonus tokens
uint totalBonusPercent = dateBonusPercent + volumeBonusPercent;
if(totalBonusPercent > 0){
tokensToEmit = tokensToEmit + mulByFraction(tokensToEmit, totalBonusPercent, 100);
}
require(add(soldTokensOnIco, tokensToEmit) <= supplyLimit);
soldTokensOnIco = add(soldTokensOnIco, tokensToEmit);
//emit tokens to token holder
cartaxiToken.emitTokens(_buyer, tokensToEmit);
etherRaised = add(etherRaised, msg.value);
}
/// @dev Fall back function ~50k-100k gas
function () payable onIcoRunning {
buyTokens(msg.sender);
}
/// @dev Burn tokens from accounts only in state "not migrated". Only manager can do it
/// @param _from Address of account
function burnTokens(address _from, uint _value) onlyManager notMigrated {
cartaxiToken.burnTokens(_from, _value);
}
/// @dev Partial withdraw. Only manager can do it
function withdrawEther(uint _value) onlyManager {
require(_value > 0);
assert(_value <= this.balance);
// send 123 to get 1.23
escrow.transfer(_value * 10000000000000000); // 10^16
}
/// @dev Ether withdraw. Only manager can do it
function withdrawAllEther() onlyManager {
if(this.balance > 0)
{
escrow.transfer(this.balance);
}
}
///@dev Send tokens to bountyOwner depending on crowdsale results. Can be send only after ICO.
function sendTokensToBountyOwner() onlyManager whenInitialized {
require(!sentTokensToBountyOwner);
//Calculate total tokens sold on pre-ICO and ICO
uint tokensSold = add(soldTokensOnIco, soldTokensOnPreIco);
//Calculate bounty tokens depending on total tokens sold
uint bountyTokens = mulByFraction(tokensSold, 25, 1000); // 2.5%
cartaxiToken.emitTokens(bountyOwner, bountyTokens);
sentTokensToBountyOwner = true;
}
/// @dev Send tokens to founders. Can be sent only after cartaxiToken.rewardTime() (2018.02.04 0:00 UTC)
function sendTokensToFounders() onlyManager whenInitialized {
require(!sentTokensToFounders && now >= foundersRewardTime);
//Calculate total tokens sold on pre-ICO and ICO
uint tokensSold = add(soldTokensOnIco, soldTokensOnPreIco);
//Calculate founder reward depending on total tokens sold
uint totalRewardToFounders = mulByFraction(tokensSold, 3166, 10000); // 31.66%
uint founderReward = mulByFraction(totalRewardToFounders, 25, 100); // 25% pie
//send every founder 25% of total founder reward
cartaxiToken.emitTokens(founder1, founderReward);
cartaxiToken.emitTokens(founder2, founderReward);
cartaxiToken.emitTokens(founder3, founderReward);
cartaxiToken.emitTokens(founder4, founderReward);
sentTokensToFounders = true;
}
}
|
Send tokens to bountyOwner depending on crowdsale results. Can be send only after ICO.Calculate total tokens sold on pre-ICO and ICOCalculate bounty tokens depending on total tokens sold
|
function sendTokensToBountyOwner() onlyManager whenInitialized {
require(!sentTokensToBountyOwner);
uint tokensSold = add(soldTokensOnIco, soldTokensOnPreIco);
cartaxiToken.emitTokens(bountyOwner, bountyTokens);
sentTokensToBountyOwner = true;
}
| 6,349,669
|
// CryptoPuppies Source code
// Copied from: https://etherscan.io/address/0x06012c8cf97bead5deae237070f9587f8e7a266d#code
pragma solidity ^0.4.11;
/**
* @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() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <dete@axiomzen.co> (https://github.com/dete)
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);
}
// // Auction wrapper functions
// Auction wrapper functions
/// @title SEKRETOOOO
contract GeneScience {
/// @dev simply a boolean to indicate this is the contract we expect to be
function isGeneScience() public pure returns (bool);
/// @dev given genes of puppies 1 & 2, return a genetic combination - may have a random factor
/// @param genes1 genes of mom
/// @param genes2 genes of sire
/// @return the genes that are supposed to be passed down the child
function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256);
}
/// @title Puppy sports contract
contract PuppySports {
/// @dev simply a boolean to indipuppye this is the contract we expect to be
function isPuppySports() public pure returns (bool);
/// @dev contract that provides gaming functionality
/// @param puppyId - id of the puppy
/// @param gameId - id of the game
/// @param targetBlock - proof of randomness
/// @return true if puppy won the game, false otherwise
function playGame(uint256 puppyId, uint256 gameId, uint256 targetBlock) public returns (bool);
}
/// @title A facet of PuppiesCore that manages special access privileges.
/// @author SmartFoxLabs
/// @dev See the PuppiesCore contract documentation to understand how the various contract facets are arranged.
contract PuppyAccessControl {
// This facet controls access control for CryptoPuppies. 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 PuppiesCore constructor.
//
// - The CFO: The CFO can withdraw funds from PuppiesCore and its auction contracts.
//
// - The COO: The COO can release gen0 puppies to auction, and mint promo puppys.
//
// 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);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
/// @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 CryptoPuppies. Holds all common structs, events and base variables.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the PuppiesCore contract documentation to understand how the various contract facets are arranged.
contract PuppyBase is PuppyAccessControl {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new puppy comes into existence. This obviously
/// includes any time a puppy is created through the giveBirth method, but it is also called
/// when a new gen0 puppy is created.
event Birth(address owner, uint256 puppyId, uint256 matronId, uint256 sireId, uint256 genes);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a puppy
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// @dev The main Puppy struct. Every puppy in CryptoPuppies 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 Puppy {
// The Puppy's genetic code is packed into these 256-bits, the format is
// sooper-sekret! A puppy's genes never change.
uint256 genes;
// The timestamp from the block when this puppy came into existence.
uint64 birthTime;
// The minimum timestamp after which this puppy can engage in breeding
// activities again. This same timestamp is used for the pregnancy
// timer (for matrons) as well as the siring cooldown.
uint64 cooldownEndBlock;
// The ID of the parents of this Puppy, set to 0 for gen0 puppys.
// Note that using 32-bit unsigned integers limits us to a "mere"
// 4 billion puppys. This number might seem small until you realize
// that Ethereum currently has a limit of about 500 million
// transactions per year! So, this definitely won't be a problem
// for several years (even as Ethereum learns to scale).
uint32 matronId;
uint32 sireId;
// Set to the ID of the sire puppy for matrons that are pregnant,
// zero otherwise. A non-zero value here is how we know a puppy
// is pregnant. Used to retrieve the genetic material for the new
// puppy when the birth transpires.
uint32 siringWithId;
// Set to the index in the cooldown array (see below) that represents
// the current cooldown duration for this Puppy. This starts at zero
// for gen0 puppys, and is initialized to floor(generation/2) for others.
// Incremented by one for each successful breeding action, regardless
// of whether this puppy is acting as matron or sire.
uint16 cooldownIndex;
// The "generation number" of this puppy. puppys minted by the CK contract
// for sale are called "gen0" and have a generation number of 0. The
// generation number of all other puppys is the larger of the two generation
// numbers of their parents, plus one.
// (i.e. max(matron.generation, sire.generation) + 1)
uint16 generation;
uint16 childNumber;
uint16 strength;
uint16 agility;
uint16 intelligence;
uint16 speed;
}
/*** CONSTANTS ***/
/// @dev A lookup table indipuppying the cooldown duration after any successful
/// breeding action, called "pregnancy time" for matrons and "siring cooldown"
/// for sires. Designed such that the cooldown roughly doubles each time a puppy
/// is bred, encouraging owners not to just keep breeding the same puppy over
/// and over again. Caps out at one week (a puppy can breed an unbounded number
/// of times, and the maximum cooldown is always seven days).
uint32[14] public cooldowns = [
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(10 minutes),
uint32(30 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the Puppy struct for all puppies in existence. The ID
/// of each puppy is actually an index into this array. Note that ID 0 is a negapuppy,
/// the unPuppy, the mythical beast that is the parent of all gen0 puppys. A bizarre
/// creature that is both matron and sire... to itself! Has an invalid genetic code.
/// In other words, puppy ID 0 is invalid... ;-)
Puppy[] puppies;
/// @dev A mapping from puppy IDs to the address that owns them. All puppys have
/// some valid owner address, even gen0 puppys are created with a non-zero owner.
mapping (uint256 => address) public PuppyIndexToOwner;
// @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 puppyIds to an address that has been approved to call
/// transferFrom(). Each Puppy can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public PuppyIndexToApproved;
/// @dev A mapping from puppyIds to an address that has been approved to use
/// this Puppy for siring via breedWith(). Each Puppy can only have one approved
/// address for siring at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public sireAllowedToAddress;
/// @dev The address of the ClockAuction contract that handles sales of puppies. This
/// same contract handles both peer-to-peer sales as well as the gen0 sales which are
/// initiated every 15 minutes.
SaleClockAuction public saleAuction;
/// @dev The address of a custom ClockAuction subclassed contract that handles siring
/// auctions. Needs to be separate from saleAuction because the actions taken on success
/// after a sales and siring auction are quite different.
SiringClockAuction public siringAuction;
/// @dev Assigns ownership of a specific Puppy to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of puppys is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
PuppyIndexToOwner[_tokenId] = _to;
// When creating new puppys _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// once the puppy is transferred also clear sire allowances
delete sireAllowedToAddress[_tokenId];
// clear any previously approved ownership exchange
delete PuppyIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
/// @dev An internal method that creates a new Puppy 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 _matronId The Puppy ID of the matron of this puppy (zero for gen0)
/// @param _sireId The Puppy ID of the sire of this puppy (zero for gen0)
/// @param _generation The generation number of this puppy, must be computed by caller.
/// @param _genes The Puppy's genetic code.
/// @param _owner The inital owner of this puppy, must be non-zero (except for the unPuppy, ID 0)
function _createPuppy(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner,
uint16 _strength,
uint16 _agility,
uint16 _intelligence,
uint16 _speed
)
internal
returns (uint)
{
// These requires are not strictly necessary, our calling code should make
// sure that these conditions are never broken. However! _createPuppy() is already
// an expensive call (for storage), and it doesn't hurt to be especially careful
// to ensure our data structures are always valid.
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
// New Puppy starts with the same cooldown as parent gen/2
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
Puppy memory _puppy = Puppy({
genes: _genes,
birthTime: uint64(now),
cooldownEndBlock: 0,
matronId: uint32(_matronId),
sireId: uint32(_sireId),
siringWithId: 0,
cooldownIndex: cooldownIndex,
generation: uint16(_generation),
childNumber: 0,
strength: _strength,
agility: _agility,
intelligence: _intelligence,
speed: _speed
});
uint256 newpuppyId = puppies.push(_puppy) - 1;
// It's probably never going to happen, 4 billion puppys is A LOT, but
// let's just be 100% sure we never let this happen.
require(newpuppyId == uint256(uint32(newpuppyId)));
// emit the birth event
Birth(
_owner,
newpuppyId,
uint256(_puppy.matronId),
uint256(_puppy.sireId),
_puppy.genes
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newpuppyId);
return newpuppyId;
}
// Any C-level can fix how many seconds per blocks are currently observed.
function setSecondsPerBlock(uint256 secs) external onlyCLevel {
require(secs < cooldowns[0]);
secondsPerBlock = secs;
}
}
/// @title The external contract that is responsible for generating metadata for the puppies,
/// 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 view 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 The facet of the CryptoPuppies core contract that manages ownership, ERC-721 (draft) compliant.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the PuppiesCore contract documentation to understand how the various contract facets are arranged.
contract PuppyOwnership is PuppyBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "CryptoPuppies";
string public constant symbol = "CP";
// The contract that will return Puppy metadata
ERC721Metadata public erc721Metadata;
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));
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// CEO only.
function setMetadataAddress(address _contractAddress) public onlyCEO {
erc721Metadata = ERC721Metadata(_contractAddress);
}
// 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 Puppy.
/// @param _claimant the address we are validating against.
/// @param _tokenId puppy id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return PuppyIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Puppy.
/// @param _claimant the address we are confirming puppy is approved for.
/// @param _tokenId puppy id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return PuppyIndexToApproved[_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 puppies on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
PuppyIndexToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of puppies 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];
}
/// @notice Transfers a Puppy to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// CryptoPuppies specifically) or your Puppy may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Puppy 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 puppies (except very briefly
// after a gen0 puppy 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 puppies
// through the allow + transferFrom flow.
require(_to != address(saleAuction));
require(_to != address(siringAuction));
// You can only send your own puppy.
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 Puppy 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 Puppy 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 Puppy 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 Puppy to be transfered.
/// @param _to The address that should take ownership of the Puppy. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Puppy 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 puppies (except very briefly
// after a gen0 puppy 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 puppies currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return puppies.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given Puppy.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = PuppyIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all Puppy IDs assigned to an address.
/// @param _owner The owner whose puppies we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Puppy array looking for puppys 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 totalpuppys = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all puppys have IDs starting at 1 and increasing
// sequentially up to the totalpuppy count.
uint256 puppyId;
for (puppyId = 1; puppyId <= totalpuppys; puppyId++) {
if (PuppyIndexToOwner[puppyId] == _owner) {
result[resultIndex] = puppyId;
resultIndex++;
}
}
return result;
}
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>)
/// 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 <arachnid@notdot.net>)
/// 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;
}
/// @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 Puppy 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);
}
}
/// @title A facet of PuppiesCore that manages Puppy siring, gestation, and birth.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the PuppiesCore contract documentation to understand how the various contract facets are arranged.
contract PuppyBreeding is PuppyOwnership {
/// @dev The Pregnant event is fired when two puppys successfully breed and the pregnancy
/// timer begins for the matron.
event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock);
/// @notice The minimum payment required to use breedWithAuto(). This fee goes towards
/// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by
/// the COO role as the gas price changes.
uint256 public autoBirthFee = 8 finney;
// Keeps track of number of pregnant puppies.
uint256 public pregnantpuppies;
uint256 public minChildCount = 2;
uint256 public maxChildCount = 14;
uint randNonce = 0;
/// @dev The address of the sibling contract that is used to implement the sooper-sekret
/// genetic combination algorithm.
GeneScience public geneScience;
PuppySports public puppySports;
function setMinChildCount(uint256 _minChildCount) onlyCOO whenNotPaused {
require(_minChildCount >= 2);
minChildCount = _minChildCount;
}
function setMaxChildCount(uint256 _maxChildCount) onlyCOO whenNotPaused {
require(_maxChildCount > minChildCount);
maxChildCount = _maxChildCount;
}
function setGeneScienceAddress(address _address) external onlyCEO {
GeneScience candidateContract = GeneScience(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isGeneScience());
// Set the new contract address
geneScience = candidateContract;
}
function setPuppySports(address _address) external onlyCEO {
PuppySports candidateContract = PuppySports(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isPuppySports());
// Set the new contract address
puppySports = candidateContract;
}
/// @dev Checks that a given puppy is able to breed. Requires that the
/// current cooldown is finished (for sires) and also checks that there is
/// no pending pregnancy.
function _isReadyToBreed(Puppy _pup) internal view returns (bool) {
// In addition to checking the cooldownEndBlock, we also need to check to see if
// the puppy has a pending birth; there can be some period of time between the end
// of the pregnacy timer and the birth event.
uint256 numberOfAllowedChild = maxChildCount - _pup.generation * 2;
if (numberOfAllowedChild < minChildCount) {
numberOfAllowedChild = minChildCount;
}
bool isChildLimitNotReached = _pup.childNumber < numberOfAllowedChild;
return (_pup.siringWithId == 0) && (_pup.cooldownEndBlock <= uint64(block.number)) && isChildLimitNotReached;
}
/// @dev Check if a sire has authorized breeding with this matron. True if both sire
/// and matron have the same owner, or if the sire has given siring permission to
/// the matron's owner (via approveSiring()).
function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) {
address matronOwner = PuppyIndexToOwner[_matronId];
address sireOwner = PuppyIndexToOwner[_sireId];
// Siring is okay if they have same owner, or if the matron's owner was given
// permission to breed with this sire.
return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner);
}
/// @dev Set the cooldownEndTime for the given Puppy, based on its current cooldownIndex.
/// Also increments the cooldownIndex (unless it has hit the cap).
/// @param _puppy A reference to the Puppy in storage which needs its timer started.
function _triggerCooldown(Puppy storage _puppy) internal {
// Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).
_puppy.cooldownEndBlock = uint64((cooldowns[_puppy.cooldownIndex]/secondsPerBlock) + block.number);
// Increment the breeding count, clamping it at 13, which is the length of the
// cooldowns array. We could check the array size dynamically, but hard-coding
// this as a constant saves gas. Yay, Solidity!
if (_puppy.cooldownIndex < 13) {
_puppy.cooldownIndex += 1;
}
}
/// @dev Set the cooldownEndTime for the given Puppy, based on its current cooldownIndex.
/// Also increments the cooldownIndex (unless it has hit the cap).
/// @param _puppy A reference to the Puppy in storage which needs its timer started.
function _triggerChildCount(Puppy storage _puppy) internal {
// Increment the child count
_puppy.childNumber += 1;
}
/// @notice Grants approval to another user to sire with one of your puppies.
/// @param _addr The address that will be able to sire with your Puppy. Set to
/// address(0) to clear all siring approvals for this Puppy.
/// @param _sireId A Puppy that you own that _addr will now be able to sire with.
function approveSiring(address _addr, uint256 _sireId)
external
whenNotPaused
{
require(_owns(msg.sender, _sireId));
sireAllowedToAddress[_sireId] = _addr;
}
/// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only
/// be called by the COO address. (This fee is used to offset the gas cost incurred
/// by the autobirth daemon).
function setAutoBirthFee(uint256 val) external onlyCOO {
autoBirthFee = val;
}
/// @dev Checks to see if a given Puppy is pregnant and (if so) if the gestation
/// period has passed.
function _isReadyToGiveBirth(Puppy _matron) private view returns (bool) {
return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number));
}
/// @notice Checks that a given puppy is able to breed (i.e. it is not pregnant or
/// in the middle of a siring cooldown).
/// @param _puppyId reference the id of the puppy, any user can inquire about it
function isReadyToBreed(uint256 _puppyId)
public
view
returns (bool)
{
require(_puppyId > 0);
Puppy storage pup = puppies[_puppyId];
return _isReadyToBreed(pup);
}
/// @dev Checks whether a Puppy is currently pregnant.
/// @param _puppyId reference the id of the puppy, any user can inquire about it
function isPregnant(uint256 _puppyId)
public
view
returns (bool)
{
require(_puppyId > 0);
// A Puppy is pregnant if and only if this field is set
return puppies[_puppyId].siringWithId != 0;
}
/// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT
/// check ownership permissions (that is up to the caller).
/// @param _matron A reference to the Puppy struct of the potential matron.
/// @param _matronId The matron's ID.
/// @param _sire A reference to the Puppy struct of the potential sire.
/// @param _sireId The sire's ID
function _isValidMatingPair(
Puppy storage _matron,
uint256 _matronId,
Puppy storage _sire,
uint256 _sireId
)
private
view
returns(bool)
{
// A Puppy can't breed with itself!
if (_matronId == _sireId) {
return false;
}
// puppies can't breed with their parents.
if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
return false;
}
if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
return false;
}
// We can short circuit the sibling check (below) if either puppy is
// gen zero (has a matron ID of zero).
if (_sire.matronId == 0 || _matron.matronId == 0) {
return true;
}
// puppies can't breed with full or half siblings.
if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) {
return false;
}
if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) {
return false;
}
// Everything seems cool! Let's get DTF.
return true;
}
/// @dev Internal check to see if a given sire and matron are a valid mating pair for
/// breeding via auction (i.e. skips ownership and siring approval checks).
function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId)
internal
view
returns (bool)
{
Puppy storage matron = puppies[_matronId];
Puppy storage sire = puppies[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId);
}
/// @notice Checks to see if two puppys can breed together, including checks for
/// ownership and siring approvals. Does NOT check that both puppys are ready for
/// breeding (i.e. breedWith could still fail until the cooldowns are finished).
/// TODO: Shouldn't this check pregnancy and cooldowns?!?
/// @param _matronId The ID of the proposed matron.
/// @param _sireId The ID of the proposed sire.
function canBreedWith(uint256 _matronId, uint256 _sireId)
external
view
returns(bool)
{
require(_matronId > 0);
require(_sireId > 0);
Puppy storage matron = puppies[_matronId];
Puppy storage sire = puppies[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId) &&
_isSiringPermitted(_sireId, _matronId);
}
/// @dev Internal utility function to initiate breeding, assumes that all breeding
/// requirements have been checked.
function _breedWith(uint256 _matronId, uint256 _sireId) internal {
// Grab a reference to the puppies from storage.
Puppy storage sire = puppies[_sireId];
Puppy storage matron = puppies[_matronId];
// Mark the matron as pregnant, keeping track of who the sire is.
matron.siringWithId = uint32(_sireId);
// Trigger the cooldown for both parents.
_triggerCooldown(sire);
_triggerCooldown(matron);
_triggerChildCount(sire);
_triggerChildCount(matron);
// Clear siring permission for both parents. This may not be strictly necessary
// but it's likely to avoid confusion!
delete sireAllowedToAddress[_matronId];
delete sireAllowedToAddress[_sireId];
// Every time a Puppy gets pregnant, counter is incremented.
pregnantpuppies++;
// Emit the pregnancy event.
Pregnant(PuppyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock);
}
/// @notice Breed a Puppy you own (as matron) with a sire that you own, or for which you
/// have previously been given Siring approval. Will either make your puppy pregnant, or will
/// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth()
/// @param _matronId The ID of the Puppy acting as matron (will end up pregnant if successful)
/// @param _sireId The ID of the Puppy acting as sire (will begin its siring cooldown if successful)
function breedWithAuto(uint256 _matronId, uint256 _sireId)
external
payable
whenNotPaused
{
// Checks for payment.
require(msg.value >= autoBirthFee);
// Caller must own the matron.
require(_owns(msg.sender, _matronId));
// Neither sire nor matron are allowed to be on auction during a normal
// breeding operation, but we don't need to check that explicitly.
// For matron: The caller of this function can't be the owner of the matron
// because the owner of a Puppy on auction is the auction house, and the
// auction house will never call breedWith().
// For sire: Similarly, a sire on auction will be owned by the auction house
// and the act of transferring ownership will have cleared any oustanding
// siring approval.
// Thus we don't need to spend gas explicitly checking to see if either puppy
// is on auction.
// Check that matron and sire are both owned by caller, or that the sire
// has given siring permission to caller (i.e. matron's owner).
// Will fail for _sireId = 0
require(_isSiringPermitted(_sireId, _matronId));
// Grab a reference to the potential matron
Puppy storage matron = puppies[_matronId];
// Make sure matron isn't pregnant, or in the middle of a siring cooldown
require(_isReadyToBreed(matron));
// Grab a reference to the potential sire
Puppy storage sire = puppies[_sireId];
// Make sure sire isn't pregnant, or in the middle of a siring cooldown
require(_isReadyToBreed(sire));
// Test that these puppys are a valid mating pair.
require(_isValidMatingPair(
matron,
_matronId,
sire,
_sireId
));
// All checks passed, Puppy gets pregnant!
_breedWith(_matronId, _sireId);
}
function playGame(uint256 _puppyId, uint256 _gameId)
external
whenNotPaused
returns(bool)
{
require(puppySports != address(0));
require(_owns(msg.sender, _puppyId));
return puppySports.playGame(_puppyId, _gameId, block.number);
}
/// @notice Have a pregnant Puppy give birth!
/// @param _matronId A Puppy ready to give birth.
/// @return The Puppy ID of the new puppy.
/// @dev Looks at a given Puppy and, if pregnant and if the gestation period has passed,
/// combines the genes of the two parents to create a new puppy. The new Puppy is assigned
/// to the current owner of the matron. Upon successful completion, both the matron and the
/// new puppy will be ready to breed again. Note that anyone can call this function (if they
/// are willing to pay the gas!), but the new puppy always goes to the mother's owner.
function giveBirth(uint256 _matronId) payable
external
whenNotPaused
returns(uint256)
{
// Grab a reference to the matron in storage.
Puppy storage matron = puppies[_matronId];
// Check that the matron is a valid puppy.
require(matron.birthTime != 0);
// Check that the matron is pregnant, and that its time has come!
require(_isReadyToGiveBirth(matron));
// Grab a reference to the sire in storage.
uint256 sireId = matron.siringWithId;
Puppy storage sire = puppies[sireId];
// Determine the higher generation number of the two parents
uint16 parentGen = matron.generation;
if (sire.generation > matron.generation) {
parentGen = sire.generation;
}
// Call the sooper-sekret gene mixing operation.
//uint256 childGenes = _babyGenes;
uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1);
// Make the new puppy!
address owner = PuppyIndexToOwner[_matronId];
// Add randomizer for attributes
uint16 strength = uint16(random(_matronId));
uint16 agility = uint16(random(strength));
uint16 intelligence = uint16(random(agility));
uint16 speed = uint16(random(intelligence));
uint256 puppyId = _createPuppy(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner, strength, agility, intelligence, speed);
// Clear the reference to sire from the matron (REQUIRED! Having siringWithId
// set is what marks a matron as being pregnant.)
delete matron.siringWithId;
// Every time a Puppy gives birth counter is decremented.
pregnantpuppies--;
// Send the balance fee to the person who made birth happen.
msg.sender.send(autoBirthFee);
// return the new puppy's ID
return puppyId;
}
//random
function random(uint256 seed) public view returns (uint8 randomNumber) {
uint8 rnd = uint8(keccak256(
seed,
block.blockhash(block.number - 1),
block.coinbase,
block.difficulty
)) % 100 + uint8(1);
return rnd % 100 + 1;
}
}
/// @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) 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 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)
);
}
/// @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 multiplipuppyion 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 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 allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
/// @title Clock auction for non-fungible tokens.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuction is Pausable, 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 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
);
// 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
whenNotPaused
{
// Sanity check that no inputs overflow how many bits we've allopuppyed
// 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 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 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);
}
}
/// @title Reverse auction modified for siring
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SiringClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSiringAuctionAddress() call.
bool public isSiringClockAuction = true;
// Delegate constructor
function SiringClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut)
{
}
/// @dev Creates and begins a new auction. Since this function is wrapped,
/// require sender to be PuppiesCore contract.
/// @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 allopuppyed
// 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 Places a bid for siring. Requires the sender
/// is the PuppiesCore contract because all bid methods
/// should be wrapped. Also returns the Puppy to the
/// seller rather than the winner.
function bid(uint256 _tokenId)
external
payable
{
require(msg.sender == address(nonFungibleContract));
address seller = tokenIdToAuction[_tokenId].seller;
// _bid checks that token ID is valid and will throw if bid fails
_bid(_tokenId, msg.value);
// We transfer the Puppy back to the seller, the winner will get
// the offspring
_transfer(seller, _tokenId);
}
}
/// @title Clock auction modified for sale of puppies
/// @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 gen0 Puppy sales
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 allopuppyed
// 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;
}
}
/// @title Handles creating auctions for sale and siring of puppies.
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract PuppiesAuction is PuppyBreeding {
// @notice The auction contract variables are defined in PuppyBase to allow
// us to refer to them in PuppyOwnership to prevent accidental transfers.
// `saleAuction` refers to the auction for gen0 and p2p sale of puppies.
// `siringAuction` refers to the auction for siring rights of puppies.
/// @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 Sets the reference to the siring auction.
/// @param _address - Address of siring contract.
function setSiringAuctionAddress(address _address) external onlyCEO {
SiringClockAuction candidateContract = SiringClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSiringClockAuction());
// Set the new contract address
siringAuction = candidateContract;
}
/// @dev Put a Puppy up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createPuppySaleAuction(
uint256 _puppyId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If Puppy is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _puppyId));
// Ensure the Puppy is not pregnant to prevent the auction
// contract accidentally receiving ownership of the child.
// NOTE: the Puppy IS allowed to be in a cooldown.
require(!isPregnant(_puppyId));
_approve(_puppyId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the Puppy.
saleAuction.createAuction(
_puppyId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Put a Puppy up for auction to be sire.
/// Performs checks to ensure the Puppy can be sired, then
/// delegates to reverse auction.
function createPuppySiringAuctiona(
uint256 _puppyId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If Puppy is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _puppyId));
require(isReadyToBreed(_puppyId));
_approve(_puppyId, siringAuction);
// Siring auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the Puppy.
siringAuction.createAuction(
_puppyId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Completes a siring auction by bidding.
/// Immediately breeds the winning matron with the sire on auction.
/// @param _sireId - ID of the sire on auction.
/// @param _matronId - ID of the matron owned by the bidder.
function bidOnSiringAuction(
uint256 _sireId,
uint256 _matronId
)
external
payable
whenNotPaused
{
// Auction contract checks input sizes
require(_owns(msg.sender, _matronId));
require(isReadyToBreed(_matronId));
require(_canBreedWithViaAuction(_matronId, _sireId));
// Define the current price of the auction.
uint256 currentPrice = siringAuction.getCurrentPrice(_sireId);
require(msg.value >= currentPrice + autoBirthFee);
// Siring auction will throw if the bid fails.
siringAuction.bid.value(msg.value - autoBirthFee)(_sireId);
_breedWith(uint32(_matronId), uint32(_sireId));
}
/// @dev Transfers the balance of the sale auction contract
/// to the PuppiesCore contract. We use two-step withdrawal to
/// prevent two transfer calls in the auction bid function.
function withdrawAuctionBalances() external onlyCLevel {
saleAuction.withdrawBalance();
siringAuction.withdrawBalance();
}
}
/// @title all functions related to creating puppys
contract PuppiesMinting is PuppiesAuction {
// Limits the number of puppys the contract owner can ever create.
uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant GEN0_CREATION_LIMIT = 15000;
// Constants for gen0 auctions.
uint256 public constant GEN0_STARTING_PRICE = 100 finney;
uint256 public constant GEN0_MINIMAL_PRICE = 10 finney;
uint256 public constant GEN0_AUCTION_DURATION = 2 days;
// Counts the number of puppys the contract owner has created.
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
/// @dev we can create promo puppys, up to a limit. Only callable by COO
/// @param _genes the encoded genes of the puppy to be created, any value is accepted
/// @param _owner the future owner of the created puppys. Default to contract COO
function createPromoPuppy(uint256 _genes, address _owner, uint16 _strength, uint16 _agility, uint16 _intelligence, uint16 _speed) external onlyCOO {
address puppyOwner = _owner;
if (puppyOwner == address(0)) {
puppyOwner = cooAddress;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createPuppy(0, 0, 0, _genes, puppyOwner, _strength, _agility, _intelligence, _speed);
}
/// @dev Creates a new gen0 Puppy with the given genes and
/// creates an auction for it.
function createGen0Auction(uint256 _genes, uint16 _strength, uint16 _agility, uint16 _intelligence, uint16 _speed, uint16 _talent) external onlyCOO {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
uint256 puppyId = _createPuppy(0, 0, 0, _genes, address(this), _strength, _agility, _intelligence, _speed);
_approve(puppyId, saleAuction);
saleAuction.createAuction(
puppyId,
_computeNextGen0Price(),
GEN0_MINIMAL_PRICE,
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;
}
}
/// @title CryptoPuppies: Collectible, breedable, and oh-so-adorable puppys on the Ethereum blockchain.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev The main CryptoPuppies contract, keeps track of puppys so they don't wander around and get lost.
contract PuppiesCore is PuppiesMinting {
// This is the main CryptoPuppies 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
// Puppy 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:
//
// - PuppyBase: 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.
//
// - PuppyAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - PuppyOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - PuppyBreeding: This file contains the methods necessary to breed puppys together, including
// keeping track of siring offers, and relies on an external genetic combination contract.
//
// - PuppyAuctions: Here we have the public methods for auctioning or bidding on puppys or siring
// services. The actual auction functionality is handled in two sibling contracts (one
// for sales and one for siring), while auction creation and bidding is mostly mediated
// through this facet of the core contract.
//
// - PuppiesMinting: This final facet contains the functionality we use for creating new gen0 puppys.
// We can make up to 5000 "promo" puppys 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 50k gen0 puppys. After that, it's all up to the
// community to breed, breed, breed!
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main CryptoPuppies smart contract instance.
function PuppiesCore() 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 mythical puppy 0 - so we don't have generation-0 parent issues
_createPuppy(0, 0, 0, uint256(-1), address(0), 0, 0, 0, 0);
}
/// @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 indipuppying 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);
}
/// @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) ||
msg.sender == address(siringAuction)
);
}
/// @notice Returns all the relevant information about a specific Puppy.
/// @param _id The ID of the Puppy of interest.
function getPuppy(uint256 _id)
external
view
returns (
bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes
) {
Puppy storage pup = puppies[_id];
// if this variable is 0 then it's not gestating
isGestating = (pup.siringWithId != 0);
isReady = (pup.cooldownEndBlock <= block.number);
cooldownIndex = uint256(pup.cooldownIndex);
nextActionAt = uint256(pup.cooldownEndBlock);
siringWithId = uint256(pup.siringWithId);
birthTime = uint256(pup.birthTime);
matronId = uint256(pup.matronId);
sireId = uint256(pup.sireId);
generation = uint256(pup.generation);
genes = pup.genes;
}
function getPuppyAttributes(uint256 _id)
external
view
returns (
uint16 childNumber,
uint16 strength,
uint16 agility,
uint16 intelligence,
uint16 speed
) {
Puppy storage pup = puppies[_id];
// if this variable is 0 then it's not gestating
childNumber = uint16(pup.childNumber);
strength = uint16(pup.strength);
agility = uint16(pup.agility);
intelligence = uint16(pup.intelligence);
speed = uint16(pup.speed);
}
/// @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(siringAuction != address(0));
//require(geneScience != address(0));
//require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
// @dev Allows the CFO to capture the balance available to the contract.
function withdrawBalance() external onlyCFO {
uint256 balance = this.balance;
// Subtract all the currently pregnant puppys we have, plus 1 of margin.
uint256 subtractFees = (pregnantpuppies + 1) * autoBirthFee;
if (balance > subtractFees) {
cfoAddress.send(balance - subtractFees);
}
}
}
|
Returns a URI pointing to a metadata package for this token conforming to ERC-721 (https://github.com/ethereum/EIPs/issues/721) _tokenId The ID number of the Puppy 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);
}
| 498,291
|
./full_match/42161/0x68bfbe1001568da0FeD281a1C99A16794bDa2754/sources/contracts/libraries/LinkedListLibrary.sol
|
pops the first entry from the linked list self stored linked list from contract _direction pop from the head (NEXT) or the tail (PREV)
|
function pop(LinkedList storage self, bool _direction) internal returns (uint256) {
bool exists;
uint256 adj;
(exists, adj) = getAdjacent(self, HEAD, _direction);
return remove(self, adj);
}
| 16,301,309
|
pragma solidity ^0.4.18;
contract HasManager {
address public manager;
modifier onlyManager {
require(msg.sender == manager);
_;
}
function transferManager(address _newManager) public onlyManager() {
require(_newManager != address(0));
manager = _newManager;
}
}
contract Ownable {
address public owner;
function Ownable() public { owner = msg.sender; }
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {owner = newOwner;}
}contract IERC20 {
function totalSupply() public constant returns (uint256);
function balanceOf(address _owner) public constant returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
function allowance(address _owner, address _spender) public constant returns (uint256);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// Crowdsale contracts interface
contract ICrowdsaleProcessor is Ownable, HasManager {
modifier whenCrowdsaleAlive() {
require(isActive());
_;
}
modifier whenCrowdsaleFailed() {
require(isFailed());
_;
}
modifier whenCrowdsaleSuccessful() {
require(isSuccessful());
_;
}
modifier hasntStopped() {
require(!stopped);
_;
}
modifier hasBeenStopped() {
require(stopped);
_;
}
modifier hasntStarted() {
require(!started);
_;
}
modifier hasBeenStarted() {
require(started);
_;
}
// Minimal acceptable hard cap
uint256 constant public MIN_HARD_CAP = 1 ether;
// Minimal acceptable duration of crowdsale
uint256 constant public MIN_CROWDSALE_TIME = 3 days;
// Maximal acceptable duration of crowdsale
uint256 constant public MAX_CROWDSALE_TIME = 50 days;
// Becomes true when timeframe is assigned
bool public started;
// Becomes true if cancelled by owner
bool public stopped;
// Total collected Ethereum: must be updated every time tokens has been sold
uint256 public totalCollected;
// Total amount of project's token sold: must be updated every time tokens has been sold
uint256 public totalSold;
// Crowdsale minimal goal, must be greater or equal to Forecasting min amount
uint256 public minimalGoal;
// Crowdsale hard cap, must be less or equal to Forecasting max amount
uint256 public hardCap;
// Crowdsale duration in seconds.
// Accepted range is MIN_CROWDSALE_TIME..MAX_CROWDSALE_TIME.
uint256 public duration;
// Start timestamp of crowdsale, absolute UTC time
uint256 public startTimestamp;
// End timestamp of crowdsale, absolute UTC time
uint256 public endTimestamp;
// Allows to transfer some ETH into the contract without selling tokens
function deposit() public payable {}
// Returns address of crowdsale token, must be ERC20 compilant
function getToken() public returns(address);
// Transfers ETH rewards amount (if ETH rewards is configured) to Forecasting contract
function mintETHRewards(address _contract, uint256 _amount) public onlyManager();
// Mints token Rewards to Forecasting contract
function mintTokenRewards(address _contract, uint256 _amount) public onlyManager();
// Releases tokens (transfers crowdsale token from mintable to transferrable state)
function releaseTokens() public onlyManager() hasntStopped() whenCrowdsaleSuccessful();
// Stops crowdsale. Called by CrowdsaleController, the latter is called by owner.
// Crowdsale may be stopped any time before it finishes.
function stop() public onlyManager() hasntStopped();
// Validates parameters and starts crowdsale
function start(uint256 _startTimestamp, uint256 _endTimestamp, address _fundingAddress)
public onlyManager() hasntStarted() hasntStopped();
// Is crowdsale failed (completed, but minimal goal wasn't reached)
function isFailed() public constant returns (bool);
// Is crowdsale active (i.e. the token can be sold)
function isActive() public constant returns (bool);
// Is crowdsale completed successfully
function isSuccessful() public constant returns (bool);
}
// Basic crowdsale implementation both for regualt and 3rdparty Crowdsale contracts
contract BasicCrowdsale is ICrowdsaleProcessor {
event CROWDSALE_START(uint256 startTimestamp, uint256 endTimestamp, address fundingAddress);
// Where to transfer collected ETH
address public fundingAddress;
// Ctor.
function BasicCrowdsale(
address _owner,
address _manager
)
public
{
owner = _owner;
manager = _manager;
}
// called by CrowdsaleController to transfer reward part of ETH
// collected by successful crowdsale to Forecasting contract.
// This call is made upon closing successful crowdfunding process
// iff agreed ETH reward part is not zero
function mintETHRewards(
address _contract, // Forecasting contract
uint256 _amount // agreed part of totalCollected which is intended for rewards
)
public
onlyManager() // manager is CrowdsaleController instance
{
require(_contract.call.value(_amount)());
}
// cancels crowdsale
function stop() public onlyManager() hasntStopped() {
// we can stop only not started and not completed crowdsale
if (started) {
require(!isFailed());
require(!isSuccessful());
}
stopped = true;
}
// called by CrowdsaleController to setup start and end time of crowdfunding process
// as well as funding address (where to transfer ETH upon successful crowdsale)
function start(
uint256 _startTimestamp,
uint256 _endTimestamp,
address _fundingAddress
)
public
onlyManager() // manager is CrowdsaleController instance
hasntStarted() // not yet started
hasntStopped() // crowdsale wasn't cancelled
{
require(_fundingAddress != address(0));
// start time must not be earlier than current time
require(_startTimestamp >= block.timestamp);
// range must be sane
require(_endTimestamp > _startTimestamp);
duration = _endTimestamp - _startTimestamp;
// duration must fit constraints
require(duration >= MIN_CROWDSALE_TIME && duration <= MAX_CROWDSALE_TIME);
startTimestamp = _startTimestamp;
endTimestamp = _endTimestamp;
fundingAddress = _fundingAddress;
// now crowdsale is considered started, even if the current time is before startTimestamp
started = true;
CROWDSALE_START(_startTimestamp, _endTimestamp, _fundingAddress);
}
// must return true if crowdsale is over, but it failed
function isFailed()
public
constant
returns(bool)
{
return (
// it was started
started &&
// crowdsale period has finished
block.timestamp >= endTimestamp &&
// but collected ETH is below the required minimum
totalCollected < minimalGoal
);
}
// must return true if crowdsale is active (i.e. the token can be bought)
function isActive()
public
constant
returns(bool)
{
return (
// it was started
started &&
// hard cap wasn't reached yet
totalCollected < hardCap &&
// and current time is within the crowdfunding period
block.timestamp >= startTimestamp &&
block.timestamp < endTimestamp
);
}
// must return true if crowdsale completed successfully
function isSuccessful()
public
constant
returns(bool)
{
return (
// either the hard cap is collected
totalCollected >= hardCap ||
// ...or the crowdfunding period is over, but the minimum has been reached
(block.timestamp >= endTimestamp && totalCollected >= minimalGoal)
);
}
}
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;
}
}
contract SmartOToken is Ownable, IERC20 {
using SafeMath for uint256;
/* Public variables of the token */
string public constant name = "STO";
string public constant symbol = "STO";
uint public constant decimals = 18;
uint256 public constant initialSupply = 12000000000 * 1 ether;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
/* Events */
event Burn(address indexed burner, uint256 value);
event Mint(address indexed to, uint256 amount);
/* Constuctor: Initializes contract with initial supply tokens to the creator of the contract */
function SmartOToken() public {
balances[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
}
/* Implementation of ERC20Interface */
function totalSupply() public constant returns (uint256) { return totalSupply; }
function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; }
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _amount) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balances[_from] >= _amount); // Check if the sender has enough
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(_from, _to, _amount);
}
function transfer(address _to, uint256 _amount) public returns (bool) {
_transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require (_value <= allowed[_from][msg.sender]); // Check allowance
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _amount) public returns (bool) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256) {
return allowed[_owner][_spender];
}
}
// Custom crowdsale example
contract SmatrOCrowdsale is BasicCrowdsale {
// Crowdsale participants
mapping(address => uint256) participants;
// tokens per ETH fixed price
uint256 tokensPerEthPrice;
// Crowdsale token
SmartOToken crowdsaleToken;
// Ctor. In this example, minimalGoal, hardCap, and price are not changeable.
// In more complex cases, those parameters may be changed until start() is called.
function SmatrOCrowdsale(
uint256 _minimalGoal,
uint256 _hardCap,
uint256 _tokensPerEthPrice,
address _token
)
public
// simplest case where manager==owner. See onlyOwner() and onlyManager() modifiers
// before functions to figure out the cases in which those addresses should differ
BasicCrowdsale(msg.sender, msg.sender)
{
// just setup them once...
minimalGoal = _minimalGoal;
hardCap = _hardCap;
tokensPerEthPrice = _tokensPerEthPrice;
crowdsaleToken = SmartOToken(_token);
}
// Here goes ICrowdsaleProcessor implementation
// returns address of crowdsale token. The token must be ERC20-compliant
function getToken()
public
returns(address)
{
return address(crowdsaleToken);
}
// called by CrowdsaleController to transfer reward part of
// tokens sold by successful crowdsale to Forecasting contract.
// This call is made upon closing successful crowdfunding process.
function mintTokenRewards(
address _contract, // Forecasting contract
uint256 _amount // agreed part of totalSold which is intended for rewards
)
public
onlyManager() // manager is CrowdsaleController instance
{
// crowdsale token is mintable in this example, tokens are created here
crowdsaleToken.transfer(_contract, _amount);
}
// transfers crowdsale token from mintable to transferrable state
function releaseTokens()
public
onlyManager() // manager is CrowdsaleController instance
hasntStopped() // crowdsale wasn't cancelled
whenCrowdsaleSuccessful() // crowdsale was successful
{
// do nothing
}
// Here go crowdsale process itself and token manipulations
function setRate(uint256 _tokensPerEthPrice)
public
onlyOwner
{
tokensPerEthPrice = _tokensPerEthPrice;
}
// default function allows for ETH transfers to the contract
function () payable public {
require(msg.value >= 0.1 * 1 ether);
// and it sells the token
sellTokens(msg.sender, msg.value);
}
// sels the project's token to buyers
function sellTokens(address _recepient, uint256 _value)
internal
hasBeenStarted() // crowdsale started
hasntStopped() // wasn't cancelled by owner
whenCrowdsaleAlive() // in active state
{
uint256 newTotalCollected = totalCollected + _value;
if (hardCap < newTotalCollected) {
// don't sell anything above the hard cap
uint256 refund = newTotalCollected - hardCap;
uint256 diff = _value - refund;
// send the ETH part which exceeds the hard cap back to the buyer
_recepient.transfer(refund);
_value = diff;
}
// token amount as per price (fixed in this example)
uint256 tokensSold = _value * tokensPerEthPrice;
// create new tokens for this buyer
crowdsaleToken.transfer(_recepient, tokensSold);
// remember the buyer so he/she/it may refund its ETH if crowdsale failed
participants[_recepient] += _value;
// update total ETH collected
totalCollected += _value;
// update totel tokens sold
totalSold += tokensSold;
}
// project's owner withdraws ETH funds to the funding address upon successful crowdsale
function withdraw(
uint256 _amount // can be done partially
)
public
onlyOwner() // project's owner
hasntStopped() // crowdsale wasn't cancelled
whenCrowdsaleSuccessful() // crowdsale completed successfully
{
require(_amount <= this.balance);
fundingAddress.transfer(_amount);
}
// backers refund their ETH if the crowdsale was cancelled or has failed
function refund()
public
{
// either cancelled or failed
require(stopped || isFailed());
uint256 amount = participants[msg.sender];
// prevent from doing it twice
require(amount > 0);
participants[msg.sender] = 0;
msg.sender.transfer(amount);
}
}
|
backers refund their ETH if the crowdsale was cancelled or has failed either cancelled or failed prevent from doing it twice
|
function refund()
public
{
require(stopped || isFailed());
uint256 amount = participants[msg.sender];
require(amount > 0);
participants[msg.sender] = 0;
msg.sender.transfer(amount);
}
| 10,674,776
|
//Address: 0xe736091fc36f1ad476f5e4e03e4425940822d3ba
//Contract name: SingularDTVFund
//Balance: 3.630685972653289973 Ether
//Verification Date: 10/5/2016
//Transacion Count: 294
// CODE STARTS HERE
/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20
/// @title Abstract token contract - Functions to be implemented by token contracts.
/// @author Stefan George - <stefan.george@consensys.net>
contract Token {
// This is not an abstract function, because solc won't recognize generated getter functions for public variables as functions
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address owner) constant returns (uint256 balance);
function transfer(address to, uint256 value) returns (bool success);
function transferFrom(address from, address to, uint256 value) returns (bool success);
function approve(address spender, uint256 value) returns (bool success);
function allowance(address owner, address spender) constant returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract SingularDTVToken is Token {
function issueTokens(address _for, uint tokenCount) returns (bool);
}
contract SingularDTVCrowdfunding {
function twoYearsPassed() returns (bool);
function startDate() returns (uint);
function CROWDFUNDING_PERIOD() returns (uint);
function TOKEN_TARGET() returns (uint);
function valuePerShare() returns (uint);
function fundBalance() returns (uint);
function campaignEndedSuccessfully() returns (bool);
}
/// @title Fund contract - Implements revenue distribution.
/// @author Stefan George - <stefan.george@consensys.net>
contract SingularDTVFund {
/*
* External contracts
*/
SingularDTVToken public singularDTVToken;
SingularDTVCrowdfunding public singularDTVCrowdfunding;
/*
* Storage
*/
address public owner;
address constant public workshop = 0xc78310231aA53bD3D0FEA2F8c705C67730929D8f;
uint public totalRevenue;
// User's address => Revenue at time of withdraw
mapping (address => uint) public revenueAtTimeOfWithdraw;
// User's address => Revenue which can be withdrawn
mapping (address => uint) public owed;
/*
* Modifiers
*/
modifier noEther() {
if (msg.value > 0) {
throw;
}
_
}
modifier onlyOwner() {
// Only guard is allowed to do this action.
if (msg.sender != owner) {
throw;
}
_
}
modifier campaignEndedSuccessfully() {
if (!singularDTVCrowdfunding.campaignEndedSuccessfully()) {
throw;
}
_
}
/*
* Contract functions
*/
/// @dev Deposits revenue. Returns success.
function depositRevenue()
external
campaignEndedSuccessfully
returns (bool)
{
totalRevenue += msg.value;
return true;
}
/// @dev Withdraws revenue for user. Returns revenue.
/// @param forAddress user's address.
function calcRevenue(address forAddress) internal returns (uint) {
return singularDTVToken.balanceOf(forAddress) * (totalRevenue - revenueAtTimeOfWithdraw[forAddress]) / singularDTVToken.totalSupply();
}
/// @dev Withdraws revenue for user. Returns revenue.
function withdrawRevenue()
external
noEther
returns (uint)
{
uint value = calcRevenue(msg.sender) + owed[msg.sender];
revenueAtTimeOfWithdraw[msg.sender] = totalRevenue;
owed[msg.sender] = 0;
if (value > 0 && !msg.sender.send(value)) {
throw;
}
return value;
}
/// @dev Credits revenue to owed balance.
/// @param forAddress user's address.
function softWithdrawRevenueFor(address forAddress)
external
noEther
returns (uint)
{
uint value = calcRevenue(forAddress);
revenueAtTimeOfWithdraw[forAddress] = totalRevenue;
owed[forAddress] += value;
return value;
}
/// @dev Setup function sets external contracts' addresses.
/// @param singularDTVTokenAddress Token address.
function setup(address singularDTVCrowdfundingAddress, address singularDTVTokenAddress)
external
noEther
onlyOwner
returns (bool)
{
if (address(singularDTVCrowdfunding) == 0 && address(singularDTVToken) == 0) {
singularDTVCrowdfunding = SingularDTVCrowdfunding(singularDTVCrowdfundingAddress);
singularDTVToken = SingularDTVToken(singularDTVTokenAddress);
return true;
}
return false;
}
/// @dev Contract constructor function sets guard address.
function SingularDTVFund() noEther {
// Set owner address
owner = msg.sender;
}
}
|
Withdraws revenue for user. Returns revenue. forAddress user's address.
|
function calcRevenue(address forAddress) internal returns (uint) {
return singularDTVToken.balanceOf(forAddress) * (totalRevenue - revenueAtTimeOfWithdraw[forAddress]) / singularDTVToken.totalSupply();
}
| 970,894
|
./partial_match/1/0xd2947e1E2eA5c4cD14AaA2b7492549129b087DAA/sources/CosmicDriftNFT.sol
|
Set the Base Extension to be used for the revealed NFTs Callable only by Owner _newBaseExtension Metadata file extension
|
function setBaseExtension(string memory _newBaseExtension)
external
onlyOwner
{
baseExtension = _newBaseExtension;
emit BaseExtensionSet(_newBaseExtension);
}
| 16,149,375
|
./full_match/4/0x0d86ffF389aAaAd1738CBf1a917ce33dBad20a06/sources/contracts/contrato.sol
|
Não há uma forma eficiente de obter a lista toda... Então temos uma ineficiente.
|
function getWhitelist() public view onlyOwner returns (whiteListData[] memory) {
return whitelistedMints;
}
| 12,470,434
|
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../ProxyToken/ProxyToken.sol";
import "../UniversalProtocolToken/UniversalProtocolToken.sol";
import "./ProxyTokenAuthorizable.sol";
import "./ProxyTokenRequestsStorage.sol";
/**
* @title ProxyTokenRequestsV0
*/
contract ProxyTokenRequestsV0 is ProxyTokenAuthorizableV0 {
using SafeMath for uint256;
event FeeBeneficiaryUpdated(address beneficiary);
event MintFeeUpdated(uint256 fee);
event MintRequestCreated(uint256 indexed requestId);
event MintRequestFulfilled(uint256 indexed requestId);
event MintRequestCancelled(uint256 indexed requestId);
event MintRequestRejected(uint256 indexed requestId);
event BurnFeeUpdated(uint256 fee);
event BurnRequestCreated(uint256 indexed requestId);
event BurnRequestFulfilled(uint256 indexed requestId);
event BurnRequestCancelled(uint256 indexed requestId);
event BurnRequestRejected(uint256 indexed requestId);
ProxyToken public _proxyToken;
ProxyTokenRequestsStorageV0 public _storage;
UniversalProtocolToken public _universalProtocolToken;
address public _feeBeneficiary;
uint256 public _burnFee;
uint256 public _mintFee;
/**
* @notice Runs the function only after checking if a mint request is new
* @param requestId Identification for mint request
*/
modifier onlyNewMintRequest(uint256 requestId) {
require(
_storage.getMintRequestStatus(requestId) == ProxyTokenRequestsStorageV0.Status.NEW,
"The mint request status must be new"
);
_;
}
/**
* @notice Runs the function only after checking if a burn request is new
* @param requestId Identification for burn request
*/
modifier onlyNewBurnRequest(uint256 requestId) {
require(
_storage.getBurnRequestStatus(requestId) == ProxyTokenRequestsStorageV0.Status.NEW,
"The burn request status must be new"
);
_;
}
/**
* @dev Runs a function only after checking if a user is authorized to request
* or is the requester of the proxy tokens to be minted
* @param user Address for verifying authorization
* @param requestId Identification for mint request
*/
modifier onlySelfMintRequester(address user, uint256 requestId) {
require(
mintRequestAuthorization[user] && _storage.getMintRequestAddressMap(requestId, "requester") == user,
"Only authorized mint requester"
);
_;
}
/**
* @dev Runs a function only after checking if a user is authorized to request,
* or is the requester of the proxy tokens to be burned
* @param user Address for verifying authorization
* @param requestId Identification for burn request
*/
modifier onlySelfBurnRequester(address user, uint256 requestId) {
require(
burnRequestAuthorization[user] && _storage.getBurnRequestAddressMap(requestId, "requester") == user,
"Only authorized burn requester"
);
_;
}
/**
* @notice Constructor for ProxyTokenRequests
* @param owner owner of the contract
* @param universalProtocolTokenAddress address of the UPT contract
* @param feeBeneficiary address of the beneficiary of the mint and burn fees
* @param burnFee burn fee (in UPT)
* @param mintFee mint fee (in UPT)
* @param proxyToken address of the Proxy Token
* @param proxyTokenRequestsStorage address for ProxyTokenRequestsStorage
*/
constructor(
address owner,
address universalProtocolTokenAddress,
address feeBeneficiary,
uint256 burnFee,
uint256 mintFee,
address proxyToken,
address proxyTokenRequestsStorage)
public ProxyTokenAuthorizableV0(owner) {
require(feeBeneficiary != address(0x0), "UPT beneficiary cannot be the zero address");
_burnFee = burnFee;
_feeBeneficiary = feeBeneficiary;
_mintFee = mintFee;
_proxyToken = ProxyToken(proxyToken);
_storage = ProxyTokenRequestsStorageV0(proxyTokenRequestsStorage);
_universalProtocolToken = UniversalProtocolToken(universalProtocolTokenAddress);
}
/**
* @notice Creates a mint request
* @notice This function requires the requester to call the `approve`
* function for `mintFee` of UniversalProtocolToken (UPT) tokens before calling this function.
* @param beneficiary address of the beneficiary of the tokens to be minted
* @param amount amount of proxy tokens to mint
*/
function createMintRequest(
address beneficiary,
uint256 amount,
string memory data)
public
onlyAuthorizedMintRequester(msg.sender)
{
require(amount > 0, "Proxy amount cannot be zero");
if (_mintFee > 0) {
require(_universalProtocolToken.transferFrom(msg.sender, _feeBeneficiary, _mintFee), "Failed to charge UPT mint fee");
}
uint256 requestId = _storage.createMintRequest();
_storage.setMintRequestAddressMap(requestId, "beneficiary", beneficiary);
_storage.setMintRequestAddressMap(requestId, "fulfiller", address(0x0));
_storage.setMintRequestAddressMap(requestId, "rejecter", address(0x0));
_storage.setMintRequestAddressMap(requestId, "requester", msg.sender);
_storage.setMintRequestStringMap(requestId, "requestData", data);
_storage.setMintRequestUintMap(requestId, "amount", amount);
emit MintRequestCreated(requestId);
}
/**
* @notice Fulfills a mint request, minting `amount` tokens
* @param requestId requestId of mint request to fulfill
* @param data external data logged as part of the mint request
*/
function fulfillMintRequest(
uint256 requestId,
string memory data)
public
onlyNewMintRequest(requestId)
onlyAuthorizedMintFulfiller(msg.sender)
{
_storage.setMintRequestStatus(requestId, ProxyTokenRequestsStorageV0.Status.FULFILLED);
_storage.setMintRequestAddressMap(requestId, "fulfiller", msg.sender);
_storage.setMintRequestStringMap(requestId, "fulfillData", data);
address beneficiary = _storage.getMintRequestAddressMap(requestId, "beneficiary");
uint256 amount = _storage.getMintRequestUintMap(requestId, "amount");
require(_proxyToken.mint(beneficiary, amount), "fulfillMintRequest failed");
emit MintRequestFulfilled(requestId);
}
/**
* @notice The proxy token owner or an authorized requester cancels a mint request
* @param requestId requestId of mint request to cancel
* @param data external data logged as part of the mint request cancellation
*/
function cancelMintRequest(
uint256 requestId,
string memory data)
public
onlyNewMintRequest(requestId)
onlySelfMintRequester(msg.sender, requestId)
{
_storage.setMintRequestStatus(requestId, ProxyTokenRequestsStorageV0.Status.CANCELLED);
_storage.setMintRequestStringMap(requestId, "cancelData", data);
emit MintRequestCancelled(requestId);
}
/**
* @notice An authorized fulfiller rejects a mint request
* @param requestId requestId of mint request to cancel
* @param data external data logged as part of the mint request cancellation
*/
function rejectMintRequest(
uint256 requestId,
string memory data)
public
onlyNewMintRequest(requestId)
onlyAuthorizedMintFulfiller(msg.sender)
{
_storage.setMintRequestStatus(requestId, ProxyTokenRequestsStorageV0.Status.REJECTED);
_storage.setMintRequestAddressMap(requestId, "rejecter", msg.sender);
_storage.setMintRequestStringMap(requestId, "rejectData", data);
emit MintRequestRejected(requestId);
}
/**
* @notice Creates a burn request, transfering `amount` tokens to this contract as escrow.
* @notice This function requires the requester to call the `approveBurn` function
* for `amount` tokens before calling this function and `approve` for `burnFee` of
* UniversalProtocolToken (UPT) tokens.
* @param beneficiary address of the beneficiary of the tokens to be burnt
* @param amount amount of proxy tokens to burn
*/
function createBurnRequest(
address beneficiary,
uint256 amount,
string memory data)
public
onlyAuthorizedBurnRequester(msg.sender)
{
require(amount > 0, "Proxy amount cannot be zero");
if (_burnFee > 0) {
require(_universalProtocolToken.transferFrom(msg.sender, _feeBeneficiary, _burnFee), "Failed to charge UPT burn fee");
}
uint256 requestId = _storage.createBurnRequest();
_storage.setBurnRequestAddressMap(requestId, "beneficiary", beneficiary);
_storage.setBurnRequestAddressMap(requestId, "fulfiller", address(0x0));
_storage.setBurnRequestAddressMap(requestId, "rejecter", address(0x0));
_storage.setBurnRequestAddressMap(requestId, "requester", msg.sender);
_storage.setBurnRequestStringMap(requestId, "requestData", data);
_storage.setBurnRequestUintMap(requestId, "amount", amount);
emit BurnRequestCreated(requestId);
}
/**
* @notice Fulfills a burn request, burning `amount` tokens
* @param requestId requestId of burn request to fulfill
* @param data external data logged as part of the burn request
*/
function fulfillBurnRequest(
uint256 requestId,
string memory data)
public
onlyNewBurnRequest(requestId)
onlyAuthorizedBurnFulfiller(msg.sender)
{
_storage.setBurnRequestAddressMap(requestId, "fulfiller", msg.sender);
_storage.setBurnRequestStatus(requestId, ProxyTokenRequestsStorageV0.Status.FULFILLED);
_storage.setBurnRequestStringMap(requestId, "fulfillData", data);
address beneficiary = _storage.getBurnRequestAddressMap(requestId, "beneficiary");
uint256 amount = _storage.getBurnRequestUintMap(requestId, "amount");
require(_proxyToken.burnFrom(beneficiary, amount), "fulfillBurnRequest failed");
emit BurnRequestFulfilled(requestId);
}
/**
* @notice The proxy token owner or an authorized requester cancels a burn request
* @param requestId requestId of burn request to cancel
* @param data external data logged as part of the burn request cancellation
*/
function cancelBurnRequest(
uint256 requestId,
string memory data)
public
onlyNewBurnRequest(requestId)
onlySelfBurnRequester(msg.sender, requestId)
{
_storage.setBurnRequestStatus(requestId, ProxyTokenRequestsStorageV0.Status.CANCELLED);
_storage.setBurnRequestStringMap(requestId, "cancelData", data);
emit BurnRequestCancelled(requestId);
}
/**
* @notice An authorized fulfiller rejects a burn request
* @param requestId requestId of burn request to cancel
* @param data external data logged as part of the burn request cancellation
*/
function rejectBurnRequest(
uint256 requestId,
string memory data)
public
onlyNewBurnRequest(requestId)
onlyAuthorizedBurnFulfiller(msg.sender)
{
_storage.setBurnRequestAddressMap(requestId, "rejecter", msg.sender);
_storage.setBurnRequestStatus(requestId, ProxyTokenRequestsStorageV0.Status.REJECTED);
_storage.setBurnRequestStringMap(requestId, "rejectData", data);
emit BurnRequestRejected(requestId);
}
/**
* @notice Get the burn fee
*/
function getBurnFee() public view returns(uint256) {
return _burnFee;
}
/**
* @notice Get the UPT fee beneficiary
*/
function getFeeBeneficiary() public view returns(address) {
return _feeBeneficiary;
}
/**
* @notice Get the mint fee
*/
function getMintFee() public view returns(uint256) {
return _mintFee;
}
/**
* @notice The owner can set a new burn fee
* @param burnFee the burn fee in UPT
*/
function setBurnFee(uint256 burnFee) public onlyOwner {
_burnFee = burnFee;
emit BurnFeeUpdated(_burnFee);
}
/**
* @notice The owner can set a UPT fee beneficiary
* @param feeBeneficiary the UPT fee beneficiary
*/
function setFeeBeneficiary(address feeBeneficiary) public onlyOwner {
_feeBeneficiary = feeBeneficiary;
emit FeeBeneficiaryUpdated(feeBeneficiary);
}
/**
* @notice The owner can set a new mint fee
* @param mintFee the mint fee in UPT
*/
function setMintFee(uint256 mintFee) public onlyOwner {
_mintFee = mintFee;
emit MintFeeUpdated(_mintFee);
}
}
|
Fulfills a mint request, minting `amount` tokens requestId requestId of mint request to fulfill data external data logged as part of the mint request/
|
function fulfillMintRequest(
uint256 requestId,
string memory data)
public
onlyNewMintRequest(requestId)
onlyAuthorizedMintFulfiller(msg.sender)
{
_storage.setMintRequestStatus(requestId, ProxyTokenRequestsStorageV0.Status.FULFILLED);
_storage.setMintRequestAddressMap(requestId, "fulfiller", msg.sender);
_storage.setMintRequestStringMap(requestId, "fulfillData", data);
address beneficiary = _storage.getMintRequestAddressMap(requestId, "beneficiary");
uint256 amount = _storage.getMintRequestUintMap(requestId, "amount");
require(_proxyToken.mint(beneficiary, amount), "fulfillMintRequest failed");
emit MintRequestFulfilled(requestId);
}
| 7,277,707
|
./full_match/5/0x4E95da32B1D75CD399b79cd85fE77f0e2935CC46/sources/contracts/CrowdFunding.sol
|
fucntionscheck all okincrement number of campaigns
|
function createCampaign(address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image) public returns (uint256)
{
Campaign storage campaign = campaigns[numberOfCampaigns];
require(campaign.deadline < block.timestamp, "Deadline is a Date in the Future");
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
numberOfCampaigns++;
}
| 11,621,227
|
./full_match/8453/0x6AE3fFA7bb6f95fAcA1F1A7f85880C87141c0236/sources/contracts/staking/sys/MixinFinalizer.sol
|
@inheritdoc IStaking Make sure the previous epoch has been fully finalized. mint epoch inflation, jump first epoch as all registered pool accounts will become active from following epoch mint happens before time has passed check, therefore tokens will be allocated even before expiry if method is called but will not be minted again until epoch time has passed. This could happen when epoch length is changed only. If there are no pools to finalize then the epoch is finalized.
|
function endEpoch() external override returns (uint256 numPoolsToFinalize) {
uint256 currentEpoch_ = currentEpoch;
uint256 prevEpoch = currentEpoch_ - 1;
uint256 numPoolsToFinalizeFromPrevEpoch = aggregatedStatsByEpoch[prevEpoch].numPoolsToFinalize;
require(numPoolsToFinalizeFromPrevEpoch == 0, "STAKING_MISSING_POOLS_TO_BE_FINALIZED_ERROR");
if (currentEpoch_ > uint256(1)) {
try IInflation(_getInflation()).mintInflation() returns (uint256 mintedInflation) {
emit GrgMintEvent(mintedInflation);
emit CatchStringEvent(revertReason);
emit ReturnDataEvent(returnData);
}
}
IStructs.AggregatedStats memory aggregatedStats = aggregatedStatsByEpoch[currentEpoch_];
currentEpoch_,
aggregatedStats.numPoolsToFinalize,
aggregatedStats.rewardsAvailable,
aggregatedStats.totalFeesCollected,
aggregatedStats.totalWeightedStake
);
if (aggregatedStats.numPoolsToFinalize == 0) {
emit EpochFinalized(currentEpoch_, 0, aggregatedStats.rewardsAvailable);
}
return aggregatedStats.numPoolsToFinalize;
}
| 11,544,541
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import './interfaces/IERC1155BurnMintable.sol';
import './interfaces/IWOWSCryptofolio.sol';
import './interfaces/IWOWSERC1155.sol';
contract WOWSCryptofolio is IWOWSCryptofolio {
// Our NFT token parent
IWOWSERC1155 private _deployer;
// The owner of the NFT token parent
address private _owner;
// Mapping of cryptofolio items owned by this
mapping(address => uint256[]) private _cryptofolios;
// List of all known tradefloors
address[] public _tradefloors;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Triggered if sft receives new tokens from operator
*/
event CryptoFolioAdded(
address indexed sft,
address indexed operator,
uint256[] tokenIds,
uint256[] amounts
);
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {IWOWSCryptofolio-initialize}.
*/
function initialize() external override {
require(address(_deployer) == address(0), 'CF: Already initialized');
_deployer = IWOWSERC1155(msg.sender);
}
//////////////////////////////////////////////////////////////////////////////
// Implementation of {IWOWSCryptofolio}
//////////////////////////////////////////////////////////////////////////////
/**
* @dev See {IWOWSCryptofolio-getCryptofolio}.
*/
function getCryptofolio(address tradefloor)
external
view
override
returns (uint256[] memory tokenIds, uint256 idsLength)
{
uint256[] storage opIds = _cryptofolios[tradefloor];
uint256[] memory result = new uint256[](opIds.length);
uint256 newLength = 0;
if (opIds.length > 0) {
address[] memory accounts = new address[](opIds.length);
for (uint256 i = 0; i < opIds.length; ++i) accounts[i] = address(this);
uint256[] memory balances =
IERC1155(tradefloor).balanceOfBatch(accounts, opIds);
for (uint256 i = 0; i < opIds.length; ++i)
if (balances[i] > 0) result[newLength++] = opIds[i];
}
return (result, newLength);
}
/**
* @dev See {IWOWSCryptofolio-setOwner}.
*/
function setOwner(address newOwner) external override {
require(msg.sender == address(_deployer), 'CF: Only deployer');
for (uint256 i = 0; i < _tradefloors.length; ++i) {
if (_owner != address(0))
IERC1155(_tradefloors[i]).setApprovalForAll(_owner, false);
if (newOwner != address(0))
IERC1155(_tradefloors[i]).setApprovalForAll(newOwner, true);
}
_owner = newOwner;
}
/**
* @dev See {IWOWSCryptofolio-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool allow) external override {
require(msg.sender == _owner, 'CF: Only owner');
for (uint256 i = 0; i < _tradefloors.length; ++i) {
IERC1155(_tradefloors[i]).setApprovalForAll(operator, allow);
}
}
/**
* @dev See {IWOWSCryptofolio-burn}.
*/
function burn() external override {
require(msg.sender == address(_deployer), 'CF: Only deployer');
for (uint256 i = 0; i < _tradefloors.length; ++i) {
IERC1155BurnMintable tradefloor = IERC1155BurnMintable(_tradefloors[i]);
uint256[] storage opIds = _cryptofolios[address(tradefloor)];
if (opIds.length > 0) {
address[] memory accounts = new address[](opIds.length);
for (uint256 j = 0; j < opIds.length; ++j) accounts[j] = address(this);
uint256[] memory balances = tradefloor.balanceOfBatch(accounts, opIds);
tradefloor.burnBatch(address(this), opIds, balances);
}
delete _cryptofolios[address(tradefloor)];
}
delete _tradefloors;
}
//////////////////////////////////////////////////////////////////////////////
// Hooks
//////////////////////////////////////////////////////////////////////////////
function onERC1155Received(
address,
address,
uint256 tokenId,
uint256 amount,
bytes memory
) external returns (bytes4) {
uint256[] memory tokenIds = new uint256[](1);
tokenIds[0] = tokenId;
uint256[] memory amounts = new uint256[](1);
amounts[0] = amount;
_onTokensReceived(tokenIds, amounts);
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory tokenIds,
uint256[] memory amounts,
bytes memory
) external returns (bytes4) {
_onTokensReceived(tokenIds, amounts);
return this.onERC1155BatchReceived.selector;
}
//////////////////////////////////////////////////////////////////////////////
// Internal functionality
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Update our collection of tradeable cryptofolio items
*
* This function is only allowed to be called from one of our pseudo
* TokenReceiver contracts.
*/
function _onTokensReceived(
uint256[] memory tokenIds,
uint256[] memory amounts
) internal {
address tradefloor = msg.sender;
require(_deployer.isTradeFloor(tradefloor), 'CF: Only tradefloor');
require(tokenIds.length == amounts.length, 'CF: Input lengths differ');
uint256[] storage currentIds = _cryptofolios[tradefloor];
if (currentIds.length == 0) {
IERC1155(tradefloor).setApprovalForAll(_owner, true);
_tradefloors.push(tradefloor);
}
for (uint256 iIds = 0; iIds < tokenIds.length; ++iIds) {
if (amounts[iIds] > 0) {
uint256 tokenId = tokenIds[iIds];
// Search tokenId
uint256 i = 0;
for (; i < currentIds.length && currentIds[i] != tokenId; ++i) i;
// If token was not found, insert it
if (i == currentIds.length) currentIds.push(tokenId);
}
}
emit CryptoFolioAdded(address(this), tradefloor, tokenIds, amounts);
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '@openzeppelin/contracts/token/ERC1155/IERC1155.sol';
interface IERC1155BurnMintable is IERC1155 {
/**
* @dev Mint amount new tokens at ID `tokenId` (MINTER_ROLE required)
*/
function mint(
address to,
uint256 tokenId,
uint256 amount,
bytes memory data
) external;
/**
* @dev Mint new token amounts at IDs `tokenIds` (MINTER_ROLE required)
*/
function mintBatch(
address to,
uint256[] memory tokenIds,
uint256[] memory amounts,
bytes memory data
) external;
/**
* @dev Burn value amount of tokens with ID `tokenId`.
*
* Caller must be approvedForAll.
*/
function burn(
address account,
uint256 tokenId,
uint256 value
) external;
/**
* @dev Burn `values` amounts of tokens with IDs `tokenIds`.
*
* Caller must be approvedForAll.
*/
function burnBatch(
address account,
uint256[] memory tokenIds,
uint256[] memory values
) external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio interface
*
* TODO: Describe cryptofolios
*/
interface IWOWSCryptofolio {
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Initialize the deployed contract after creation
*
* This is a one time call which sets _deployer to msg.sender.
* Subsequent calls reverts.
*/
function initialize() external;
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Return array of cryptofolio token IDs
*
* The token IDs belong to the contract tradefloor.
*
* @param tradefloor The tradefloor items belong to
*
* @return tokenIds The token IDs in scope of operator
* @return idsLength The number of valid token IDs
*/
function getCryptofolio(address tradefloor)
external
view
returns (uint256[] memory tokenIds, uint256 idsLength);
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set the owner of the underlying NFT
*
* This function is called if ownership of the parent NFT has changed.
*
* The new owner gets allowance to transfer cryptofolio items. The new owner
* is allowed to transfer / burn cryptofolio items. Make sure that allowance
* is removed from previous owner.
*
* @param owner The new owner of the underlying NFT
*/
function setOwner(address owner) external;
/**
* @dev Allow owner (of parent NFT) to approve external operators to transfer
* our cryptofolio items
*
* The NFT owner is allowed to approve operator to handle cryptofolios.
*
* @param operator The operator
* @param allow True to approve for all NFTs, false to revoke approval
*/
function setApprovalForAll(address operator, bool allow) external;
/**
* @dev Burn all cryptofolio items
*
* In case an underlying NFT is burned, we also burn the cryptofolio.
*/
function burn() external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio interface
*
* TODO: Describe cryptofolios
*/
interface IWOWSERC1155 {
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Check if the specified address is a known tradefloor
*
* @param account The address to check
*
* @return True if the address is a known tradefloor, false otherwise
*/
function isTradeFloor(address account) external view returns (bool);
/**
* @dev Get the token ID of a given address
*
* A cross check is required because token ID 0 is valid.
*
* @param tokenAddress The address to convert to a token ID
*
* @return The token ID on success, or uint256(-1) if `tokenAddress` does not
* belong to a token ID
*/
function addressToTokenId(address tokenAddress)
external
view
returns (uint256);
/**
* @dev Get the address for a given token ID
*
* @param tokenId The token ID to convert
*
* @return The address, or address(0) in case the token ID does not belong
* to an NFT
*/
function tokenIdToAddress(uint256 tokenId) external view returns (address);
/**
* @dev Get the next mintable token ID for the specified card
*
* @param level The level of the card
* @param cardId The token ID of the card
*
* @return bool True if a free token ID was found, false otherwise
* @return uint256 The first free token ID if one was found, or invalid otherwise
*/
function getNextMintableTokenId(uint8 level, uint8 cardId)
external
view
returns (bool, uint256);
/**
* @dev Return the next mintable custom token ID
*/
function getNextMintableCustomToken() external view returns (uint256);
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set the URI for either predefined cards or custom cards
*
* For changing the default URI for predefined cards, token ID 0 must be
* passed. Custom token ID's (> 32-bit range) get their own URI per token ID.
*
* @param tokenId The token ID whose URI is being set. Use `tokenId` == 0 to
* set the default URI. `tokenId` >= 0xFFFFFFFF is for custom URIs.
* @param _uri The URI, also allowing for the ERC-1155 {id} mechanism.
*/
function setURI(uint256 tokenId, string memory _uri) external;
/**
* @dev Set the URI which is returned for custom cards without specific URI
*
* @param _uri The URI, also allowing for the ERC-1155 {id} mechanism.
*/
function setCustomDefaultURI(string memory _uri) external;
/**
* @dev Each custom card has its own level. Level will be used when
* calculating rewards and raiding power.
*
* @param tokenId The ID of the token whose level is being set
* @param cardLevel The new level of the specified token
*/
function setCustomCardLevel(uint256 tokenId, uint8 cardLevel) external;
}
|
See {IWOWSCryptofolio-burn}./
|
function burn() external override {
require(msg.sender == address(_deployer), 'CF: Only deployer');
for (uint256 i = 0; i < _tradefloors.length; ++i) {
IERC1155BurnMintable tradefloor = IERC1155BurnMintable(_tradefloors[i]);
uint256[] storage opIds = _cryptofolios[address(tradefloor)];
if (opIds.length > 0) {
address[] memory accounts = new address[](opIds.length);
for (uint256 j = 0; j < opIds.length; ++j) accounts[j] = address(this);
uint256[] memory balances = tradefloor.balanceOfBatch(accounts, opIds);
tradefloor.burnBatch(address(this), opIds, balances);
}
delete _cryptofolios[address(tradefloor)];
}
delete _tradefloors;
}
| 14,767,993
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @dev Implementation of Vegion Token.
* @author Vegion Team
*/
contract VegionToken is Context, IERC20, IERC20Metadata, Ownable {
mapping(address => uint256) private _balances;
mapping(address => uint256) private _freezes;
mapping(address => bool) private _addressExists;
mapping(uint256 => address) private _addresses;
uint256 private _addressCount = 0;
address private _addressDev;
address private _addressAd;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
uint256 private _totalBurn;
uint256 private _burnStop;
string private _name = "VegionToken";
string private _symbol = "VT";
mapping(address => bool) private _addressNoAirdrop;
mapping(address => uint256) private _addressAirdrop;
uint256 private _totalAirdrop = 0;
uint256 private _totalVt = 0;
uint256 private _adBatchEnd = 0;
uint256 private _adBatchLast = 0;
uint256 private _adBatchTotal = 0;
uint256 private _adBatchVtTotal = 0;
mapping(address => bool) private _admins;
/**
* @dev constructor
*/
constructor(address addressDev, address addressAd) {
require(addressDev != address(0), "constructor: dev address error");
require(addressAd != address(0), "constructor: airdrop address error");
require(
addressDev != addressAd,
"constructor: dev and airdrop not same"
);
_totalSupply = 100_000_000 * 10**decimals();
_totalBurn = 0;
_burnStop = 2_100_000 * 10**decimals();
// owner
_addressExists[_msgSender()] = true;
_addresses[_addressCount++] = _msgSender();
// dev
if (!_addressExists[addressDev]) {
_addressExists[addressDev] = true;
_addresses[_addressCount++] = addressDev;
}
_addressDev = addressDev;
// airdrop
if (!_addressExists[addressAd]) {
_addressExists[addressAd] = true;
_addresses[_addressCount++] = addressAd;
}
_addressAd = addressAd;
_admins[_msgSender()] = true;
}
/**
* @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.
*/
function decimals() public view virtual override returns (uint8) {
return 8;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev totalBurn.
*/
function totalBurn() public view virtual returns (uint256) {
return _totalBurn;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transferBurn(_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}.
*/
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(
currentAllowance >= amount,
"transferFrom: transfer amount exceeds allowance"
);
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
_transfer(sender, recipient, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender] + addedValue
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(
currentAllowance >= subtractedValue,
"decreaseAllowance: decreased allowance below zero"
);
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev burn
*/
function burn(uint256 amount) public virtual returns (bool) {
_burn(_msgSender(), amount);
return true;
}
/**
* @dev get address count
*/
function addressCount() public view onlyAdmin returns (uint256) {
return _addressCount;
}
/**
* @dev check if address exist
*/
function isAddressExist(address target)
public
view
onlyAdmin
returns (bool)
{
return _addressExists[target];
}
/**
* @dev total airdrop vt
*/
function totalAirdrop() public view onlyAdmin returns (uint256) {
return _totalAirdrop;
}
/**
* @dev total address vt
*/
function totalVt() public view onlyAdmin returns (uint256) {
return _totalVt;
}
/**
* airdrop
*/
function airdrop(address recipient, uint256 amount)
public
onlyAdmin
returns (bool)
{
require(
recipient != address(0),
"airdrop: airdrop to the zero address"
);
// if recipient not exist
if (!_addressExists[recipient]) {
_addressExists[recipient] = true;
_addresses[_addressCount++] = recipient;
}
_balances[recipient] += amount;
_totalVt += amount;
emit Transfer(address(0), recipient, amount);
return true;
}
/**
* airdrops
*/
function airdrops(address[] memory recipients, uint256[] memory amounts)
public
onlyAdmin
returns (bool)
{
require(
recipients.length == amounts.length,
"airdrops: length not equal"
);
for (uint256 i = 0; i < recipients.length; i++) {
if (recipients[i] != address(0)) {
airdrop(recipients[i], amounts[i]);
}
}
return true;
}
/**
* airdropAll
*/
function airdropAll() public onlyAdmin returns (bool) {
_airdrop(0, _addressCount, _totalAirdrop, _totalVt);
_totalAirdrop = 0;
return true;
}
/**
* airdrop batch
*/
function airdropBatch(uint256 count) public onlyAdmin returns (bool) {
if (_adBatchTotal <= 0) {
require(
_totalAirdrop > 0,
"airdropBatch: airdrop total should bigger than zero"
);
_adBatchTotal = _totalAirdrop;
_adBatchVtTotal = _totalVt;
_adBatchEnd = _addressCount;
_adBatchLast = 0;
_totalAirdrop = 0;
}
uint256 end = _adBatchLast + count >= _adBatchEnd
? _adBatchEnd
: _adBatchLast + count;
_airdrop(_adBatchLast, end, _adBatchTotal, _adBatchVtTotal);
if (end >= _adBatchEnd) {
_adBatchTotal = 0;
_adBatchVtTotal = 0;
_adBatchEnd = 0;
_adBatchLast = 0;
} else {
_adBatchLast = end;
}
return true;
}
/**
* address can get airdrop or not
*/
function isAddressNoAirdrop(address target)
public
view
onlyAdmin
returns (bool)
{
return _addressNoAirdrop[target];
}
/**
* address airdrop
*/
function addressAirdrop() public view returns (uint256) {
return _addressAirdrop[_msgSender()];
}
/**
* receive airdrop
*/
function receiveAirdrop() public returns (bool) {
require(
_addressAirdrop[_msgSender()] > 0,
"receiveAirdrop: no wait receive airdrop vt"
);
uint256 waitReceive = _addressAirdrop[_msgSender()];
require(
_balances[_addressAd] >= waitReceive,
"receiveAirdrop: not enough airdrop vt"
);
_balances[_msgSender()] += waitReceive;
_addressAirdrop[_msgSender()] = 0;
_balances[_addressAd] -= waitReceive;
_totalVt += waitReceive;
emit Transfer(_addressAd, _msgSender(), waitReceive);
return true;
}
/**
* setNoAirdrop for target address
*/
function setNoAirdrop(address target, bool noAirdrop)
public
onlyAdmin
returns (bool)
{
require(
_addressNoAirdrop[target] != noAirdrop,
"setNoAirdrop: same setting."
);
_addressNoAirdrop[target] = noAirdrop;
return true;
}
/**
* freeze
*/
function freeze(address target, uint256 amount)
public
onlyAdmin
returns (bool)
{
require(_balances[target] >= amount, "freeze: freeze amount error");
_balances[target] -= amount;
_freezes[target] += amount;
_totalVt -= amount;
emit Freeze(target, amount);
return true;
}
/**
* unfreeze
*/
function unfreeze(address target, uint256 amount)
public
onlyAdmin
returns (bool)
{
require(_freezes[target] >= amount, "unfreeze: unfreeze amount error");
_balances[target] += amount;
_freezes[target] -= amount;
_totalVt += amount;
emit Unfreeze(target, amount);
return true;
}
/**
* @dev See {IERC20-freezeOf}.
*/
function freezeOf(address account) public view returns (uint256) {
return _freezes[account];
}
/**
* @dev get dev
*/
function getAddressDev() public view onlyAdmin returns (address) {
return _addressDev;
}
/**
* @dev set new dev
*/
function transferDev(address newDev) public onlyAdmin returns (bool) {
require(newDev != address(0), "transferDev: new address zero");
if (!_addressExists[newDev]) {
_addressExists[newDev] = true;
_addresses[_addressCount++] = newDev;
}
uint256 amount = _balances[_addressDev];
address oldDev = _addressDev;
_balances[newDev] = amount;
_balances[oldDev] = 0;
_addressDev = newDev;
emit Transfer(oldDev, newDev, amount);
return true;
}
/**
* @dev get ad
*/
function getAddressAd() public view onlyAdmin returns (address) {
return _addressAd;
}
/**
* @dev set new ad
*/
function transferAd(address newAd) public onlyAdmin returns (bool) {
require(newAd != address(0), "transferAd: new address zero");
if (!_addressExists[newAd]) {
_addressExists[newAd] = true;
_addresses[_addressCount++] = newAd;
}
uint256 amount = _balances[_addressAd];
address oldAd = _addressAd;
_balances[newAd] = amount;
_balances[oldAd] = 0;
_addressAd = newAd;
emit Transfer(oldAd, newAd, amount);
return true;
}
/**
* @dev admin modifier
*/
modifier onlyAdmin() {
require(_admins[_msgSender()], "onlyAdmin: caller is not the admin");
_;
}
function addAdmin(address admin) public onlyOwner {
require(admin != address(0), "addAdmin: admin is not zero");
require(!_admins[admin], "addAdmin: admin is already admin");
_admins[admin] = true;
}
function removeAdmin(address admin) public onlyOwner {
require(admin != address(0), "removeAdmin: admin is not zero");
require(_admins[admin], "removeAdmin: admin is not admin");
_admins[admin] = false;
}
function isAdmin(address admin) public view onlyOwner returns (bool) {
return _admins[admin];
}
function _airdrop(
uint256 start,
uint256 end,
uint256 adTotal,
uint256 vtTotal
) internal {
require(end > start, "_airdrop: end should bigger than start");
require(adTotal > 0, "_airdrop: airdrop total should bigger than zero");
require(vtTotal > 0, "_airdrop: vt total should bigger than zero");
for (uint256 i = start; i < end; i++) {
address addr = _addresses[i];
uint256 balance = _balances[addr];
if (balance > 0 && addr != _addressAd) {
uint256 airdropVt = (adTotal * balance) / vtTotal;
if (_addressNoAirdrop[addr]) {
_totalSupply -= airdropVt;
_totalBurn += airdropVt;
emit Transfer(_addressAd, address(0), airdropVt);
} else {
_addressAirdrop[addr] += airdropVt;
}
}
}
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(
sender != address(0),
"_transfer: transfer from the zero address"
);
require(
recipient != address(0),
"_transfer: transfer to the zero address"
);
uint256 senderBalance = _balances[sender];
require(
senderBalance >= amount,
"_transfer: transfer amount exceeds balance"
);
unchecked {
_balances[sender] = senderBalance - amount;
}
// if recipient not exist
if (!_addressExists[recipient]) {
_addressExists[recipient] = true;
_addresses[_addressCount++] = recipient;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*/
function _transferBurn(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(
sender != address(0),
"_transferBurn: transfer from the zero address"
);
require(
recipient != address(0),
"_transferBurn: transfer to the zero address"
);
uint256 senderBalance = _balances[sender];
require(
senderBalance >= amount,
"_transferBurn: transfer amount exceeds balance"
);
unchecked {
_balances[sender] = senderBalance - amount;
}
// if recipient not exist
if (!_addressExists[recipient]) {
_addressExists[recipient] = true;
_addresses[_addressCount++] = recipient;
}
if (_totalBurn < _burnStop) {
// 50% decrease
uint256 toRecipient = amount / 2;
_balances[recipient] += toRecipient;
emit Transfer(sender, recipient, toRecipient);
// 30% airdrop
uint256 toAirdrop = (amount * 3) / 10;
_balances[_addressAd] += toAirdrop;
_totalAirdrop += toAirdrop;
_totalVt -= toAirdrop;
emit Transfer(sender, _addressAd, toAirdrop);
// 5% developer
uint256 toDev = (amount * 5) / 100;
_balances[_addressDev] += toDev;
emit Transfer(sender, _addressDev, toDev);
// 15% burn
uint256 toBurn = (amount * 15) / 100;
_totalSupply -= toBurn;
_totalBurn += toBurn;
_totalVt -= toBurn;
emit Transfer(sender, address(0), toBurn);
} else {
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "VegionToken: mint to the zero address");
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "_burn: burn from the zero address");
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "_burn: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
_totalBurn += amount;
_totalVt -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "_approve: approve from the zero address");
require(spender != address(0), "_approve: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* transfer balance to owner
*/
function withdrawEther(uint256 amount) public onlyOwner {
require(
address(this).balance >= amount,
"withdrawEther: not enough ether balance."
);
payable(owner()).transfer(amount);
}
/**
* can accept ether
*/
receive() external payable {}
/**
* @dev Emitted when `value` tokens are freezed.
*/
event Freeze(address indexed target, uint256 value);
/**
* @dev Emitted when `value` tokens are unfreezed.
*/
event Unfreeze(address indexed target, uint256 value);
}
|
See {IERC20-transferFrom}./
|
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(
currentAllowance >= amount,
"transferFrom: transfer amount exceeds allowance"
);
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
_transfer(sender, recipient, amount);
return true;
}
| 489,718
|
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { IController } from "../../interfaces/IController.sol";
import { ISetValuer } from "../../interfaces/ISetValuer.sol";
import { INAVIssuanceHook } from "../../interfaces/INAVIssuanceHook.sol";
import { Invoke } from "../lib/Invoke.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { IWETH } from "../../interfaces/external/IWETH.sol";
import { ModuleBase } from "../lib/ModuleBase.sol";
import { Position } from "../lib/Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
import { ResourceIdentifier } from "../lib/ResourceIdentifier.sol";
/**
* @title CustomOracleNavIssuanceModule
* @author Set Protocol
*
* Module that enables issuance and redemption with any valid ERC20 token or ETH if allowed by the manager. Sender receives
* a proportional amount of SetTokens on issuance or ERC20 token on redemption based on the calculated net asset value using
* oracle prices. Manager is able to enforce a premium / discount on issuance / redemption to avoid arbitrage and front
* running when relying on oracle prices. Managers can charge a fee (denominated in reserve asset).
*/
contract CustomOracleNavIssuanceModule is ModuleBase, ReentrancyGuard {
using AddressArrayUtils for address[];
using Invoke for ISetToken;
using Position for ISetToken;
using PreciseUnitMath for uint256;
using PreciseUnitMath for int256;
using ResourceIdentifier for IController;
using SafeMath for uint256;
using SafeCast for int256;
using SafeCast for uint256;
using SignedSafeMath for int256;
/* ============ Events ============ */
event SetTokenNAVIssued(
ISetToken indexed _setToken,
address _issuer,
address _to,
address _reserveAsset,
address _hookContract,
uint256 _setTokenQuantity,
uint256 _managerFee,
uint256 _premium
);
event SetTokenNAVRedeemed(
ISetToken indexed _setToken,
address _redeemer,
address _to,
address _reserveAsset,
address _hookContract,
uint256 _setTokenQuantity,
uint256 _managerFee,
uint256 _premium
);
event ReserveAssetAdded(
ISetToken indexed _setToken,
address _newReserveAsset
);
event ReserveAssetRemoved(
ISetToken indexed _setToken,
address _removedReserveAsset
);
event PremiumEdited(
ISetToken indexed _setToken,
uint256 _newPremium
);
event ManagerFeeEdited(
ISetToken indexed _setToken,
uint256 _newManagerFee,
uint256 _index
);
event FeeRecipientEdited(
ISetToken indexed _setToken,
address _feeRecipient
);
/* ============ Structs ============ */
struct NAVIssuanceSettings {
INAVIssuanceHook managerIssuanceHook; // Issuance hook configurations
INAVIssuanceHook managerRedemptionHook; // Redemption hook configurations
ISetValuer setValuer; // Optional custom set valuer. If address(0) is provided, fetch the default one from the controller
address[] reserveAssets; // Allowed reserve assets - Must have a price enabled with the price oracle
address feeRecipient; // Manager fee recipient
uint256[2] managerFees; // Manager fees. 0 index is issue and 1 index is redeem fee (0.01% = 1e14, 1% = 1e16)
uint256 maxManagerFee; // Maximum fee manager is allowed to set for issue and redeem
uint256 premiumPercentage; // Premium percentage (0.01% = 1e14, 1% = 1e16). This premium is a buffer around oracle
// prices paid by user to the SetToken, which prevents arbitrage and oracle front running
uint256 maxPremiumPercentage; // Maximum premium percentage manager is allowed to set (configured by manager)
uint256 minSetTokenSupply; // Minimum SetToken supply required for issuance and redemption
// to prevent dramatic inflationary changes to the SetToken's position multiplier
}
struct ActionInfo {
uint256 preFeeReserveQuantity; // Reserve value before fees; During issuance, represents raw quantity
// During redeem, represents post-premium value
uint256 protocolFees; // Total protocol fees (direct + manager revenue share)
uint256 managerFee; // Total manager fee paid in reserve asset
uint256 netFlowQuantity; // When issuing, quantity of reserve asset sent to SetToken
// When redeeming, quantity of reserve asset sent to redeemer
uint256 setTokenQuantity; // When issuing, quantity of SetTokens minted to mintee
// When redeeming, quantity of SetToken redeemed
uint256 previousSetTokenSupply; // SetToken supply prior to issue/redeem action
uint256 newSetTokenSupply; // SetToken supply after issue/redeem action
int256 newPositionMultiplier; // SetToken position multiplier after issue/redeem
uint256 newReservePositionUnit; // SetToken reserve asset position unit after issue/redeem
}
/* ============ State Variables ============ */
// Wrapped ETH address
IWETH public immutable weth;
// Mapping of SetToken to NAV issuance settings struct
mapping(ISetToken => NAVIssuanceSettings) public navIssuanceSettings;
// Mapping to efficiently check a SetToken's reserve asset validity
// SetToken => reserveAsset => isReserveAsset
mapping(ISetToken => mapping(address => bool)) public isReserveAsset;
/* ============ Constants ============ */
// 0 index stores the manager fee in managerFees array, percentage charged on issue (denominated in reserve asset)
uint256 constant internal MANAGER_ISSUE_FEE_INDEX = 0;
// 1 index stores the manager fee percentage in managerFees array, charged on redeem
uint256 constant internal MANAGER_REDEEM_FEE_INDEX = 1;
// 0 index stores the manager revenue share protocol fee % on the controller, charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX = 0;
// 1 index stores the manager revenue share protocol fee % on the controller, charged in the redeem function
uint256 constant internal PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX = 1;
// 2 index stores the direct protocol fee % on the controller, charged in the issuance function
uint256 constant internal PROTOCOL_ISSUE_DIRECT_FEE_INDEX = 2;
// 3 index stores the direct protocol fee % on the controller, charged in the redeem function
uint256 constant internal PROTOCOL_REDEEM_DIRECT_FEE_INDEX = 3;
/* ============ Constructor ============ */
/**
* @param _controller Address of controller contract
* @param _weth Address of wrapped eth
*/
constructor(IController _controller, IWETH _weth) public ModuleBase(_controller) {
weth = _weth;
}
/* ============ External Functions ============ */
/**
* Deposits the allowed reserve asset into the SetToken and mints the appropriate % of Net Asset Value of the SetToken
* to the specified _to address.
*
* @param _setToken Instance of the SetToken contract
* @param _reserveAsset Address of the reserve asset to issue with
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
* @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance
* @param _to Address to mint SetToken to
*/
function issue(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
uint256 _minSetTokenReceiveQuantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, _reserveAsset, _reserveAssetQuantity);
_callPreIssueHooks(_setToken, _reserveAsset, _reserveAssetQuantity, msg.sender, _to);
ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, _reserveAsset, _reserveAssetQuantity);
_validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo);
_transferCollateralAndHandleFees(_setToken, IERC20(_reserveAsset), issueInfo);
_handleIssueStateUpdates(_setToken, _reserveAsset, _to, issueInfo);
}
/**
* Wraps ETH and deposits WETH if allowed into the SetToken and mints the appropriate % of Net Asset Value of the SetToken
* to the specified _to address.
*
* @param _setToken Instance of the SetToken contract
* @param _minSetTokenReceiveQuantity Min quantity of SetToken to receive after issuance
* @param _to Address to mint SetToken to
*/
function issueWithEther(
ISetToken _setToken,
uint256 _minSetTokenReceiveQuantity,
address _to
)
external
payable
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
weth.deposit{ value: msg.value }();
_validateCommon(_setToken, address(weth), msg.value);
_callPreIssueHooks(_setToken, address(weth), msg.value, msg.sender, _to);
ActionInfo memory issueInfo = _createIssuanceInfo(_setToken, address(weth), msg.value);
_validateIssuanceInfo(_setToken, _minSetTokenReceiveQuantity, issueInfo);
_transferWETHAndHandleFees(_setToken, issueInfo);
_handleIssueStateUpdates(_setToken, address(weth), _to, issueInfo);
}
/**
* Redeems a SetToken into a valid reserve asset representing the appropriate % of Net Asset Value of the SetToken
* to the specified _to address. Only valid if there are available reserve units on the SetToken.
*
* @param _setToken Instance of the SetToken contract
* @param _reserveAsset Address of the reserve asset to redeem with
* @param _setTokenQuantity Quantity of SetTokens to redeem
* @param _minReserveReceiveQuantity Min quantity of reserve asset to receive
* @param _to Address to redeem reserve asset to
*/
function redeem(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity,
uint256 _minReserveReceiveQuantity,
address _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, _reserveAsset, _setTokenQuantity);
_callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to);
ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, _reserveAsset, _setTokenQuantity);
_validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo);
_setToken.burn(msg.sender, _setTokenQuantity);
// Instruct the SetToken to transfer the reserve asset back to the user
_setToken.strictInvokeTransfer(
_reserveAsset,
_to,
redeemInfo.netFlowQuantity
);
_handleRedemptionFees(_setToken, _reserveAsset, redeemInfo);
_handleRedeemStateUpdates(_setToken, _reserveAsset, _to, redeemInfo);
}
/**
* Redeems a SetToken into Ether (if WETH is valid) representing the appropriate % of Net Asset Value of the SetToken
* to the specified _to address. Only valid if there are available WETH units on the SetToken.
*
* @param _setToken Instance of the SetToken contract
* @param _setTokenQuantity Quantity of SetTokens to redeem
* @param _minReserveReceiveQuantity Min quantity of reserve asset to receive
* @param _to Address to redeem reserve asset to
*/
function redeemIntoEther(
ISetToken _setToken,
uint256 _setTokenQuantity,
uint256 _minReserveReceiveQuantity,
address payable _to
)
external
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
_validateCommon(_setToken, address(weth), _setTokenQuantity);
_callPreRedeemHooks(_setToken, _setTokenQuantity, msg.sender, _to);
ActionInfo memory redeemInfo = _createRedemptionInfo(_setToken, address(weth), _setTokenQuantity);
_validateRedemptionInfo(_setToken, _minReserveReceiveQuantity, _setTokenQuantity, redeemInfo);
_setToken.burn(msg.sender, _setTokenQuantity);
// Instruct the SetToken to transfer WETH from SetToken to module
_setToken.strictInvokeTransfer(
address(weth),
address(this),
redeemInfo.netFlowQuantity
);
weth.withdraw(redeemInfo.netFlowQuantity);
_to.transfer(redeemInfo.netFlowQuantity);
_handleRedemptionFees(_setToken, address(weth), redeemInfo);
_handleRedeemStateUpdates(_setToken, address(weth), _to, redeemInfo);
}
/**
* SET MANAGER ONLY. Add an allowed reserve asset
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset to add
*/
function addReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) {
require(!isReserveAsset[_setToken][_reserveAsset], "Reserve asset already exists");
navIssuanceSettings[_setToken].reserveAssets.push(_reserveAsset);
isReserveAsset[_setToken][_reserveAsset] = true;
emit ReserveAssetAdded(_setToken, _reserveAsset);
}
/**
* SET MANAGER ONLY. Remove a reserve asset
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset to remove
*/
function removeReserveAsset(ISetToken _setToken, address _reserveAsset) external onlyManagerAndValidSet(_setToken) {
require(isReserveAsset[_setToken][_reserveAsset], "Reserve asset does not exist");
navIssuanceSettings[_setToken].reserveAssets = navIssuanceSettings[_setToken].reserveAssets.remove(_reserveAsset);
delete isReserveAsset[_setToken][_reserveAsset];
emit ReserveAssetRemoved(_setToken, _reserveAsset);
}
/**
* SET MANAGER ONLY. Edit the premium percentage
*
* @param _setToken Instance of the SetToken
* @param _premiumPercentage Premium percentage in 10e16 (e.g. 10e16 = 1%)
*/
function editPremium(ISetToken _setToken, uint256 _premiumPercentage) external onlyManagerAndValidSet(_setToken) {
require(_premiumPercentage <= navIssuanceSettings[_setToken].maxPremiumPercentage, "Premium must be less than maximum allowed");
navIssuanceSettings[_setToken].premiumPercentage = _premiumPercentage;
emit PremiumEdited(_setToken, _premiumPercentage);
}
/**
* SET MANAGER ONLY. Edit manager fee
*
* @param _setToken Instance of the SetToken
* @param _managerFeePercentage Manager fee percentage in 10e16 (e.g. 10e16 = 1%)
* @param _managerFeeIndex Manager fee index. 0 index is issue fee, 1 index is redeem fee
*/
function editManagerFee(
ISetToken _setToken,
uint256 _managerFeePercentage,
uint256 _managerFeeIndex
)
external
onlyManagerAndValidSet(_setToken)
{
require(_managerFeePercentage <= navIssuanceSettings[_setToken].maxManagerFee, "Manager fee must be less than maximum allowed");
navIssuanceSettings[_setToken].managerFees[_managerFeeIndex] = _managerFeePercentage;
emit ManagerFeeEdited(_setToken, _managerFeePercentage, _managerFeeIndex);
}
/**
* SET MANAGER ONLY. Edit the manager fee recipient
*
* @param _setToken Instance of the SetToken
* @param _managerFeeRecipient Manager fee recipient
*/
function editFeeRecipient(ISetToken _setToken, address _managerFeeRecipient) external onlyManagerAndValidSet(_setToken) {
require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address");
navIssuanceSettings[_setToken].feeRecipient = _managerFeeRecipient;
emit FeeRecipientEdited(_setToken, _managerFeeRecipient);
}
/**
* SET MANAGER ONLY. Initializes this module to the SetToken with hooks, allowed reserve assets,
* fees and issuance premium. Only callable by the SetToken's manager. Hook addresses are optional.
* Address(0) means that no hook will be called.
*
* @param _setToken Instance of the SetToken to issue
* @param _navIssuanceSettings NAVIssuanceSettings struct defining parameters
*/
function initialize(
ISetToken _setToken,
NAVIssuanceSettings memory _navIssuanceSettings
)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_navIssuanceSettings.reserveAssets.length > 0, "Reserve assets must be greater than 0");
require(_navIssuanceSettings.maxManagerFee < PreciseUnitMath.preciseUnit(), "Max manager fee must be less than 100%");
require(_navIssuanceSettings.maxPremiumPercentage < PreciseUnitMath.preciseUnit(), "Max premium percentage must be less than 100%");
require(_navIssuanceSettings.managerFees[0] <= _navIssuanceSettings.maxManagerFee, "Manager issue fee must be less than max");
require(_navIssuanceSettings.managerFees[1] <= _navIssuanceSettings.maxManagerFee, "Manager redeem fee must be less than max");
require(_navIssuanceSettings.premiumPercentage <= _navIssuanceSettings.maxPremiumPercentage, "Premium must be less than max");
require(_navIssuanceSettings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
// Initial mint of Set cannot use NAVIssuance since minSetTokenSupply must be > 0
require(_navIssuanceSettings.minSetTokenSupply > 0, "Min SetToken supply must be greater than 0");
for (uint256 i = 0; i < _navIssuanceSettings.reserveAssets.length; i++) {
require(!isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]], "Reserve assets must be unique");
isReserveAsset[_setToken][_navIssuanceSettings.reserveAssets[i]] = true;
}
navIssuanceSettings[_setToken] = _navIssuanceSettings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Issuance settings and
* reserve asset states are deleted.
*/
function removeModule() external override {
ISetToken setToken = ISetToken(msg.sender);
for (uint256 i = 0; i < navIssuanceSettings[setToken].reserveAssets.length; i++) {
delete isReserveAsset[setToken][navIssuanceSettings[setToken].reserveAssets[i]];
}
delete navIssuanceSettings[setToken];
}
receive() external payable {}
/* ============ External Getter Functions ============ */
function getReserveAssets(ISetToken _setToken) external view returns (address[] memory) {
return navIssuanceSettings[_setToken].reserveAssets;
}
function getIssuePremium(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (uint256)
{
return _getIssuePremium(_setToken, _reserveAsset, _reserveAssetQuantity);
}
function getRedeemPremium(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (uint256)
{
return _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity);
}
function getManagerFee(ISetToken _setToken, uint256 _managerFeeIndex) external view returns (uint256) {
return navIssuanceSettings[_setToken].managerFees[_managerFeeIndex];
}
/**
* Get the expected SetTokens minted to recipient on issuance
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
*
* @return uint256 Expected SetTokens to be minted to recipient
*/
function getExpectedSetTokenIssueQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (uint256)
{
(,, uint256 netReserveFlow) = _getFees(
_setToken,
_reserveAssetQuantity,
PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_ISSUE_DIRECT_FEE_INDEX,
MANAGER_ISSUE_FEE_INDEX
);
uint256 setTotalSupply = _setToken.totalSupply();
return _getSetTokenMintQuantity(
_setToken,
_reserveAsset,
netReserveFlow,
setTotalSupply
);
}
/**
* Get the expected reserve asset to be redeemed
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _setTokenQuantity Quantity of SetTokens to redeem
*
* @return uint256 Expected reserve asset quantity redeemed
*/
function getExpectedReserveRedeemQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (uint256)
{
uint256 preFeeReserveQuantity = _getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(,, uint256 netReserveFlows) = _getFees(
_setToken,
preFeeReserveQuantity,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
return netReserveFlows;
}
/**
* Checks if issue is valid
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _reserveAssetQuantity Quantity of the reserve asset to issue with
*
* @return bool Returns true if issue is valid
*/
function isIssueValid(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
external
view
returns (bool)
{
uint256 setTotalSupply = _setToken.totalSupply();
return _reserveAssetQuantity != 0
&& isReserveAsset[_setToken][_reserveAsset]
&& setTotalSupply >= navIssuanceSettings[_setToken].minSetTokenSupply;
}
/**
* Checks if redeem is valid
*
* @param _setToken Instance of the SetToken
* @param _reserveAsset Address of the reserve asset
* @param _setTokenQuantity Quantity of SetTokens to redeem
*
* @return bool Returns true if redeem is valid
*/
function isRedeemValid(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
external
view
returns (bool)
{
uint256 setTotalSupply = _setToken.totalSupply();
if (
_setTokenQuantity == 0
|| !isReserveAsset[_setToken][_reserveAsset]
|| setTotalSupply < navIssuanceSettings[_setToken].minSetTokenSupply.add(_setTokenQuantity)
) {
return false;
} else {
uint256 totalRedeemValue =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(,, uint256 expectedRedeemQuantity) = _getFees(
_setToken,
totalRedeemValue,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
return existingUnit.preciseMul(setTotalSupply) >= expectedRedeemQuantity;
}
}
/* ============ Internal Functions ============ */
function _validateCommon(ISetToken _setToken, address _reserveAsset, uint256 _quantity) internal view {
require(_quantity > 0, "Quantity must be > 0");
require(isReserveAsset[_setToken][_reserveAsset], "Must be valid reserve asset");
}
function _validateIssuanceInfo(ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, ActionInfo memory _issueInfo) internal view {
// Check that total supply is greater than min supply needed for issuance
// Note: A min supply amount is needed to avoid division by 0 when SetToken supply is 0
require(
_issueInfo.previousSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply,
"Supply must be greater than minimum to enable issuance"
);
require(_issueInfo.setTokenQuantity >= _minSetTokenReceiveQuantity, "Must be greater than min SetToken");
}
function _validateRedemptionInfo(
ISetToken _setToken,
uint256 _minReserveReceiveQuantity,
uint256 _setTokenQuantity,
ActionInfo memory _redeemInfo
)
internal
view
{
// Check that new supply is more than min supply needed for redemption
// Note: A min supply amount is needed to avoid division by 0 when redeeming SetToken to 0
require(
_redeemInfo.newSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply,
"Supply must be greater than minimum to enable redemption"
);
require(_redeemInfo.netFlowQuantity >= _minReserveReceiveQuantity, "Must be greater than min receive reserve quantity");
}
function _createIssuanceInfo(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity
)
internal
view
returns (ActionInfo memory)
{
ActionInfo memory issueInfo;
issueInfo.previousSetTokenSupply = _setToken.totalSupply();
issueInfo.preFeeReserveQuantity = _reserveAssetQuantity;
(issueInfo.protocolFees, issueInfo.managerFee, issueInfo.netFlowQuantity) = _getFees(
_setToken,
issueInfo.preFeeReserveQuantity,
PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_ISSUE_DIRECT_FEE_INDEX,
MANAGER_ISSUE_FEE_INDEX
);
issueInfo.setTokenQuantity = _getSetTokenMintQuantity(
_setToken,
_reserveAsset,
issueInfo.netFlowQuantity,
issueInfo.previousSetTokenSupply
);
(issueInfo.newSetTokenSupply, issueInfo.newPositionMultiplier) = _getIssuePositionMultiplier(_setToken, issueInfo);
issueInfo.newReservePositionUnit = _getIssuePositionUnit(_setToken, _reserveAsset, issueInfo);
return issueInfo;
}
function _createRedemptionInfo(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
internal
view
returns (ActionInfo memory)
{
ActionInfo memory redeemInfo;
redeemInfo.setTokenQuantity = _setTokenQuantity;
redeemInfo.preFeeReserveQuantity =_getRedeemReserveQuantity(_setToken, _reserveAsset, _setTokenQuantity);
(redeemInfo.protocolFees, redeemInfo.managerFee, redeemInfo.netFlowQuantity) = _getFees(
_setToken,
redeemInfo.preFeeReserveQuantity,
PROTOCOL_REDEEM_MANAGER_REVENUE_SHARE_FEE_INDEX,
PROTOCOL_REDEEM_DIRECT_FEE_INDEX,
MANAGER_REDEEM_FEE_INDEX
);
redeemInfo.previousSetTokenSupply = _setToken.totalSupply();
(redeemInfo.newSetTokenSupply, redeemInfo.newPositionMultiplier) = _getRedeemPositionMultiplier(_setToken, _setTokenQuantity, redeemInfo);
redeemInfo.newReservePositionUnit = _getRedeemPositionUnit(_setToken, _reserveAsset, redeemInfo);
return redeemInfo;
}
/**
* Transfer reserve asset from user to SetToken and fees from user to appropriate fee recipients
*/
function _transferCollateralAndHandleFees(ISetToken _setToken, IERC20 _reserveAsset, ActionInfo memory _issueInfo) internal {
transferFrom(_reserveAsset, msg.sender, address(_setToken), _issueInfo.netFlowQuantity);
if (_issueInfo.protocolFees > 0) {
transferFrom(_reserveAsset, msg.sender, controller.feeRecipient(), _issueInfo.protocolFees);
}
if (_issueInfo.managerFee > 0) {
transferFrom(_reserveAsset, msg.sender, navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee);
}
}
/**
* Transfer WETH from module to SetToken and fees from module to appropriate fee recipients
*/
function _transferWETHAndHandleFees(ISetToken _setToken, ActionInfo memory _issueInfo) internal {
weth.transfer(address(_setToken), _issueInfo.netFlowQuantity);
if (_issueInfo.protocolFees > 0) {
weth.transfer(controller.feeRecipient(), _issueInfo.protocolFees);
}
if (_issueInfo.managerFee > 0) {
weth.transfer(navIssuanceSettings[_setToken].feeRecipient, _issueInfo.managerFee);
}
}
function _handleIssueStateUpdates(
ISetToken _setToken,
address _reserveAsset,
address _to,
ActionInfo memory _issueInfo
)
internal
{
_setToken.editPositionMultiplier(_issueInfo.newPositionMultiplier);
_setToken.editDefaultPosition(_reserveAsset, _issueInfo.newReservePositionUnit);
_setToken.mint(_to, _issueInfo.setTokenQuantity);
emit SetTokenNAVIssued(
_setToken,
msg.sender,
_to,
_reserveAsset,
address(navIssuanceSettings[_setToken].managerIssuanceHook),
_issueInfo.setTokenQuantity,
_issueInfo.managerFee,
_issueInfo.protocolFees
);
}
function _handleRedeemStateUpdates(
ISetToken _setToken,
address _reserveAsset,
address _to,
ActionInfo memory _redeemInfo
)
internal
{
_setToken.editPositionMultiplier(_redeemInfo.newPositionMultiplier);
_setToken.editDefaultPosition(_reserveAsset, _redeemInfo.newReservePositionUnit);
emit SetTokenNAVRedeemed(
_setToken,
msg.sender,
_to,
_reserveAsset,
address(navIssuanceSettings[_setToken].managerRedemptionHook),
_redeemInfo.setTokenQuantity,
_redeemInfo.managerFee,
_redeemInfo.protocolFees
);
}
function _handleRedemptionFees(ISetToken _setToken, address _reserveAsset, ActionInfo memory _redeemInfo) internal {
// Instruct the SetToken to transfer protocol fee to fee recipient if there is a fee
payProtocolFeeFromSetToken(_setToken, _reserveAsset, _redeemInfo.protocolFees);
// Instruct the SetToken to transfer manager fee to manager fee recipient if there is a fee
if (_redeemInfo.managerFee > 0) {
_setToken.strictInvokeTransfer(
_reserveAsset,
navIssuanceSettings[_setToken].feeRecipient,
_redeemInfo.managerFee
);
}
}
/**
* Returns the issue premium percentage. Virtual function that can be overridden in future versions of the module
* and can contain arbitrary logic to calculate the issuance premium.
*/
function _getIssuePremium(
ISetToken _setToken,
address /* _reserveAsset */,
uint256 /* _reserveAssetQuantity */
)
virtual
internal
view
returns (uint256)
{
return navIssuanceSettings[_setToken].premiumPercentage;
}
/**
* Returns the redeem premium percentage. Virtual function that can be overridden in future versions of the module
* and can contain arbitrary logic to calculate the redemption premium.
*/
function _getRedeemPremium(
ISetToken _setToken,
address /* _reserveAsset */,
uint256 /* _setTokenQuantity */
)
virtual
internal
view
returns (uint256)
{
return navIssuanceSettings[_setToken].premiumPercentage;
}
/**
* Returns the fees attributed to the manager and the protocol. The fees are calculated as follows:
*
* ManagerFee = (manager fee % - % to protocol) * reserveAssetQuantity
* Protocol Fee = (% manager fee share + direct fee %) * reserveAssetQuantity
*
* @param _setToken Instance of the SetToken
* @param _reserveAssetQuantity Quantity of reserve asset to calculate fees from
* @param _protocolManagerFeeIndex Index to pull rev share NAV Issuance fee from the Controller
* @param _protocolDirectFeeIndex Index to pull direct NAV issuance fee from the Controller
* @param _managerFeeIndex Index from NAVIssuanceSettings (0 = issue fee, 1 = redeem fee)
*
* @return uint256 Fees paid to the protocol in reserve asset
* @return uint256 Fees paid to the manager in reserve asset
* @return uint256 Net reserve to user net of fees
*/
function _getFees(
ISetToken _setToken,
uint256 _reserveAssetQuantity,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns (uint256, uint256, uint256)
{
(uint256 protocolFeePercentage, uint256 managerFeePercentage) = _getProtocolAndManagerFeePercentages(
_setToken,
_protocolManagerFeeIndex,
_protocolDirectFeeIndex,
_managerFeeIndex
);
// Calculate total notional fees
uint256 protocolFees = protocolFeePercentage.preciseMul(_reserveAssetQuantity);
uint256 managerFee = managerFeePercentage.preciseMul(_reserveAssetQuantity);
uint256 netReserveFlow = _reserveAssetQuantity.sub(protocolFees).sub(managerFee);
return (protocolFees, managerFee, netReserveFlow);
}
function _getProtocolAndManagerFeePercentages(
ISetToken _setToken,
uint256 _protocolManagerFeeIndex,
uint256 _protocolDirectFeeIndex,
uint256 _managerFeeIndex
)
internal
view
returns(uint256, uint256)
{
// Get protocol fee percentages
uint256 protocolDirectFeePercent = controller.getModuleFee(address(this), _protocolDirectFeeIndex);
uint256 protocolManagerShareFeePercent = controller.getModuleFee(address(this), _protocolManagerFeeIndex);
uint256 managerFeePercent = navIssuanceSettings[_setToken].managerFees[_managerFeeIndex];
// Calculate revenue share split percentage
uint256 protocolRevenueSharePercentage = protocolManagerShareFeePercent.preciseMul(managerFeePercent);
uint256 managerRevenueSharePercentage = managerFeePercent.sub(protocolRevenueSharePercentage);
uint256 totalProtocolFeePercentage = protocolRevenueSharePercentage.add(protocolDirectFeePercent);
return (totalProtocolFeePercentage, managerRevenueSharePercentage);
}
function _getSetTokenMintQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _netReserveFlows, // Value of reserve asset net of fees
uint256 _setTotalSupply
)
internal
view
returns (uint256)
{
uint256 premiumPercentage = _getIssuePremium(_setToken, _reserveAsset, _netReserveFlows);
uint256 premiumValue = _netReserveFlows.preciseMul(premiumPercentage);
// If the set manager provided a custom valuer at initialization time, use it. Otherwise get it from the controller
// Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (1e18)
// Reverts if price is not found
uint256 setTokenValuation = _getSetValuer(_setToken).calculateSetTokenValuation(_setToken, _reserveAsset);
// Get reserve asset decimals
uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals();
uint256 normalizedTotalReserveQuantityNetFees = _netReserveFlows.preciseDiv(10 ** reserveAssetDecimals);
uint256 normalizedTotalReserveQuantityNetFeesAndPremium = _netReserveFlows.sub(premiumValue).preciseDiv(10 ** reserveAssetDecimals);
// Calculate SetTokens to mint to issuer
uint256 denominator = _setTotalSupply.preciseMul(setTokenValuation).add(normalizedTotalReserveQuantityNetFees).sub(normalizedTotalReserveQuantityNetFeesAndPremium);
return normalizedTotalReserveQuantityNetFeesAndPremium.preciseMul(_setTotalSupply).preciseDiv(denominator);
}
function _getRedeemReserveQuantity(
ISetToken _setToken,
address _reserveAsset,
uint256 _setTokenQuantity
)
internal
view
returns (uint256)
{
// Get valuation of the SetToken with the quote asset as the reserve asset. Returns value in precise units (10e18)
// Reverts if price is not found
uint256 setTokenValuation = _getSetValuer(_setToken).calculateSetTokenValuation(_setToken, _reserveAsset);
uint256 totalRedeemValueInPreciseUnits = _setTokenQuantity.preciseMul(setTokenValuation);
// Get reserve asset decimals
uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals();
uint256 prePremiumReserveQuantity = totalRedeemValueInPreciseUnits.preciseMul(10 ** reserveAssetDecimals);
uint256 premiumPercentage = _getRedeemPremium(_setToken, _reserveAsset, _setTokenQuantity);
uint256 premiumQuantity = prePremiumReserveQuantity.preciseMulCeil(premiumPercentage);
return prePremiumReserveQuantity.sub(premiumQuantity);
}
/**
* The new position multiplier is calculated as follows:
* inflationPercentage = (newSupply - oldSupply) / newSupply
* newMultiplier = (1 - inflationPercentage) * positionMultiplier
*/
function _getIssuePositionMultiplier(
ISetToken _setToken,
ActionInfo memory _issueInfo
)
internal
view
returns (uint256, int256)
{
// Calculate inflation and new position multiplier. Note: Round inflation up in order to round position multiplier down
uint256 newTotalSupply = _issueInfo.setTokenQuantity.add(_issueInfo.previousSetTokenSupply);
int256 newPositionMultiplier = _setToken.positionMultiplier()
.mul(_issueInfo.previousSetTokenSupply.toInt256())
.div(newTotalSupply.toInt256());
return (newTotalSupply, newPositionMultiplier);
}
/**
* Calculate deflation and new position multiplier. Note: Round deflation down in order to round position multiplier down
*
* The new position multiplier is calculated as follows:
* deflationPercentage = (oldSupply - newSupply) / newSupply
* newMultiplier = (1 + deflationPercentage) * positionMultiplier
*/
function _getRedeemPositionMultiplier(
ISetToken _setToken,
uint256 _setTokenQuantity,
ActionInfo memory _redeemInfo
)
internal
view
returns (uint256, int256)
{
uint256 newTotalSupply = _redeemInfo.previousSetTokenSupply.sub(_setTokenQuantity);
int256 newPositionMultiplier = _setToken.positionMultiplier()
.mul(_redeemInfo.previousSetTokenSupply.toInt256())
.div(newTotalSupply.toInt256());
return (newTotalSupply, newPositionMultiplier);
}
/**
* The new position reserve asset unit is calculated as follows:
* totalReserve = (oldUnit * oldSetTokenSupply) + reserveQuantity
* newUnit = totalReserve / newSetTokenSupply
*/
function _getIssuePositionUnit(
ISetToken _setToken,
address _reserveAsset,
ActionInfo memory _issueInfo
)
internal
view
returns (uint256)
{
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
uint256 totalReserve = existingUnit
.preciseMul(_issueInfo.previousSetTokenSupply)
.add(_issueInfo.netFlowQuantity);
return totalReserve.preciseDiv(_issueInfo.newSetTokenSupply);
}
/**
* The new position reserve asset unit is calculated as follows:
* totalReserve = (oldUnit * oldSetTokenSupply) - reserveQuantityToSendOut
* newUnit = totalReserve / newSetTokenSupply
*/
function _getRedeemPositionUnit(
ISetToken _setToken,
address _reserveAsset,
ActionInfo memory _redeemInfo
)
internal
view
returns (uint256)
{
uint256 existingUnit = _setToken.getDefaultPositionRealUnit(_reserveAsset).toUint256();
uint256 totalExistingUnits = existingUnit.preciseMul(_redeemInfo.previousSetTokenSupply);
uint256 outflow = _redeemInfo.netFlowQuantity.add(_redeemInfo.protocolFees).add(_redeemInfo.managerFee);
// Require withdrawable quantity is greater than existing collateral
require(totalExistingUnits >= outflow, "Must be greater than total available collateral");
return totalExistingUnits.sub(outflow).preciseDiv(_redeemInfo.newSetTokenSupply);
}
/**
* If a pre-issue hook has been configured, call the external-protocol contract. Pre-issue hook logic
* can contain arbitrary logic including validations, external function calls, etc.
*/
function _callPreIssueHooks(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
address _caller,
address _to
)
internal
{
INAVIssuanceHook preIssueHook = navIssuanceSettings[_setToken].managerIssuanceHook;
if (address(preIssueHook) != address(0)) {
preIssueHook.invokePreIssueHook(_setToken, _reserveAsset, _reserveAssetQuantity, _caller, _to);
}
}
/**
* If a pre-redeem hook has been configured, call the external-protocol contract.
*/
function _callPreRedeemHooks(ISetToken _setToken, uint256 _setQuantity, address _caller, address _to) internal {
INAVIssuanceHook preRedeemHook = navIssuanceSettings[_setToken].managerRedemptionHook;
if (address(preRedeemHook) != address(0)) {
preRedeemHook.invokePreRedeemHook(_setToken, _setQuantity, _caller, _to);
}
}
/**
* If a custom set valuer has been configured, use it. Otherwise fetch the default one form the
* controller.
*/
function _getSetValuer(ISetToken _setToken) internal view returns (ISetValuer) {
ISetValuer customValuer = navIssuanceSettings[_setToken].setValuer;
return address(customValuer) == address(0) ? controller.getSetValuer() : customValuer;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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, 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 SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IController {
function addSet(address _setToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isSet(address _setToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { ISetToken } from "../interfaces/ISetToken.sol";
interface ISetValuer {
function calculateSetTokenValuation(ISetToken _setToken, address _quoteAsset) external view returns (uint256);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { ISetToken } from "./ISetToken.sol";
interface INAVIssuanceHook {
function invokePreIssueHook(
ISetToken _setToken,
address _reserveAsset,
uint256 _reserveAssetQuantity,
address _sender,
address _to
)
external;
function invokePreRedeemHook(
ISetToken _setToken,
uint256 _redeemQuantity,
address _sender,
address _to
)
external;
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
/**
* @title Invoke
* @author Set Protocol
*
* A collection of common utility functions for interacting with the SetToken's invoke function
*/
library Invoke {
using SafeMath for uint256;
/* ============ Internal ============ */
/**
* Instructs the SetToken to set approvals of the ERC20 token to a spender.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to approve
* @param _spender The account allowed to spend the SetToken's balance
* @param _quantity The quantity of allowance to allow
*/
function invokeApprove(
ISetToken _setToken,
address _token,
address _spender,
uint256 _quantity
)
internal
{
bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity);
_setToken.invoke(_token, 0, callData);
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function invokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity);
_setToken.invoke(_token, 0, callData);
}
}
/**
* Instructs the SetToken to transfer the ERC20 token to a recipient.
* The new SetToken balance must equal the existing balance less the quantity transferred
*
* @param _setToken SetToken instance to invoke
* @param _token ERC20 token to transfer
* @param _to The recipient account
* @param _quantity The quantity to transfer
*/
function strictInvokeTransfer(
ISetToken _setToken,
address _token,
address _to,
uint256 _quantity
)
internal
{
if (_quantity > 0) {
// Retrieve current balance of token for the SetToken
uint256 existingBalance = IERC20(_token).balanceOf(address(_setToken));
Invoke.invokeTransfer(_setToken, _token, _to, _quantity);
// Get new balance of transferred token for SetToken
uint256 newBalance = IERC20(_token).balanceOf(address(_setToken));
// Verify only the transfer quantity is subtracted
require(
newBalance == existingBalance.sub(_quantity),
"Invalid post transfer balance"
);
}
}
/**
* Instructs the SetToken to unwrap the passed quantity of WETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeUnwrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity);
_setToken.invoke(_weth, 0, callData);
}
/**
* Instructs the SetToken to wrap the passed quantity of ETH
*
* @param _setToken SetToken instance to invoke
* @param _weth WETH address
* @param _quantity The quantity to unwrap
*/
function invokeWrapWETH(ISetToken _setToken, address _weth, uint256 _quantity) internal {
bytes memory callData = abi.encodeWithSignature("deposit()");
_setToken.invoke(_weth, _quantity, callData);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ISetToken
* @author Set Protocol
*
* Interface for operating with SetTokens.
*/
interface ISetToken is IERC20 {
/* ============ Enums ============ */
enum ModuleState {
NONE,
PENDING,
INITIALIZED
}
/* ============ Structs ============ */
/**
* The base definition of a SetToken Position
*
* @param component Address of token in the Position
* @param module If not in default state, the address of associated module
* @param unit Each unit is the # of components per 10^18 of a SetToken
* @param positionState Position ENUM. Default is 0; External is 1
* @param data Arbitrary data
*/
struct Position {
address component;
address module;
int256 unit;
uint8 positionState;
bytes data;
}
/**
* A struct that stores a component's cash position details and external positions
* This data structure allows O(1) access to a component's cash position units and
* virtual units.
*
* @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency
* updating all units at once via the position multiplier. Virtual units are achieved
* by dividing a "real" value by the "positionMultiplier"
* @param componentIndex
* @param externalPositionModules List of external modules attached to each external position. Each module
* maps to an external position
* @param externalPositions Mapping of module => ExternalPosition struct for a given component
*/
struct ComponentPosition {
int256 virtualUnit;
address[] externalPositionModules;
mapping(address => ExternalPosition) externalPositions;
}
/**
* A struct that stores a component's external position details including virtual unit and any
* auxiliary data.
*
* @param virtualUnit Virtual value of a component's EXTERNAL position.
* @param data Arbitrary data
*/
struct ExternalPosition {
int256 virtualUnit;
bytes data;
}
/* ============ Functions ============ */
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title IWETH
* @author Set Protocol
*
* Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal
* functionality.
*/
interface IWETH is IERC20{
function deposit()
external
payable;
function withdraw(
uint256 wad
)
external;
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
import { ExplicitERC20 } from "../../lib/ExplicitERC20.sol";
import { IController } from "../../interfaces/IController.sol";
import { IModule } from "../../interfaces/IModule.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { Invoke } from "./Invoke.sol";
import { Position } from "./Position.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
import { ResourceIdentifier } from "./ResourceIdentifier.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title ModuleBase
* @author Set Protocol
*
* Abstract class that houses common Module-related state and functions.
*/
abstract contract ModuleBase is IModule {
using AddressArrayUtils for address[];
using Invoke for ISetToken;
using Position for ISetToken;
using PreciseUnitMath for uint256;
using ResourceIdentifier for IController;
using SafeCast for int256;
using SafeCast for uint256;
using SafeMath for uint256;
using SignedSafeMath for int256;
/* ============ State Variables ============ */
// Address of the controller
IController public controller;
/* ============ Modifiers ============ */
modifier onlyManagerAndValidSet(ISetToken _setToken) {
require(isSetManager(_setToken, msg.sender), "Must be the SetToken manager");
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
_;
}
modifier onlySetManager(ISetToken _setToken, address _caller) {
require(isSetManager(_setToken, _caller), "Must be the SetToken manager");
_;
}
modifier onlyValidAndInitializedSet(ISetToken _setToken) {
require(isSetValidAndInitialized(_setToken), "Must be a valid and initialized SetToken");
_;
}
/**
* Throws if the sender is not a SetToken's module or module not enabled
*/
modifier onlyModule(ISetToken _setToken) {
require(
_setToken.moduleStates(msg.sender) == ISetToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
_;
}
/**
* Utilized during module initializations to check that the module is in pending state
* and that the SetToken is valid
*/
modifier onlyValidAndPendingSet(ISetToken _setToken) {
require(controller.isSet(address(_setToken)), "Must be controller-enabled SetToken");
require(isSetPendingInitialization(_setToken), "Must be pending initialization");
_;
}
/* ============ Constructor ============ */
/**
* Set state variables and map asset pairs to their oracles
*
* @param _controller Address of controller contract
*/
constructor(IController _controller) public {
controller = _controller;
}
/* ============ Internal Functions ============ */
/**
* Transfers tokens from an address (that has set allowance on the module).
*
* @param _token The address of the ERC20 token
* @param _from The address to transfer from
* @param _to The address to transfer to
* @param _quantity The number of tokens to transfer
*/
function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal {
ExplicitERC20.transferFrom(_token, _from, _to, _quantity);
}
/**
* Gets the integration for the module with the passed in name. Validates that the address is not empty
*/
function getAndValidateAdapter(string memory _integrationName) internal view returns(address) {
bytes32 integrationHash = getNameHash(_integrationName);
return getAndValidateAdapterWithHash(integrationHash);
}
/**
* Gets the integration for the module with the passed in hash. Validates that the address is not empty
*/
function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) {
address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash(
address(this),
_integrationHash
);
require(adapter != address(0), "Must be valid adapter");
return adapter;
}
/**
* Gets the total fee for this module of the passed in index (fee % * quantity)
*/
function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) {
uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex);
return _quantity.preciseMul(feePercentage);
}
/**
* Pays the _feeQuantity from the _setToken denominated in _token to the protocol fee recipient
*/
function payProtocolFeeFromSetToken(ISetToken _setToken, address _token, uint256 _feeQuantity) internal {
if (_feeQuantity > 0) {
_setToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity);
}
}
/**
* Returns true if the module is in process of initialization on the SetToken
*/
function isSetPendingInitialization(ISetToken _setToken) internal view returns(bool) {
return _setToken.isPendingModule(address(this));
}
/**
* Returns true if the address is the SetToken's manager
*/
function isSetManager(ISetToken _setToken, address _toCheck) internal view returns(bool) {
return _setToken.manager() == _toCheck;
}
/**
* Returns true if SetToken must be enabled on the controller
* and module is registered on the SetToken
*/
function isSetValidAndInitialized(ISetToken _setToken) internal view returns(bool) {
return controller.isSet(address(_setToken)) &&
_setToken.isInitializedModule(address(this));
}
/**
* Hashes the string and returns a bytes32 value
*/
function getNameHash(string memory _name) internal pure returns(bytes32) {
return keccak256(bytes(_name));
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/SafeCast.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
/**
* @title Position
* @author Set Protocol
*
* Collection of helper functions for handling and updating SetToken Positions
*
* CHANGELOG:
* - Updated editExternalPosition to work when no external position is associated with module
*/
library Position {
using SafeCast for uint256;
using SafeMath for uint256;
using SafeCast for int256;
using SignedSafeMath for int256;
using PreciseUnitMath for uint256;
/* ============ Helper ============ */
/**
* Returns whether the SetToken has a default position for a given component (if the real unit is > 0)
*/
function hasDefaultPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) > 0;
}
/**
* Returns whether the SetToken has an external position for a given component (if # of position modules is > 0)
*/
function hasExternalPosition(ISetToken _setToken, address _component) internal view returns(bool) {
return _setToken.getExternalPositionModules(_component).length > 0;
}
/**
* Returns whether the SetToken component default position real unit is greater than or equal to units passed in.
*/
function hasSufficientDefaultUnits(ISetToken _setToken, address _component, uint256 _unit) internal view returns(bool) {
return _setToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256();
}
/**
* Returns whether the SetToken component external position is greater than or equal to the real units passed in.
*/
function hasSufficientExternalUnits(
ISetToken _setToken,
address _component,
address _positionModule,
uint256 _unit
)
internal
view
returns(bool)
{
return _setToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256();
}
/**
* If the position does not exist, create a new Position and add to the SetToken. If it already exists,
* then set the position units. If the new units is 0, remove the position. Handles adding/removing of
* components where needed (in light of potential external positions).
*
* @param _setToken Address of SetToken being modified
* @param _component Address of the component
* @param _newUnit Quantity of Position units - must be >= 0
*/
function editDefaultPosition(ISetToken _setToken, address _component, uint256 _newUnit) internal {
bool isPositionFound = hasDefaultPosition(_setToken, _component);
if (!isPositionFound && _newUnit > 0) {
// If there is no Default Position and no External Modules, then component does not exist
if (!hasExternalPosition(_setToken, _component)) {
_setToken.addComponent(_component);
}
} else if (isPositionFound && _newUnit == 0) {
// If there is a Default Position and no external positions, remove the component
if (!hasExternalPosition(_setToken, _component)) {
_setToken.removeComponent(_component);
}
}
_setToken.editDefaultPositionUnit(_component, _newUnit.toInt256());
}
/**
* Update an external position and remove and external positions or components if necessary. The logic flows as follows:
* 1) If component is not already added then add component and external position.
* 2) If component is added but no existing external position using the passed module exists then add the external position.
* 3) If the existing position is being added to then just update the unit and data
* 4) If the position is being closed and no other external positions or default positions are associated with the component
* then untrack the component and remove external position.
* 5) If the position is being closed and other existing positions still exist for the component then just remove the
* external position.
*
* @param _setToken SetToken being updated
* @param _component Component position being updated
* @param _module Module external position is associated with
* @param _newUnit Position units of new external position
* @param _data Arbitrary data associated with the position
*/
function editExternalPosition(
ISetToken _setToken,
address _component,
address _module,
int256 _newUnit,
bytes memory _data
)
internal
{
if (_newUnit != 0) {
if (!_setToken.isComponent(_component)) {
_setToken.addComponent(_component);
_setToken.addExternalPositionModule(_component, _module);
} else if (!_setToken.isExternalPositionModule(_component, _module)) {
_setToken.addExternalPositionModule(_component, _module);
}
_setToken.editExternalPositionUnit(_component, _module, _newUnit);
_setToken.editExternalPositionData(_component, _module, _data);
} else {
require(_data.length == 0, "Passed data must be null");
// If no default or external position remaining then remove component from components array
if (_setToken.getExternalPositionRealUnit(_component, _module) != 0) {
address[] memory positionModules = _setToken.getExternalPositionModules(_component);
if (_setToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) {
require(positionModules[0] == _module, "External positions must be 0 to remove component");
_setToken.removeComponent(_component);
}
_setToken.removeExternalPositionModule(_component, _module);
}
}
}
/**
* Get total notional amount of Default position
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _positionUnit Quantity of Position units
*
* @return Total notional amount of units
*/
function getDefaultTotalNotional(uint256 _setTokenSupply, uint256 _positionUnit) internal pure returns (uint256) {
return _setTokenSupply.preciseMul(_positionUnit);
}
/**
* Get position unit from total notional amount
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _totalNotional Total notional amount of component prior to
* @return Default position unit
*/
function getDefaultPositionUnit(uint256 _setTokenSupply, uint256 _totalNotional) internal pure returns (uint256) {
return _totalNotional.preciseDiv(_setTokenSupply);
}
/**
* Get the total tracked balance - total supply * position unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @return Notional tracked balance
*/
function getDefaultTrackedBalance(ISetToken _setToken, address _component) internal view returns(uint256) {
int256 positionUnit = _setToken.getDefaultPositionRealUnit(_component);
return _setToken.totalSupply().preciseMul(positionUnit.toUint256());
}
/**
* Calculates the new default position unit and performs the edit with the new unit
*
* @param _setToken Address of the SetToken
* @param _component Address of the component
* @param _setTotalSupply Current SetToken supply
* @param _componentPreviousBalance Pre-action component balance
* @return Current component balance
* @return Previous position unit
* @return New position unit
*/
function calculateAndEditDefaultPosition(
ISetToken _setToken,
address _component,
uint256 _setTotalSupply,
uint256 _componentPreviousBalance
)
internal
returns(uint256, uint256, uint256)
{
uint256 currentBalance = IERC20(_component).balanceOf(address(_setToken));
uint256 positionUnit = _setToken.getDefaultPositionRealUnit(_component).toUint256();
uint256 newTokenUnit;
if (currentBalance > 0) {
newTokenUnit = calculateDefaultEditPositionUnit(
_setTotalSupply,
_componentPreviousBalance,
currentBalance,
positionUnit
);
} else {
newTokenUnit = 0;
}
editDefaultPosition(_setToken, _component, newTokenUnit);
return (currentBalance, positionUnit, newTokenUnit);
}
/**
* Calculate the new position unit given total notional values pre and post executing an action that changes SetToken state
* The intention is to make updates to the units without accidentally picking up airdropped assets as well.
*
* @param _setTokenSupply Supply of SetToken in precise units (10^18)
* @param _preTotalNotional Total notional amount of component prior to executing action
* @param _postTotalNotional Total notional amount of component after the executing action
* @param _prePositionUnit Position unit of SetToken prior to executing action
* @return New position unit
*/
function calculateDefaultEditPositionUnit(
uint256 _setTokenSupply,
uint256 _preTotalNotional,
uint256 _postTotalNotional,
uint256 _prePositionUnit
)
internal
pure
returns (uint256)
{
// If pre action total notional amount is greater then subtract post action total notional and calculate new position units
uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_setTokenSupply));
return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_setTokenSupply);
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title PreciseUnitMath
* @author Set Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IController } from "../../interfaces/IController.sol";
import { IIntegrationRegistry } from "../../interfaces/IIntegrationRegistry.sol";
import { IPriceOracle } from "../../interfaces/IPriceOracle.sol";
import { ISetValuer } from "../../interfaces/ISetValuer.sol";
/**
* @title ResourceIdentifier
* @author Set Protocol
*
* A collection of utility functions to fetch information related to Resource contracts in the system
*/
library ResourceIdentifier {
// IntegrationRegistry will always be resource ID 0 in the system
uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0;
// PriceOracle will always be resource ID 1 in the system
uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1;
// SetValuer resource will always be resource ID 2 in the system
uint256 constant internal SET_VALUER_RESOURCE_ID = 2;
/* ============ Internal ============ */
/**
* Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on
* the Controller
*/
function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) {
return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID));
}
/**
* Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller
*/
function getPriceOracle(IController _controller) internal view returns (IPriceOracle) {
return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID));
}
/**
* Gets the instance of Set valuer on Controller. Note: SetValuer is stored as index 2 on the Controller
*/
function getSetValuer(IController _controller) internal view returns (ISetValuer) {
return ISetValuer(_controller.resourceId(SET_VALUER_RESOURCE_ID));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title ExplicitERC20
* @author Set Protocol
*
* Utility functions for ERC20 transfers that require the explicit amount to be transferred.
*/
library ExplicitERC20 {
using SafeMath for uint256;
/**
* When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity".
* Ensures that the recipient has received the correct quantity (ie no fees taken on transfer)
*
* @param _token ERC20 token to approve
* @param _from The account to transfer tokens from
* @param _to The account to transfer tokens to
* @param _quantity The quantity to transfer
*/
function transferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _quantity
)
internal
{
// Call specified ERC20 contract to transfer tokens (via proxy).
if (_quantity > 0) {
uint256 existingBalance = _token.balanceOf(_to);
SafeERC20.safeTransferFrom(
_token,
_from,
_to,
_quantity
);
uint256 newBalance = _token.balanceOf(_to);
// Verify transfer quantity is reflected in balance
require(
newBalance == existingBalance.add(_quantity),
"Invalid post transfer balance"
);
}
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title IModule
* @author Set Protocol
*
* Interface for interacting with Modules.
*/
interface IModule {
/**
* Called by a SetToken to notify that this module was removed from the Set token. Any logic can be included
* in case checks need to be made or state needs to be cleared.
*/
function removeModule() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
interface IIntegrationRegistry {
function addIntegration(address _module, string memory _id, address _wrapper) external;
function getIntegrationAdapter(address _module, string memory _id) external view returns(address);
function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address);
function isValidIntegration(address _module, string memory _id) external view returns(bool);
}
/*
Copyright 2020 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache License, Version 2.0
*/
pragma solidity 0.6.10;
/**
* @title IPriceOracle
* @author Set Protocol
*
* Interface for interacting with PriceOracle
*/
interface IPriceOracle {
/* ============ Functions ============ */
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256);
function masterQuoteAsset() external view returns (address);
}
|
Check that total supply is greater than min supply needed for issuance Note: A min supply amount is needed to avoid division by 0 when SetToken supply is 0
|
function _validateIssuanceInfo(ISetToken _setToken, uint256 _minSetTokenReceiveQuantity, ActionInfo memory _issueInfo) internal view {
require(
_issueInfo.previousSetTokenSupply >= navIssuanceSettings[_setToken].minSetTokenSupply,
"Supply must be greater than minimum to enable issuance"
);
require(_issueInfo.setTokenQuantity >= _minSetTokenReceiveQuantity, "Must be greater than min SetToken");
}
| 91,158
|
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.13;
// Imports
import "./Ownable.sol";
import "./ReentrancyGuard.sol";
import "./IERC20.sol";
import "./IERC721.sol";
// MOD Interface
interface MODToken {
function mint(address recipient, uint256 amount) external;
}
/// @title MOD - Staking Contract
contract NFTStaking is Ownable, ReentrancyGuard {
// Staker details
struct Staker {
uint256[] tokenIds;
uint256 currentYield;
uint256 numberOfTokensStaked;
uint256 lastCheckpoint;
}
uint256 public constant SECONDS_IN_DAY = 24 * 60 * 60;
IERC721 public immutable nftContract;
MODToken public immutable rewardToken;
bool public stakingLaunched;
mapping(address => Staker) public stakers;
uint256 public lowYieldEndBound = 4;
uint256 public mediumYieldEndBound = 9;
uint256 public highYieldStartBound = 10;
uint256 public lowYieldPerSecond;
uint256 public mediumYieldPerSecond;
uint256 public highYieldPerSecond;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
mapping(uint256 => address) private _ownerOfToken;
event Deposit(address indexed staker, uint256 amount);
event Withdraw(address indexed staker, uint256 amount);
event Claim(address indexed staker, uint256 tokenAmount);
/// @dev The contract constructor
constructor(
IERC721 _nftContract,
MODToken _rewardToken,
uint256 _lowYieldPerDay,
uint256 _mediumYieldPerDay,
uint256 _highYieldPerDay
) {
rewardToken = _rewardToken;
nftContract = _nftContract;
lowYieldPerSecond = _lowYieldPerDay / SECONDS_IN_DAY;
mediumYieldPerSecond = _mediumYieldPerDay / SECONDS_IN_DAY;
highYieldPerSecond = _highYieldPerDay / SECONDS_IN_DAY;
}
/**
* @param _lowYieldEndBound The upper bound of the lowest range that produces low yield
* @param _lowYieldPerDay The amount of tokens in Wei that a user earns for each token in the lowest range per day
* @param _mediumYieldEndBound The upper bound of the medium range that produces medium yield
* @param _mediumYieldPerDay The amount of tokens in Wei that a user earns for each token in the medium range per day
* @param _highYieldStartBound The lower bound of the highest range that produces high yield
* @param _highYieldPerDay The amount of tokens in Wei that a user earns for each token in the highest range per day
* @dev Sets yield parameters
*/
function setYieldParams(
uint256 _lowYieldEndBound,
uint256 _lowYieldPerDay,
uint256 _mediumYieldEndBound,
uint256 _mediumYieldPerDay,
uint256 _highYieldStartBound,
uint256 _highYieldPerDay
) external onlyOwner {
lowYieldEndBound = _lowYieldEndBound;
lowYieldPerSecond = _lowYieldPerDay / SECONDS_IN_DAY;
mediumYieldEndBound = _mediumYieldEndBound;
mediumYieldPerSecond = _mediumYieldPerDay / SECONDS_IN_DAY;
highYieldStartBound = _highYieldStartBound;
highYieldPerSecond = _highYieldPerDay / SECONDS_IN_DAY;
}
/**
* @param tokenIds The list of token IDs to stake
* @dev Stakes NFTs
*/
function deposit(uint256[] memory tokenIds) external nonReentrant {
require(stakingLaunched, "Staking is not launched yet");
Staker storage staker = stakers[_msgSender()];
if (staker.numberOfTokensStaked > 0) {
uint256 rewards = getUnclaimedRewards(_msgSender());
_claimReward(_msgSender(), rewards);
}
for (uint256 i; i < tokenIds.length; i++) {
require(nftContract.ownerOf(tokenIds[i]) == _msgSender(), "Not the owner");
nftContract.safeTransferFrom(_msgSender(), address(this), tokenIds[i]);
_ownerOfToken[tokenIds[i]] = _msgSender();
staker.tokenIds.push(tokenIds[i]);
staker.numberOfTokensStaked += 1;
}
staker.currentYield = getTotalYieldPerSecond(staker.numberOfTokensStaked);
staker.lastCheckpoint = block.timestamp;
emit Deposit(_msgSender(), tokenIds.length);
}
/**
* @param tokenIds The list of token IDs to unstake
* @dev Withdraws NFTs
*/
function withdraw(uint256[] memory tokenIds) external nonReentrant {
Staker storage staker = stakers[_msgSender()];
if (staker.numberOfTokensStaked > 0) {
uint256 rewards = getUnclaimedRewards(_msgSender());
_claimReward(_msgSender(), rewards);
}
for (uint256 i; i < tokenIds.length; i++) {
require(nftContract.ownerOf(tokenIds[i]) == address(this), "Invalid tokenIds provided");
require(_ownerOfToken[tokenIds[i]] == _msgSender(), "Not the owner of one ore more provided tokens");
_ownerOfToken[tokenIds[i]] = address(0);
staker.tokenIds = _moveTokenToLast(staker.tokenIds, tokenIds[i]);
staker.tokenIds.pop();
staker.numberOfTokensStaked -= 1;
nftContract.safeTransferFrom(address(this), _msgSender(), tokenIds[i]);
}
staker.currentYield = getTotalYieldPerSecond(staker.numberOfTokensStaked);
staker.lastCheckpoint = block.timestamp;
emit Withdraw(_msgSender(), tokenIds.length);
}
/// @dev Transfers reward to a user
function claimReward() external nonReentrant {
Staker storage staker = stakers[_msgSender()];
if (staker.numberOfTokensStaked > 0) {
uint256 rewards = getUnclaimedRewards(_msgSender());
_claimReward(_msgSender(), rewards);
}
staker.lastCheckpoint = block.timestamp;
}
/**
* @param tokenIds The list of token IDs to withdraw
* @dev Withdraws ERC721 in case of emergency
*/
function emergencyWithdraw(uint256[] memory tokenIds) external onlyOwner {
require(tokenIds.length <= 50, "50 is max per tx");
for (uint256 i; i < tokenIds.length; i++) {
address receiver = _ownerOfToken[tokenIds[i]];
if (receiver != address(0) && nftContract.ownerOf(tokenIds[i]) == address(this)) {
nftContract.transferFrom(address(this), receiver, tokenIds[i]);
}
}
}
/// @dev Starts NFT staking program
function launchStaking() external onlyOwner {
require(!stakingLaunched, "Staking has been launched already");
stakingLaunched = true;
}
/**
* @param balance The balance of a user
* @dev Gets total yield per second of all staked tokens of a user
*/
function getTotalYieldPerSecond(uint256 balance) public view returns (uint256) {
if (balance == 0) {
return 0;
}
if (balance <= lowYieldEndBound) {
return balance * lowYieldPerSecond;
} else if (balance <= mediumYieldEndBound) {
return lowYieldEndBound * lowYieldPerSecond + (balance - lowYieldEndBound) * mediumYieldPerSecond;
} else if (balance >= highYieldStartBound) {
uint256 lowYieldAmount = lowYieldEndBound;
uint256 mediumYieldAmount = mediumYieldEndBound - lowYieldEndBound;
uint256 highYieldAmount = balance - lowYieldAmount - mediumYieldAmount;
return lowYieldAmount * lowYieldPerSecond + mediumYieldAmount * mediumYieldPerSecond + highYieldAmount * highYieldPerSecond;
}
return 0;
}
/**
* @param staker The address of a user
* @dev Calculates unclaimed reward of a user
*/
function getUnclaimedRewards(address staker) public view returns (uint256) {
if (stakers[staker].lastCheckpoint == 0) {
return 0;
}
return (block.timestamp - stakers[staker].lastCheckpoint) * stakers[staker].currentYield;
}
/**
* @param staker The address of a user
* @dev Returns all token IDs staked by a user
*/
function getStakedTokens(address staker) public view returns (uint256[] memory) {
return stakers[staker].tokenIds;
}
/**
* @param staker The address of a user
* @dev Returns the number of tokens staked by a user
*/
function getTotalStakedAmount(address staker) public view returns (uint256) {
return stakers[staker].numberOfTokensStaked;
}
/// @dev Gets called whenever an IERC721 tokenId token is transferred to this contract via IERC721.safeTransferFrom
function onERC721Received(
address,
address,
uint256,
bytes calldata data
) public returns (bytes4) {
return _ERC721_RECEIVED;
}
/**
* @param list The array of token IDs
* @param tokenId The token ID to move to the end of the array
* @dev Moves the element that matches tokenId to the end of the array
*/
function _moveTokenToLast(uint256[] memory list, uint256 tokenId) internal pure returns (uint256[] memory) {
uint256 tokenIndex = 0;
uint256 lastTokenIndex = list.length - 1;
uint256 length = list.length;
for (uint256 i = 0; i < length; i++) {
if (list[i] == tokenId) {
tokenIndex = i + 1;
break;
}
}
require(tokenIndex != 0, "msg.sender is not the owner");
tokenIndex -= 1;
if (tokenIndex != lastTokenIndex) {
list[tokenIndex] = list[lastTokenIndex];
list[lastTokenIndex] = tokenId;
}
return list;
}
/**
* @param staker The user address
* @param amount The amount of tokens to claim
* @dev Transfers reward to a user
*/
function _claimReward(address staker, uint256 amount) private {
rewardToken.mint(staker, amount);
emit Claim(staker, amount);
}
}
|
balance The balance of a user Gets total yield per second of all staked tokens of a user/
|
function getTotalYieldPerSecond(uint256 balance) public view returns (uint256) {
if (balance == 0) {
return 0;
}
if (balance <= lowYieldEndBound) {
return balance * lowYieldPerSecond;
return lowYieldEndBound * lowYieldPerSecond + (balance - lowYieldEndBound) * mediumYieldPerSecond;
uint256 lowYieldAmount = lowYieldEndBound;
uint256 mediumYieldAmount = mediumYieldEndBound - lowYieldEndBound;
uint256 highYieldAmount = balance - lowYieldAmount - mediumYieldAmount;
return lowYieldAmount * lowYieldPerSecond + mediumYieldAmount * mediumYieldPerSecond + highYieldAmount * highYieldPerSecond;
}
return 0;
}
| 1,421,411
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./ERC721Enumerable.sol";
import "./CollaborativeOwnable.sol";
import "./ProxyRegistry.sol";
contract TheGauntlet is ERC721Enumerable, CollaborativeOwnable, ReentrancyGuard {
using SafeMath for uint256;
using Address for address;
using Strings for uint256;
uint256 public maxSupply = 5002;
string public baseURI = "";
address public proxyRegistryAddress = address(0);
uint256 public mintPrice = 30000000000000000;
uint256 public mintLimit = 10;
bool public mintIsActive = false;
uint256 public totalMinted = 0;
address public collaboratorWithdrawAddress = address(0);
uint256 public developerPercentage = 20;
bool public gauntletStarted = false;
uint256 public constant survivorCount = 10;
uint256 public constant survivorCutPercentage = 65;
uint256 public survivorCut = 0;
mapping(address => bool) private _claimed;
uint256 public unclaimedCount = 10;
uint256[] private _unburnedTokens; // token id
mapping(uint256 => uint256) private _unburnedTokensIndex; // token id to array position
uint256 public totalBurned = 0;
address public withdrawAddress0 = address(0);
address public withdrawAddress1 = address(0);
uint256 private randomSeed = 0;
constructor(address _proxyRegistryAddress, address _withdrawAddress0, address _withdrawAddress1) ERC721("The Gauntlet", "GAUNTLET") {
proxyRegistryAddress = _proxyRegistryAddress;
withdrawAddress0 = _withdrawAddress0;
withdrawAddress1 = _withdrawAddress1;
}
//
// Public / External
//
function mint(uint256 quantity) external payable nonReentrant {
require(mintIsActive, "inactive");
require(!gauntletStarted, "started");
require(quantity > 0, "quantity");
require(quantity <= mintLimit, "limit");
uint256 ts = totalSupply();
require((ts + quantity) <= maxSupply, "supply");
require(mintPrice.mul(quantity) <= msg.value, "value");
for (uint i = 0; i < quantity; i++) {
uint256 tokenId = ts + i;
_safeMint(_msgSender(), tokenId);
_addTokenToUnburnedEnumeration(tokenId);
}
totalMinted = totalMinted.add(quantity);
}
function claim() external nonReentrant {
require(totalSupply() == survivorCount, "incomplete");
uint256 balance = balanceOf(_msgSender());
require(balance > 0, "holder");
require(!_claimed[_msgSender()], "claimed");
uint256 cut = survivorCut.mul(balance);
_claimed[_msgSender()] = true;
unclaimedCount = unclaimedCount.sub(balance);
payable(_msgSender()).transfer(cut);
}
// Override ERC721
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
// Override ERC721
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "invalid token");
string memory __baseURI = _baseURI();
return bytes(__baseURI).length > 0 ? string(abi.encodePacked(__baseURI, tokenId.toString(), ".json")) : '.json';
}
// Override ERC721
function isApprovedForAll(address owner, address operator) override public view returns (bool) {
if (address(proxyRegistryAddress) != address(0)) {
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
}
return super.isApprovedForAll(owner, operator);
}
//
// Private
//
function _addTokenToUnburnedEnumeration(uint256 tokenId) private {
_unburnedTokensIndex[tokenId] = _unburnedTokens.length;
_unburnedTokens.push(tokenId);
}
function _removeTokenFromUnburnedEnumeration(uint256 tokenId) private {
uint256 lastTokenIndex = _unburnedTokens.length - 1;
uint256 tokenIndex = _unburnedTokensIndex[tokenId];
uint256 lastTokenId = _unburnedTokens[lastTokenIndex];
_unburnedTokens[tokenIndex] = lastTokenId;
_unburnedTokensIndex[lastTokenId] = tokenIndex;
delete _unburnedTokensIndex[tokenId];
_unburnedTokens.pop();
}
function _random() internal returns (uint256) {
uint256 randomNumber = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), _msgSender(), randomSeed)));
randomSeed = randomNumber;
return randomNumber;
}
function _getRandomTokenId() internal returns (uint256) {
uint256 randomIndex = _random() % _unburnedTokens.length;
return _unburnedTokens[randomIndex];
}
//
// Collaborator Access
//
function burn(uint256 newRandomSeed, uint256 quantity) external onlyCollaborator {
require((_unburnedTokens.length - quantity) >= survivorCount, "quantity");
require(newRandomSeed != 0, "zero");
randomSeed = newRandomSeed;
for (uint256 i = 0; i < quantity; i++) {
uint256 tokenId = _getRandomTokenId();
_burn(tokenId);
_removeTokenFromUnburnedEnumeration(tokenId);
totalBurned++;
}
}
function setBaseURI(string memory uri) external onlyCollaborator {
baseURI = uri;
}
function startGauntlet() external onlyCollaborator {
require(!gauntletStarted, "started");
mintIsActive = false;
gauntletStarted = true;
uint256 balance = address(this).balance;
survivorCut = balance.mul(survivorCutPercentage).div(1000);
}
function reduceMintPrice(uint256 newPrice) external onlyCollaborator {
require(newPrice >= 0 && newPrice < mintPrice);
mintPrice = newPrice;
}
function reduceMaxSupply(uint256 newMaxSupply) external onlyCollaborator {
require(newMaxSupply >= 0 && newMaxSupply < maxSupply);
require(newMaxSupply >= totalSupply());
require(!gauntletStarted);
maxSupply = newMaxSupply;
}
function setMintIsActive(bool active) external onlyCollaborator {
mintIsActive = active;
}
function setMintLimit(uint256 limit) external onlyCollaborator {
require(limit > 0, "limit");
mintLimit = limit;
}
function setProxyRegistryAddress(address prAddress) external onlyCollaborator {
proxyRegistryAddress = prAddress;
}
function withdraw() external onlyCollaborator nonReentrant {
require(gauntletStarted, "not started");
uint256 balance = address(this).balance;
uint256 reserved = survivorCut.mul(unclaimedCount);
require(balance > reserved, "reserved");
uint256 remaining = balance.sub(reserved);
require(balance > 0, "zero");
uint256 cut = remaining.div(2);
payable(withdrawAddress0).transfer(cut);
payable(withdrawAddress1).transfer(cut);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
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));
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());
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.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));
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));
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));
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);
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()));
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender());
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId));
_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));
_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));
}
/**
* @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));
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));
}
/**
* @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));
require(!_exists(tokenId));
_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);
require(to != address(0));
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("unsafe");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
abstract contract CollaborativeOwnable is Ownable {
using Address for address;
mapping(address => bool) private _collaborators;
uint256 private _collaboratorCount;
constructor() {
}
function isCollaborator(address collaboratorAddress) public view virtual returns (bool) {
return _collaborators[collaboratorAddress];
}
modifier onlyCollaborator() {
require(owner() == _msgSender() || _collaborators[_msgSender()], "CO1");
_;
}
function addCollaborator(address collaboratorAddress) public onlyCollaborator {
require(collaboratorAddress != address(0), "CO2");
require(!_collaborators[collaboratorAddress], "CO3");
_collaborators[collaboratorAddress] = true;
_collaboratorCount++;
}
function removeCollaborator(address collaboratorAddress) public onlyCollaborator {
require(collaboratorAddress != address(0), "CO4");
require(_collaborators[collaboratorAddress], "CO4");
require(_collaboratorCount > 1, "CO4");
_collaborators[collaboratorAddress] = false;
_collaboratorCount--;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
|
Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. The call is not executed if the target address is not a contract. from address representing the previous owner of the given token ID to target address that will receive the tokens tokenId uint256 ID of the token to be transferred _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;
if (reason.length == 0) {
revert("unsafe");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
| 1,582,382
|
./partial_match/1/0x20d3613ce72EA75dcB16C09b7e82002C090dC434/sources/CHUCKY.sol
|
generate the uniswap pair path of token -> weth make the swap
|
function swapTokensForETH(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = ROUTER.WETH();
_approve(address(this), address(ROUTER), tokenAmount);
ROUTER.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
| 2,632,923
|
./full_match/4/0xC209E294664C8Cb5B55EbF1CAE6CaCCd024Cb822/sources/contracts/ERC721A.sol
|
See {IERC721-ownerOf}./
|
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return address(uint160(_packedOwnershipOf(tokenId)));
}
| 727,651
|
./full_match/1/0x16089279eFBAC25b174686E60F89a5f8fd5fB8a6/sources/browser/FoldingOnAnchor.sol
|
Gets a flash loan from flashLoaner passing dataToExecuteOn. This data will be used inside the call to proxyUseFlashLoan (below) Set the flashLoaner we want to use for this flash loan request
|
function getFlashLoan(
address flashLoaner,
address tokenToLoan,
uint256 flashLoanAmount,
bytes memory dataToExecuteOn
) internal {
require(flashLoanAmount > 0, "PFL: amount is 0");
require(approvedFlashLoaners[flashLoaner], "PFL: FlashLoaner not approved");
targetFlashLoaner = flashLoaner;
(bool success, bytes memory returnData) = flashLoaner.delegatecall(abi.encodeWithSignature(
"getFlashLoan(address,address,uint256,bytes)",
address(this), tokenToLoan, flashLoanAmount, dataToExecuteOn
));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize())
}
}
}
| 4,994,460
|
./full_match/40/0xe231B919963c1cA0968FaC88e5B1Fdd87B38B4F3/sources/contracts/ZappyUsdcTlos.sol
|
Determines the amount of reward in wTLOS upon calling the harvest function
|
function callReward() public view returns (uint256) {
uint256 outputBal = rewardBalance();
uint256 wrappedOut;
if (outputBal > 0) {
uint256[] memory amountsOut = IUniSwapRouter(router).getAmountsOut(outputBal, outputToWrappedPath);
wrappedOut = amountsOut[amountsOut.length -1];
}
return wrappedOut * PLATFORM_FEE / FEE_DIVISOR * CALL_FEE / FEE_DIVISOR;
}
| 9,543,217
|
/**
*Submitted for verification at Etherscan.io on 2020-07-05
*/
/*
___________________________________________________________________
_ _ ______
| | / / /
--|-/|-/-----__---/----__----__---_--_----__-------/-------__------
|/ |/ /___) / / ' / ) / / ) /___) / / )
__/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_
1111111 1111111 1111111 111111 111
11111111111111111 1111111111111111111
111 11111111111 1111111111111111111
11111 11111111111 1111111 11111111111
111111111111 111 111 111 11111111111
1111111 111 111 111 111 11111111111
-------------------------------------------------------------------
Copyright (c) 2020 onwards QR PAL Inc. ( https://qrpal.money )
-------------------------------------------------------------------
*/
pragma solidity 0.5.16;
// Owner Handler
contract ownerShip // Auction Contract Owner and OwherShip change
{
//Global storage declaration
address internal ownerWallet;
address internal newOwner;
//Event defined for ownership transfered
event OwnershipTransferredEv(address indexed previousOwner, address indexed newOwner);
//Sets owner only on first run
constructor() public
{
//Set contract owner
ownerWallet = msg.sender;
emit OwnershipTransferredEv(address(0), msg.sender);
}
function transferOwnership(address _newOwner) external onlyOwner
{
newOwner = _newOwner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
//the reason for this flow is to protect owners from sending ownership to unintended address due to human error
function acceptOwnership() external
{
require(msg.sender == newOwner); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit OwnershipTransferredEv(ownerWallet, newOwner); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
ownerWallet = newOwner; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
newOwner = address(0); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
//This will restrict function only for owner where attached
modifier onlyOwner()
{
require(msg.sender == ownerWallet);
_;
}
}
interface usdtInterface
{
function transfer(address _to, uint256 _amount) external returns (bool);
function transferFrom(address _from, address _to, uint256 _amount) external returns (bool);
}
interface multiadminInterface
{
function payamount(uint256 _amount) external;
}
contract QRPal is ownerShip {
//public variables
uint internal maxDownLimit = 2;
uint internal levelLifeTime = 8640000; // = 100 days;
uint internal lastIDCount = 0;
address internal usdtTokenAddress;
struct userInfo {
bool joined;
uint id;
uint referrerID;
address[] referral;
mapping(uint => uint) levelExpired;
}
mapping(uint => uint) internal priceOfLevel;
mapping (address => userInfo) internal userInfos;
mapping (uint => address) internal userAddressByID;
address internal multiadminaddress;
//events
event regLevelEv(uint indexed _userID, address indexed _userWallet, uint indexed _referrerID, address _refererWallet, uint _originalReferrer, uint _time);
event levelBuyEv(address indexed _user, uint _level, uint _amount, uint _time);
event paidForLevelEv(address indexed _user, address indexed _referral, uint _level, uint _amount, uint _time);
event lostForLevelEv(address indexed _user, address indexed _referral, uint _level, uint _amount, uint _time);
/**
* constructor makes all the levels upgraded of ID 1 - owner
*/
constructor(address _usdtTokenAddress, address _multiadminAddress) public {
require(_usdtTokenAddress!=address(0));
require(_multiadminAddress!=address(0));
usdtTokenAddress = _usdtTokenAddress;
multiadminaddress=_multiadminAddress;
priceOfLevel[1] = 20*(10**6);//usdt
priceOfLevel[2] = 30*(10**6);//usdt
priceOfLevel[3] = 60*(10**6);//usdt
priceOfLevel[4] = 180*(10**6);//usdt
priceOfLevel[5] = 880*(10**6);//usdt
priceOfLevel[6] = 6160*(10**6);//usdt
priceOfLevel[7] = 8320*(10**6);//usdt
priceOfLevel[8] = 13280*(10**6);//usdt
priceOfLevel[9] = 16240*(10**6);//usdt
priceOfLevel[10] = 29640*(10**6);//usdt
userInfo memory UserInfo;
lastIDCount++;
UserInfo = userInfo({
joined: true,
id: lastIDCount,
referrerID: 0,
referral: new address[](0)
});
userInfos[multiadminaddress] = UserInfo;
userAddressByID[lastIDCount] = multiadminaddress;
for(uint i = 1; i <= 10; i++) {
userInfos[multiadminaddress].levelExpired[i] = 99999999999;
emit paidForLevelEv(multiadminaddress, address(0), i, priceOfLevel[i], now);
}
emit regLevelEv(lastIDCount, multiadminaddress, 0, address(0), 0, now);
}
/**
* no incoming ether, as all process happening in USDT
*/
function () external payable {
revert();
}
/**
* This function register the user in the system. He has to provide referrer ID.
* User should have USDT balance as well approval of this smart contract in order for this function to work.
*/
function regUser(uint _referrerID) external {
uint originalReferrerID = _referrerID;
require(!userInfos[msg.sender].joined, 'User exist'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(_referrerID > 0 && _referrerID <= lastIDCount, 'Incorrect referrer Id'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
//require(msg.value == priceOfLevel[1], 'Incorrect Value');
if(userInfos[userAddressByID[_referrerID]].referral.length >= maxDownLimit) _referrerID = userInfos[findFreeReferrer(userAddressByID[_referrerID])].id; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
userInfo memory UserInfo;
lastIDCount++; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
UserInfo = userInfo({
joined: true,
id: lastIDCount, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
referrerID: _referrerID,
referral: new address[](0)
});
userInfos[msg.sender] = UserInfo; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
userAddressByID[lastIDCount] = msg.sender; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
userInfos[msg.sender].levelExpired[1] = now + levelLifeTime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
userInfos[userAddressByID[_referrerID]].referral.push(msg.sender); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
payForLevel(1, msg.sender);
emit regLevelEv(lastIDCount, msg.sender, _referrerID, userAddressByID[_referrerID], originalReferrerID, now); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit levelBuyEv(msg.sender, 1, priceOfLevel[1], now); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* This function to buy any level. User has to specify level number to buy it.
* User should have USDT balance as well approval of this smart contract in order for this function to work.
*/
function buyLevel(uint _level) external returns(bool) {
require(userInfos[msg.sender].joined, 'User not exist'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(_level > 0 && _level <= 10, 'Incorrect level');
//owner can buy levels without paying anything
if(msg.sender!=ownerWallet){ //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
//require(amount == priceOfLevel[_level], 'Incorrect Value');
//require(usdtInterface(usdtTokenAddress).transferFrom(msg.sender,address(this), priceOfLevel[_level]),"usdt transfer fail");
}
if(_level == 1) {
userInfos[msg.sender].levelExpired[1] += levelLifeTime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
else {
for(uint l =_level - 1; l > 0; l--) require(userInfos[msg.sender].levelExpired[l] >= now, 'Buy the previous level'); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if(userInfos[msg.sender].levelExpired[_level] == 0) userInfos[msg.sender].levelExpired[_level] = now + levelLifeTime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
else userInfos[msg.sender].levelExpired[_level] += levelLifeTime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
payForLevel(_level, msg.sender);
emit levelBuyEv(msg.sender, _level, priceOfLevel[_level], now); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
return true;
}
/**
* Internal function to which distributes fund.
*/
function payForLevel(uint _level, address _user) internal {
address referer;
address referer1;
address referer2;
address referer3;
address referer4;
if(_level == 1 || _level == 6) {
referer = userAddressByID[userInfos[_user].referrerID];
}
else if(_level == 2 || _level == 7) {
referer1 = userAddressByID[userInfos[_user].referrerID];
referer = userAddressByID[userInfos[referer1].referrerID];
}
else if(_level == 3 || _level == 8) {
referer1 = userAddressByID[userInfos[_user].referrerID];
referer2 = userAddressByID[userInfos[referer1].referrerID];
referer = userAddressByID[userInfos[referer2].referrerID];
}
else if(_level == 4 || _level == 9) {
referer1 = userAddressByID[userInfos[_user].referrerID];
referer2 = userAddressByID[userInfos[referer1].referrerID];
referer3 = userAddressByID[userInfos[referer2].referrerID];
referer = userAddressByID[userInfos[referer3].referrerID];
}
else if(_level == 5 || _level == 10) {
referer1 = userAddressByID[userInfos[_user].referrerID];
referer2 = userAddressByID[userInfos[referer1].referrerID];
referer3 = userAddressByID[userInfos[referer2].referrerID];
referer4 = userAddressByID[userInfos[referer3].referrerID];
referer = userAddressByID[userInfos[referer4].referrerID];
}
if(!userInfos[referer].joined) referer = userAddressByID[1];
bool sent = false;
if(userInfos[referer].levelExpired[_level] >= now) {
//sent = address(uint160(referer)).transfer(priceOfLevel[_level]);
if(referer==multiadminaddress)
{
referer=ownerWallet;
}
sent = usdtInterface(usdtTokenAddress).transferFrom(msg.sender,referer, priceOfLevel[_level]);
if (sent) {
emit paidForLevelEv(referer, msg.sender, _level, priceOfLevel[_level], now);
}
}
if(!sent) {
emit lostForLevelEv(referer, msg.sender, _level, priceOfLevel[_level], now);
if(userAddressByID[userInfos[referer].referrerID]==multiadminaddress)
{
multiadminInterface(multiadminaddress).payamount(priceOfLevel[_level]);
usdtInterface(usdtTokenAddress).transferFrom(msg.sender,multiadminaddress, priceOfLevel[_level]);
emit paidForLevelEv(multiadminaddress, msg.sender, _level, priceOfLevel[_level], now);
}
else
{
payForLevel(_level, referer);
}
}
}
/**
* Find available free referrer in the matrix. It search maximum 126 positions.
* For any chances where matrix goes beyond 126 position, then UI should supply correct referrer ID, to avoid hitting this limit.
*/
function findFreeReferrer(address _user) public view returns(address) {
if(userInfos[_user].referral.length < maxDownLimit) return _user; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
address[] memory referrals = new address[](126);
referrals[0] = userInfos[_user].referral[0]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
referrals[1] = userInfos[_user].referral[1]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
address freeReferrer;
bool noFreeReferrer = true;
for(uint i = 0; i < 126; i++) {
if(userInfos[referrals[i]].referral.length == maxDownLimit) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if(i < 62) {
referrals[(i+1)*2] = userInfos[referrals[i]].referral[0]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
referrals[(i+1)*2+1] = userInfos[referrals[i]].referral[1]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
else {
noFreeReferrer = false;
freeReferrer = referrals[i];
break;
}
}
require(!noFreeReferrer, 'No Free Referrer');
return freeReferrer;
}
/**
* Owner can set/change USDT contract address.
* Owner can set 0x0 address to pause this network. Owner can set correct USDT address and it should start working again.
* This contract does not hold any fund, so no scam is every possible.
*/
function changeUSDTaddress(address _add) external onlyOwner{
usdtTokenAddress=_add; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* View function to see referrals of user.
*/
function viewUserReferral(address _user) external view returns(address[] memory) {
return userInfos[_user].referral; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* See user's level expire.
*/
function viewUserLevelExpired(address _user, uint _level) external view returns(uint) {
return userInfos[_user].levelExpired[_level]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* assembly function which converts buytes to address.
*/
function bytesToAddress(bytes memory bys) private pure returns (address addr) {
assembly {
addr := mload(add(bys, 20))
}
}
/**
* output the array of timestamp of user last joined. This is used to see the expiration of all the levels.
*/
function viewTimestampSinceJoined(address usr) external view returns(uint256[10] memory timeSinceJoined )
{
if(userInfos[usr].joined) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
{
for(uint256 i=0;i<10;i++)
{
uint256 t = userInfos[usr].levelExpired[i+1]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if(t>now)
{
timeSinceJoined[i] = (t-now);
}
}
}
return timeSinceJoined;
}
function changeMultiadminAddress(address _add) public onlyOwner{
require(_add!=address(0));
multiadminaddress=_add; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
|
assembly function which converts buytes to address./
|
function bytesToAddress(bytes memory bys) private pure returns (address addr) {
assembly {
addr := mload(add(bys, 20))
}
}
| 13,074,648
|
./full_match/1/0x66600c4f55527C410D4067b21474c0fa1fe1331D/sources/contracts/Collection.sol
|
@inheritdoc IERC2981 Resolve royalty info from the engine powering the sequence.
|
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount)
{
IEngine engine = sequences[_tokenData[tokenId].sequenceId].engine;
return engine.getRoyaltyInfo(address(this), tokenId, salePrice);
}
| 4,932,330
|
pragma solidity >=0.4.22 <0.7.0;
import "./HashBaseCon.sol";
/**
* This contract will take charge of submitting file hash to blockchain
*
*/
contract DRCFileHashCon is DRCHashBase {
struct FileInfo {
string fileName; // must have a value
string fileUrl; // could be empty
string author; // could be empty
}
mapping(string => FileInfo) private fileHashInfo;
event LogInsertFileHash(
address indexed _operator,
string _hash, string _fileName,
string fileUrl,
bool _bool
);
event LogDeleteFileHash(
address indexed _operator,
string _hash,
string _fileName,
string fileUrl,
bool _bool
);
/**
* @dev Constructor,not used just reserved
*/
constructor() public {
}
/**
* @dev insertHash,insert hash into contract
* @param _hash is input value of hash
* @param _uploadedData is the additional data being uploaded to the contract
* @return bool,true is successful and false is failed
*/
function insertHash(string memory _hash, bytes memory _uploadedData)
public
onlyOwner
returns (bool)
{
require(!_hash.equal(""));
(string memory _saverName, string memory _fileName, string memory _fileUrl, string memory _author)
= abi.decode(_uploadedData, (string, string, string, string));
bool res = hashInfoLib.insertHash(_hash, _saverName);
require(res);
fileHashInfo[_hash] = FileInfo(_fileName, _fileUrl, _author);
emit LogInsertFileHash(
msg.sender,
_hash,
fileHashInfo[_hash].fileName,
fileHashInfo[_hash].fileUrl,
res
);
return true;
}
/**
* @dev selectHash,select hash from contract
* @param _hash is input value of hash
* @return true/false,saver,save time
*/
function selectHash(string memory _hash)
public
view
returns (bool, address, bytes memory, uint256, string memory)
{
bool selectRes;
HashOperateLib.ExInfo memory exInfo;
(selectRes, exInfo.saver, exInfo.saverName, exInfo.saveTime) = hashInfoLib.selectHash(_hash);
string memory selectTxHash = getTxIdByHash(_hash);
bytes memory selectData = abi.encodePacked(
exInfo.saverName,
fileHashInfo[_hash].fileName,
fileHashInfo[_hash].fileUrl,
fileHashInfo[_hash].author
);
return (
selectRes,
exInfo.saver,
selectData,
exInfo.saveTime,
selectTxHash
);
}
/**
* @dev deleteHash,delete hash into contract
* @param _hash is input value of hash
* @return bool,true is successful and false is failed
*/
function deleteHash(string memory _hash) public onlyOwner returns (bool) {
bool res = hashInfoLib.deleteHash(_hash);
if (res)
delete fileHashInfo[_hash];
emit LogDeleteFileHash(
msg.sender,
_hash,
fileHashInfo[_hash].fileName,
fileHashInfo[_hash].fileUrl,
res
);
return res;
}
}
|
selectHash,select hash from contract _hash is input value of hash return true/false,saver,save time/
|
function selectHash(string memory _hash)
public
view
returns (bool, address, bytes memory, uint256, string memory)
{
bool selectRes;
HashOperateLib.ExInfo memory exInfo;
(selectRes, exInfo.saver, exInfo.saverName, exInfo.saveTime) = hashInfoLib.selectHash(_hash);
string memory selectTxHash = getTxIdByHash(_hash);
bytes memory selectData = abi.encodePacked(
exInfo.saverName,
fileHashInfo[_hash].fileName,
fileHashInfo[_hash].fileUrl,
fileHashInfo[_hash].author
);
return (
selectRes,
exInfo.saver,
selectData,
exInfo.saveTime,
selectTxHash
);
}
| 12,830,199
|
//SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
/*
* @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 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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/math/SafeMath.sol
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, 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/Counters.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: @openzeppelin/contracts/introspection/IERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor() 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
override
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index)
private
view
returns (bytes32)
{
require(
set._values.length > index,
"EnumerableSet: index out of bounds"
);
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value)
internal
returns (bool)
{
return _add(set._inner, bytes32(uint256(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/utils/EnumerableMap.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map._entries.push(MapEntry({_key: key, _value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key)
private
view
returns (bool)
{
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(
map._entries.length > index,
"EnumerableMap: index out of bounds"
);
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map)
internal
view
returns (uint256)
{
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index)
internal
view
returns (uint256, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key)
internal
view
returns (address)
{
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
return string(buffer);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
uint256 private _totalSupply;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 totalSupply_
) public {
_name = name_;
_symbol = symbol_;
_totalSupply = totalSupply_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return
_tokenOwners.get(
tokenId,
"ERC721: owner query for nonexistent token"
);
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
// If there is no base URI, return the token URI.
string memory _tokenURI = _tokenURIs[tokenId];
if (bytes(_baseURI).length == 0 && bytes(_tokenURI).length == 0) {
return "ipfs://QmdSBxcU7c64uRTZS59mEzi6mtQ7eZ38WYtHpnuzz4Mie5";
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return _tokenURI;
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString(), ".json"));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _totalSupply;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
pragma solidity ^0.6.0;
contract JCN is ERC721, Ownable {
uint16 private constant mMax = 500;
uint16 private constant mMintLimit = 2;
uint256 private constant mPriceW = 0.1 ether;
uint256 private constant mPrice = 0.18 ether;
uint256 private mStartTime = 0;
uint256 private mWhiteCount = 0;
uint256 private mMintCount = 0;
mapping(address => bool) private mWhites;
mapping(address => uint8) private mHolders;
struct Tiger {
uint256 dna;
}
Tiger[] public mTigers;
function _cread() internal virtual returns (uint256) {
uint256 dna = _generateRandom();
dna = (dna * (mMintCount + 1)) % 10000000000;
mTigers.push(Tiger(dna));
uint256 tokenid = mTigers.length - 1;
return tokenid;
}
function _generateRandom() private view returns (uint256) {
return
uint256(
keccak256(
abi.encodePacked(
(block.timestamp)
.add(block.difficulty)
.add(
(
uint256(
keccak256(
abi.encodePacked(block.coinbase)
)
)
) / (now)
)
.add(block.gaslimit)
.add(
(
uint256(
keccak256(abi.encodePacked(msg.sender))
)
) / (now)
)
.add(block.number)
)
)
) % 1000000000000000000;
}
constructor() public ERC721("JI Capital NFTs", "JI", mMax) {
//_setBaseURI("ipfs://");
}
modifier isMax() {
require(mMintCount < mMax, "mint: End of sale");
require(block.timestamp >= mStartTime, "mint: no start");
require(mHolders[_msgSender()] < mMintLimit, "ERC721: MAX");
_;
}
function mint() public payable isMax {
require(mMintCount + mWhiteCount < mMax, "mint: End of public sale");
require(msg.value >= mPrice, "mint: amount < price");
_mint1();
}
function mintW() public payable isMax {
require(mWhites[_msgSender()], "mint: no white");
require(msg.value >= mPriceW, "mint: amount < price");
mWhites[_msgSender()] = false;
mWhiteCount = mWhiteCount.sub(1);
_mint1();
}
function _mint1() private {
mMintCount++;
mHolders[_msgSender()]++;
uint256 tokenid = _cread();
_mint(_msgSender(), tokenid);
}
function setWhite(address[] memory _args, bool _bool) public onlyOwner {
for (uint16 i = 0; i < _args.length; i++) {
mWhites[_args[i]] = _bool;
}
_bool
? mWhiteCount = mWhiteCount.add(_args.length)
: mWhiteCount = mWhiteCount.sub(_args.length);
}
function setTime(uint256 _day) public onlyOwner {
mStartTime = _day;
}
function setBaseURI(string memory _baseURI) public onlyOwner {
_setBaseURI(_baseURI);
}
function setTokenURIs(uint16[] memory _tokenid, string[] memory _url)
public
onlyOwner
{
require(_tokenid.length == _url.length, "ERC721: parameter exception");
for (uint16 i = 0; i < _tokenid.length; i++) {
_setTokenURI(_tokenid[i], _url[i]);
}
}
function withdraw() public onlyOwner {
address to = owner();
(bool success, ) = to.call{value: address(this).balance}(new bytes(0));
require(success, "TransferHelper: ETH_TRANSFER_FAILED");
}
function getInfo()
public
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
return (mMintCount, mStartTime, mWhiteCount, block.timestamp);
}
}
|
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)));
}
| 61,501
|
./partial_match/56/0x6997eDB5b5c7BCe3f1B30B3fcf3e94B301Bf33A7/sources/ClientRaindrop.sol
|
Copies a slice to a new string. 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;
memcpy(retptr, self._ptr, self._len);
return ret;
}
| 11,152,643
|
./full_match/1/0xa49102f00c7d76C725235563A65aF4eb7507d0a3/sources/contracts/presale-pool/PreSaleFactory.sol
|
Get the number of all created pools return Return number of created pools/
|
function allPoolsLength() public view returns (uint256) {
return allPools.length;
}
| 3,219,677
|
/**
*Submitted for verification at Etherscan.io on 2021-06-14
*/
// hevm: flattened sources of src/UniswapV3ConverterMedianizer.sol
pragma solidity =0.6.7 >=0.4.0 >=0.5.0;
////// lib/geb-treasury-reimbursement/src/math/GebMath.sol
/* pragma solidity 0.6.7; */
contract GebMath {
uint256 public constant RAY = 10 ** 27;
uint256 public constant WAD = 10 ** 18;
function ray(uint x) public pure returns (uint z) {
z = multiply(x, 10 ** 9);
}
function rad(uint x) public pure returns (uint z) {
z = multiply(x, 10 ** 27);
}
function minimum(uint x, uint y) public pure returns (uint z) {
z = (x <= y) ? x : y;
}
function addition(uint x, uint y) public pure returns (uint z) {
z = x + y;
require(z >= x, "uint-uint-add-overflow");
}
function subtract(uint x, uint y) public pure returns (uint z) {
z = x - y;
require(z <= x, "uint-uint-sub-underflow");
}
function multiply(uint x, uint y) public pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "uint-uint-mul-overflow");
}
function rmultiply(uint x, uint y) public pure returns (uint z) {
z = multiply(x, y) / RAY;
}
function rdivide(uint x, uint y) public pure returns (uint z) {
z = multiply(x, RAY) / y;
}
function wdivide(uint x, uint y) public pure returns (uint z) {
z = multiply(x, WAD) / y;
}
function wmultiply(uint x, uint y) public pure returns (uint z) {
z = multiply(x, y) / WAD;
}
function rpower(uint x, uint n, uint base) public pure returns (uint z) {
assembly {
switch x case 0 {switch n case 0 {z := base} default {z := 0}}
default {
switch mod(n, 2) case 0 { z := base } default { z := x }
let half := div(base, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, base)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, base)
}
}
}
}
}
}
////// src/univ3/interfaces/IUniswapV3Factory.sol
/* pragma solidity >=0.5.0; */
/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
/// @notice Emitted when the owner of the factory is changed
/// @param oldOwner The owner before the owner was changed
/// @param newOwner The owner after the owner was changed
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param pool The address of the created pool
event PoolCreated(
address indexed token0,
address indexed token1,
uint24 indexed fee,
int24 tickSpacing,
address pool
);
/// @notice Emitted when a new fee amount is enabled for pool creation via the factory
/// @param fee The enabled fee, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via setOwner
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
/// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
/// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
/// @return The tick spacing
function feeAmountTickSpacing(uint24 fee) external view returns (int24);
/// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The pool address
function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
/// @notice Creates a pool for the given two tokens and fee
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param fee The desired fee for the pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
/// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
/// are invalid.
/// @return pool The address of the newly created pool
function createPool(
address tokenA,
address tokenB,
uint24 fee
) external returns (address pool);
/// @notice Updates the owner of the factory
/// @dev Must be called by the current owner
/// @param _owner The new owner of the factory
function setOwner(address _owner) external;
/// @notice Enables a fee amount with the given tickSpacing
/// @dev Fee amounts may never be removed once enabled
/// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
/// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
////// src/univ3/interfaces/pool/IUniswapV3PoolActions.sol
/* pragma solidity >=0.5.0; */
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. (0 - uint128(1)). Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
////// src/univ3/interfaces/pool/IUniswapV3PoolDerivedState.sol
/* pragma solidity >=0.5.0; */
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns a relative timestamp value representing how long, in seconds, the pool has spent between
/// tickLower and tickUpper
/// @dev This timestamp is strictly relative. To get a useful elapsed time (i.e., duration) value, the value returned
/// by this method should be checkpointed externally after a position is minted, and again before a position is
/// burned. Thus the external contract must control the lifecycle of the position.
/// @param tickLower The lower tick of the range for which to get the seconds inside
/// @param tickUpper The upper tick of the range for which to get the seconds inside
/// @return A relative timestamp for how long the pool spent in the tick range
function secondsInside(int24 tickLower, int24 tickUpper) external view returns (uint32);
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return liquidityCumulatives Cumulative liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory liquidityCumulatives);
}
////// src/univ3/interfaces/pool/IUniswapV3PoolEvents.sol
/* pragma solidity >=0.5.0; */
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
////// src/univ3/interfaces/pool/IUniswapV3PoolImmutables.sol
/* pragma solidity >=0.5.0; */
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
////// src/univ3/interfaces/pool/IUniswapV3PoolOwnerActions.sol
/* pragma solidity >=0.5.0; */
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
////// src/univ3/interfaces/pool/IUniswapV3PoolState.sol
/* pragma solidity >=0.5.0; */
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// feeGrowthOutsideX128 values can only be used if the tick is initialized,
/// i.e. if liquidityGross is greater than 0. In addition, these values are only relative and are used to
/// compute snapshots.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns 8 packed tick seconds outside values. See SecondsOutside for more information
function secondsOutside(int24 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the current tick multiplied by seconds elapsed for the life of the pool as of the
/// observation,
/// Returns liquidityCumulative the current liquidity multiplied by seconds elapsed for the life of the pool as of
/// the observation,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 liquidityCumulative,
bool initialized
);
}
////// src/univ3/interfaces/IUniswapV3Pool.sol
/* pragma solidity >=0.5.0; */
/* import './pool/IUniswapV3PoolImmutables.sol'; */
/* import './pool/IUniswapV3PoolState.sol'; */
/* import './pool/IUniswapV3PoolDerivedState.sol'; */
/* import './pool/IUniswapV3PoolActions.sol'; */
/* import './pool/IUniswapV3PoolOwnerActions.sol'; */
/* import './pool/IUniswapV3PoolEvents.sol'; */
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
////// src/univ3/libraries/FullMath.sol
/* pragma solidity >=0.4.0; */
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < (0 - uint256(1)));
result++;
}
}
}
////// src/univ3/libraries/TickMath.sol
/* pragma solidity >=0.5.0; */
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = (0 - uint256(1)) / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R");
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
////// src/UniswapV3ConverterMedianizer.sol
/* pragma solidity 0.6.7; */
/* import "geb-treasury-reimbursement/math/GebMath.sol"; */
/* import './univ3/interfaces/IUniswapV3Factory.sol'; */
/* import './univ3/interfaces/IUniswapV3Pool.sol'; */
/* import './univ3/libraries/TickMath.sol'; */
/* import './univ3/libraries/FullMath.sol'; */
abstract contract ConverterFeedLike_3 {
function getResultWithValidity() virtual external view returns (uint256,bool);
function updateResult(address) virtual external;
}
abstract contract IncreasingRewardRelayerLike_3 {
function reimburseCaller(address) virtual external;
}
contract UniswapV3ConverterMedianizer is GebMath {
// --- Auth ---
mapping (address => uint) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "UniswapV3ConverterMedianizer/account-not-authorized");
_;
}
// --- Observations ---
struct ConverterFeedObservation {
uint timestamp;
uint timeAdjustedPrice;
}
// --- Uniswap Vars ---
// Default amount of targetToken used when calculating the denominationToken output
uint256 public defaultAmountIn;
// Token for which the contract calculates the medianPrice for
address public targetToken;
// Pair token from the Uniswap pair
address public denominationToken;
// The pool to read price data from
IUniswapV3Pool public uniswapPool;
// --- Converter Feed Vars ---
// Latest converter price accumulator snapshot
uint256 public converterPriceCumulative;
ConverterFeedLike_3 public converterFeed;
ConverterFeedObservation[] public converterFeedObservations;
// --- General Vars ---
// Symbol - you want to change this every deployment
bytes32 public symbol = "raiusd";
/**
The number of observations stored for the pair, i.e. how many price observations are stored for the window.
as granularity increases from 1, more frequent updates are needed, but moving averages become more precise.
averages are computed over intervals with sizes in the range:
[windowSize - (windowSize / granularity) * 2, windowSize]
e.g. if the window size is 24 hours, and the granularity is 24, the oracle will return the average price for
the period:
[now - [22 hours, 24 hours], now]
**/
uint8 public granularity;
// When the price feed was last updated
uint256 public lastUpdateTime;
// Total number of updates
uint256 public updates;
// The desired amount of time over which the moving average should be computed, e.g. 24 hours
uint32 public windowSize;
// Maximum window size used to determine if the median is 'valid' (close to the real one) or not
uint256 public maxWindowSize;
// This is redundant with granularity and windowSize, but stored for gas savings & informational purposes.
uint256 public periodSize;
// This is the denominator for computing
uint256 public converterFeedScalingFactor;
// The last computed median price
uint256 private medianPrice;
// Manual flag that can be set by governance and indicates if a result is valid or not
uint256 public validityFlag;
// Contract relaying the SF reward to addresses that update this oracle
IncreasingRewardRelayerLike_3 public relayer;
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event ModifyParameters(
bytes32 parameter,
address addr
);
event ModifyParameters(
bytes32 parameter,
uint256 val
);
event UpdateResult(uint256 medianPrice, uint256 lastUpdateTime);
event FailedConverterFeedUpdate(bytes reason);
event FailedUniswapPairSync(bytes reason);
constructor(
address converterFeed_,
address uniswapPool_,
uint256 defaultAmountIn_,
uint32 windowSize_,
uint256 converterFeedScalingFactor_,
uint256 maxWindowSize_,
uint8 granularity_
) public {
require(uniswapPool_ != address(0), "UniswapV3ConverterMedianizer/null-uniswap-factory");
require(granularity_ > 1, 'UniswapV3ConverterMedianizer/null-granularity');
require(windowSize_ > 0, 'UniswapV3ConverterMedianizer/null-window-size');
require(maxWindowSize_ > windowSize_, 'UniswapV3ConverterMedianizer/invalid-max-window-size');
require(defaultAmountIn_ > 0, 'UniswapV3ConverterMedianizer/invalid-default-amount-in');
require(converterFeedScalingFactor_ > 0, 'UniswapV3ConverterMedianizer/null-feed-scaling-factor');
require(
(periodSize = windowSize_ / granularity_) * granularity_ == windowSize_,
'UniswapConverterBasicAveragePriceFeedMedianizer/window-not-evenly-divisible'
);
authorizedAccounts[msg.sender] = 1;
converterFeed = ConverterFeedLike_3(converterFeed_);
uniswapPool = IUniswapV3Pool(uniswapPool_);
defaultAmountIn = defaultAmountIn_;
windowSize = windowSize_;
maxWindowSize = maxWindowSize_;
converterFeedScalingFactor = converterFeedScalingFactor_;
granularity = granularity_;
validityFlag = 1;
// Populate the arrays with empty observations
for (uint i = converterFeedObservations.length; i < granularity; i++) {
converterFeedObservations.push();
}
// Emit events
emit AddAuthorization(msg.sender);
emit ModifyParameters(bytes32("converterFeed"), converterFeed_);
emit ModifyParameters(bytes32("maxWindowSize"), maxWindowSize_);
}
// --- Administration ---
/**
* @notice Modify address parameters
* @param parameter Name of the parameter to modify
* @param data New parameter value
**/
function modifyParameters(bytes32 parameter, address data) external isAuthorized {
require(data != address(0), "UniswapV3ConverterMedianizer/null-data");
if (parameter == "converterFeed") {
require(data != address(0), "UniswapV3ConverterMedianizer/null-converter-feed");
converterFeed = ConverterFeedLike_3(data);
}
else if (parameter == "targetToken") {
require(targetToken == address(0), "UniswapV3ConverterMedianizer/target-already-set");
require(data == uniswapPool.token0() || data == uniswapPool.token1(),"UniswapV3ConverterMedianizer/target-not-from-pool");
targetToken = data;
if(targetToken == uniswapPool.token0())
denominationToken = uniswapPool.token1();
else {
denominationToken = uniswapPool.token0();
}
}
else if (parameter == "relayer") {
relayer = IncreasingRewardRelayerLike_3(data);
}
else revert("UniswapV3ConverterMedianizer/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
/**
* @notice Modify uint256 parameters
* @param parameter Name of the parameter to modify
* @param data New parameter value
**/
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {
if (parameter == "validityFlag") {
require(either(data == 1, data == 0), "UniswapV3ConverterMedianizer/invalid-data");
validityFlag = data;
}
else if (parameter == "defaultAmountIn") {
require(data > 0, "UniswapV3ConverterMedianizer/invalid-default-amount-in");
defaultAmountIn = data;
}
else if (parameter == "maxWindowSize") {
require(data > windowSize, 'UniswapV3ConverterMedianizer/invalid-max-window-size');
maxWindowSize = data;
}
else revert("UniswapV3ConverterMedianizer/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
// --- General Utils --
function either(bool x, bool y) internal pure returns (bool z) {
assembly{ z := or(x, y)}
}
function both(bool x, bool y) private pure returns (bool z) {
assembly{ z := and(x, y)}
}
/**
* @notice Returns the observations from the oldest epoch (at the beginning of the window) relative to the current time
**/
function getTimeElapsedSinceFirstObservationInWindow()
private view returns (uint256 time) {
uint8 firtObservationIndex = uint8(addition(updates, 1) % granularity);
uint8 latestObservationIndex = uint8(updates % granularity);
time = subtract(converterFeedObservations[latestObservationIndex].timestamp, converterFeedObservations[firtObservationIndex].timestamp - periodSize);
}
// --- Converter Utils ---
/**
* @notice Calculate the price of an amount of tokens using the convertor price feed. Used after the contract determines
* the amount of Uniswap pair denomination tokens for amountIn target tokens
* @param amountIn Amount of denomination tokens to calculate the price for
**/
function converterComputeAmountOut(
uint256 timeElapsed,
uint256 amountIn
) public view returns (uint256 amountOut) {
require(timeElapsed > 0, "UniswapConsecutiveSlotsPriceFeedMedianizer/null-time-elapsed");
if(updates >= granularity) {
uint256 priceAverage = converterPriceCumulative / timeElapsed;
amountOut = multiply(priceAverage,amountIn) / converterFeedScalingFactor;
}
}
// --- Core Logic ---
/**
* @notice Update the internal median price
**/
function updateResult(address feeReceiver) external {
require(address(relayer) != address(0), "UniswapV3ConverterMedianizer/null-relayer");
require(targetToken != address(0), "UniswapV3ConverterMedianizer/null-target-token");
// Get final fee receiver
address finalFeeReceiver = (feeReceiver == address(0)) ? msg.sender : feeReceiver;
// Update the converter's median price first
try converterFeed.updateResult(finalFeeReceiver) {}
catch (bytes memory converterRevertReason) {
emit FailedConverterFeedUpdate(converterRevertReason);
}
// If it's the first reading, we have to set time elapsed manually
uint256 timeSinceLast = updates == 0 ? periodSize :subtract(now, lastUpdateTime);
// We only want to commit updates once per period (i.e. windowSize / granularity)
require(timeSinceLast>= periodSize, "UniswapV3ConverterMedianizer/not-enough-time-elapsed");
// Increase updates and get the index to write to
updates = addition(updates, 1);
uint8 observationIndex = uint8(updates % granularity);
updateObservations(observationIndex, timeSinceLast);
if (updates >= granularity ) medianPrice = getMedianPrice();
lastUpdateTime = now;
emit UpdateResult(medianPrice, lastUpdateTime);
// Reward caller
relayer.reimburseCaller(finalFeeReceiver);
}
/**
* @notice Push new observation data in the observation arrays
* @param observationIndex Array index of the observations to update
**/
function updateObservations(uint8 observationIndex, uint256 timeSinceLastObservation) internal {
ConverterFeedObservation storage latestConverterFeedObservation = converterFeedObservations[observationIndex];
// this value will be overwitten, so we need to first decrease the running amount
if (updates >= granularity) {
converterPriceCumulative = subtract(converterPriceCumulative, latestConverterFeedObservation.timeAdjustedPrice);
}
// Add converter feed observation
(uint256 priceFeedValue, bool hasValidValue) = converterFeed.getResultWithValidity();
require(hasValidValue, "UniswapConverterBasicAveragePriceFeedMedianizer/invalid-converter-price-feed");
// Add converter observation
latestConverterFeedObservation.timestamp = now;
latestConverterFeedObservation.timeAdjustedPrice = multiply(priceFeedValue, timeSinceLastObservation);
converterPriceCumulative = addition(converterPriceCumulative, latestConverterFeedObservation.timeAdjustedPrice);
}
function getMedianPrice() private view returns (uint256 meanPrice) {
require(targetToken != address(0), "UniswapV3ConverterMedianizer/null-target-token");
uint256 timeElapsed = getTimeElapsedSinceFirstObservationInWindow();
int24 medianTick = getUniswapMeanTick(windowSize);
uint256 uniswapAmountOut = getQuoteAtTick(medianTick, uint128(defaultAmountIn),targetToken, denominationToken);
meanPrice = converterComputeAmountOut(timeElapsed, uniswapAmountOut);
}
/// @notice Fetches time-weighted average tick using Uniswap V3 oracle
/// @param period Number of seconds in the past to start calculating time-weighted average
/// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - period) to block.timestamp
function getUniswapMeanTick(uint32 period) internal view returns (int24 timeWeightedAverageTick) {
require(period != 0, 'UniswapV3ConverterMedianizer/invalid-period');
uint32[] memory secondAgos = new uint32[](2);
secondAgos[0] = period;
secondAgos[1] = 0;
(int56[] memory tickCumulatives, ) = IUniswapV3Pool(uniswapPool).observe(secondAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
timeWeightedAverageTick = int24(tickCumulativesDelta / period);
// Always round to negative infinity
if (tickCumulativesDelta < 0 && (tickCumulativesDelta % period != 0)) timeWeightedAverageTick--;
}
/// @notice Given a tick and a token amount, calculates the amount of token received in exchange
/// @param tick Tick value used to calculate the quote
/// @param baseAmount Amount of token to be converted
/// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
/// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
/// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
function getQuoteAtTick(
int24 tick,
uint128 baseAmount,
address baseToken,
address quoteToken
) internal pure returns (uint256 quoteAmount) {
uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
uint128 maxUint = uint128(0-1);
// Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
if (sqrtRatioX96 <= maxUint) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
: FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
} else {
uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64);
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
: FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
}
}
// --- Getters ---
/**
* @notice Fetch the latest medianPrice or revert if is is null
**/
function read() external view returns (uint256) {
uint256 value = getMedianPrice();
require(
both(both(both(value > 0, updates >= granularity), validityFlag == 1),getTimeElapsedSinceFirstObservationInWindow()<= maxWindowSize),
"UniswapV3ConverterMedianizer/invalid-price-feed"
);
return value;
}
/**
* @notice Fetch the latest medianPrice and whether it is null or not
**/
function getResultWithValidity() external view returns (uint256, bool) {
return (medianPrice, both(both(medianPrice > 0, updates >= granularity), validityFlag == 1));
}
function getMedianWithMedianizedPrice(uint256 medianizedETH) external view returns(uint256) {
int24 medianTick = getUniswapMeanTick(windowSize);
uint256 uniswapAmountOut = getQuoteAtTick(medianTick, uint128(defaultAmountIn),targetToken, denominationToken);
return multiply(medianizedETH,uniswapAmountOut) / converterFeedScalingFactor;
}
function getMedianWithMedianizedAndWindow(uint32 _windowSize, uint256 medianizedETH) external view returns(uint256) {
int24 medianTick = getUniswapMeanTick(_windowSize);
uint256 uniswapAmountOut = getQuoteAtTick(medianTick, uint128(defaultAmountIn),targetToken, denominationToken);
return multiply(medianizedETH,uniswapAmountOut) / converterFeedScalingFactor;
}
}
|
--- Administration --- Modify address parameters parameter Name of the parameter to modify data New parameter value/
|
function modifyParameters(bytes32 parameter, address data) external isAuthorized {
require(data != address(0), "UniswapV3ConverterMedianizer/null-data");
if (parameter == "converterFeed") {
require(data != address(0), "UniswapV3ConverterMedianizer/null-converter-feed");
converterFeed = ConverterFeedLike_3(data);
}
else if (parameter == "targetToken") {
require(targetToken == address(0), "UniswapV3ConverterMedianizer/target-already-set");
require(data == uniswapPool.token0() || data == uniswapPool.token1(),"UniswapV3ConverterMedianizer/target-not-from-pool");
targetToken = data;
if(targetToken == uniswapPool.token0())
denominationToken = uniswapPool.token1();
else {
denominationToken = uniswapPool.token0();
}
}
else if (parameter == "relayer") {
relayer = IncreasingRewardRelayerLike_3(data);
}
else revert("UniswapV3ConverterMedianizer/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
| 6,772,930
|
./full_match/80001/0xB44Ae12e3245A3FbdD9445c536ef568a702e77DF/sources/contracts/PhatRollupAnchor.sol
|
Get the next item id in queue.
|
function getTailIndex() public view returns (uint32) {
uint32 tail = queueGetUint(KEY_TAIL);
return tail;
}
| 845,159
|
./full_match/1/0x9621809F47dBB9d9e48E4c1cEE679DEd6c9aeA06/sources/contracts/drops/AllowList.sol
|
Returns the length of the allow list./
|
function _length() internal view returns (uint256) {
return _allowList.length();
}
| 9,611,615
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../interfaces/Types.sol";
import "../interfaces/ILedger.sol";
import "../interfaces/IOracleMaster.sol";
import "./utils/ReportUtils.sol";
contract Oracle {
using ReportUtils for uint256;
event Completed(uint256);
// is already pushed flag
bool public isPushed;
// Current era report hashes
uint256[] internal currentReportVariants;
// Current era reports
Types.OracleData[] private currentReports;
// Then oracle member push report, its bit is set
uint256 internal currentReportBitmask;
// oracle master contract address
address public ORACLE_MASTER;
// linked ledger contract address
address public LEDGER;
// Allows function calls only from OracleMaster
modifier onlyOracleMaster() {
require(msg.sender == ORACLE_MASTER);
_;
}
/**
* @notice Initialize oracle contract
* @param _oracleMaster oracle master address
* @param _ledger linked ledger address
*/
function initialize(address _oracleMaster, address _ledger) external {
require(ORACLE_MASTER == address(0), "ORACLE: ALREADY_INITIALIZED");
ORACLE_MASTER = _oracleMaster;
LEDGER = _ledger;
}
/**
* @notice Returns true if member is already reported
* @param _index oracle member index
* @return is reported indicator
*/
function isReported(uint256 _index) external view returns (bool) {
return (currentReportBitmask & (1 << _index)) != 0;
}
/**
* @notice Accept oracle report data, allowed to call only by oracle master contract
* @param _index oracle member index
* @param _quorum the minimum number of voted oracle members to accept a variant
* @param _eraId current era id
* @param _staking report data
*/
function reportRelay(uint256 _index, uint256 _quorum, uint64 _eraId, Types.OracleData calldata _staking) external onlyOracleMaster {
{
uint256 mask = 1 << _index;
uint256 reportBitmask = currentReportBitmask;
require(reportBitmask & mask == 0, "ORACLE: ALREADY_SUBMITTED");
currentReportBitmask = (reportBitmask | mask);
}
// return instantly if already got quorum and pushed data
if (isPushed) {
return;
}
// convert staking report into 31 byte hash. The last byte is used for vote counting
uint256 variant = uint256(keccak256(abi.encode(_staking))) & ReportUtils.COUNT_OUTMASK;
uint256 i = 0;
uint256 _length = currentReportVariants.length;
// iterate on all report variants we already have, limited by the oracle members maximum
while (i < _length && currentReportVariants[i].isDifferent(variant)) ++i;
if (i < _length) {
if (currentReportVariants[i].getCount() + 1 >= _quorum) {
_push(_eraId, _staking);
} else {
++currentReportVariants[i];
// increment variant counter, see ReportUtils for details
}
} else {
if (_quorum == 1) {
_push(_eraId, _staking);
} else {
currentReportVariants.push(variant + 1);
currentReports.push(_staking);
}
}
}
/**
* @notice Change quorum threshold, allowed to call only by oracle master contract
* @dev Method can trigger to pushing data to ledger if quorum threshold decreased and
now for contract already reached new threshold.
* @param _quorum new quorum threshold
* @param _eraId current era id
*/
function softenQuorum(uint8 _quorum, uint64 _eraId) external onlyOracleMaster {
(bool isQuorum, uint256 reportIndex) = _getQuorumReport(_quorum);
if (isQuorum) {
Types.OracleData memory report = _getStakeReport(reportIndex);
_push(
_eraId, report
);
}
}
/**
* @notice Clear data about current reporting, allowed to call only by oracle master contract
*/
function clearReporting() external onlyOracleMaster {
_clearReporting();
}
/**
* @notice Returns report by given index
* @param _index oracle member index
* @return staking report data
*/
function _getStakeReport(uint256 _index) internal view returns (Types.OracleData storage staking) {
assert(_index < currentReports.length);
return currentReports[_index];
}
/**
* @notice Clear data about current reporting
*/
function _clearReporting() internal {
currentReportBitmask = 0;
isPushed = false;
delete currentReportVariants;
delete currentReports;
}
/**
* @notice Push data to ledger
*/
function _push(uint64 _eraId, Types.OracleData memory report) internal {
ILedger(LEDGER).pushData(_eraId, report);
isPushed = true;
}
/**
* @notice Return whether the `_quorum` is reached and the final report can be pushed
*/
function _getQuorumReport(uint256 _quorum) internal view returns (bool, uint256) {
// check most frequent cases first: all reports are the same or no reports yet
uint256 _length = currentReportVariants.length;
if (_length == 1) {
return (currentReportVariants[0].getCount() >= _quorum, 0);
} else if (_length == 0) {
return (false, type(uint256).max);
}
// if more than 2 kind of reports exist, choose the most frequent
uint256 maxind = 0;
uint256 repeat = 0;
uint16 maxval = 0;
uint16 cur = 0;
for (uint256 i = 0; i < _length; ++i) {
cur = currentReportVariants[i].getCount();
if (cur >= maxval) {
if (cur == maxval) {
++repeat;
} else {
maxind = i;
maxval = cur;
repeat = 0;
}
}
}
return (maxval >= _quorum && repeat == 0, maxind);
}
}
|
Returns true if member is already reported _index oracle member index return is reported indicator/
|
function isReported(uint256 _index) external view returns (bool) {
return (currentReportBitmask & (1 << _index)) != 0;
}
| 967,661
|
//Address: 0xd1670c55f5e68fede5fddd8ace64a3329f778b89
//Contract name: ATSTokenReservation
//Balance: 215.853806028 Ether
//Verification Date: 5/30/2018
//Transacion Count: 81
// CODE STARTS HERE
pragma solidity ^0.4.23;
/*
* Contract accepting reservations for ATS tokens.
* The actual tokens are not yet created and distributed due to non-technical reasons.
* This contract is used to collect funds for the ATS token sale and to transparently document that on a blockchain.
* It is tailored to allow a simple user journey while keeping complexity minimal.
* Once the privileged "state controller" sets the state to "Open", anybody can send Ether to the contract.
* Only Ether sent from whitelisted addresses is accepted for future ATS token conversion.
* The whitelisting is done by a dedicated whitelist controller.
* Whitelisting can take place asynchronously - that is, participants don't need to wait for the whitelisting to
* succeed before sending funds. This is a technical detail which allows for a smoother user journey.
* The state controller can switch to synchronous whitelisting (no Ether accepted from accounts not whitelisted before).
* Participants can trigger refunding during the Open state by making a transfer of 0 Ether.
* Funds of those not whitelisted (not accepted) are never locked, they can trigger refund beyond Open state.
* Only in Over state can whitelisted Ether deposits be fetched from the contract.
*
* When setting the state to Open, the state controller specifies a minimal timeframe for this state.
* Transition to the next state (Locked) is not possible (enforced by the contract).
* This gives participants the guarantee that they can get their full deposits refunded anytime and independently
* of the will of anybody else during that timeframe.
* (Note that this is true only as long as the whole process takes place before the date specified by FALLBACK_FETCH_FUNDS_TS)
*
* Ideally, there's no funds left in the contract once the state is set to Over and the accepted deposits were fetched.
* Since this can't really be foreseen, there's a fallback which allows to fetch all remaining Ether
* to a pre-specified address after a pre-specified date.
*
* Static analysis: block.timestamp is not used in a way which gives miners leeway for taking advantage.
*
* see https://code.lab10.io/graz/04-artis/artis/issues/364 for task evolution
*/
contract ATSTokenReservation {
// ################### DATA STRUCTURES ###################
enum States {
Init, // initial state. Contract is deployed, but deposits not yet accepted
Open, // open for token reservations. Refunds possible for all
Locked, // open for token reservations. Refunds locked for accepted deposits
Over // contract has done its duty. Funds payout can be triggered by state controller
}
// ################### CONSTANTS ###################
// 1. Oct 2018
uint32 FALLBACK_PAYOUT_TS = 1538352000;
// ################### STATE VARIABLES ###################
States public state = States.Init;
// privileged account: switch contract state, change config, whitelisting, trigger payout, ...
address public stateController;
// privileged account: whitelisting
address public whitelistController;
// Collected funds can be transferred only to this address. Is set in constructor.
address public payoutAddress;
// accepted deposits (received from whitelisted accounts)
uint256 public cumAcceptedDeposits = 0;
// not (yet) accepted deposits (received from non-whitelisted accounts)
uint256 public cumAlienDeposits = 0;
// cap for how much we accept (since the amount of tokens sold is also capped)
uint256 public maxCumAcceptedDeposits = 1E9 * 1E18; // pre-set to effectively unlimited (> existing ETH)
uint256 public minDeposit = 0.1 * 1E18; // lower bound per participant (can be a kind of spam protection)
uint256 minLockingTs; // earliest possible start of "locked" phase
// whitelisted addresses (those having "accepted" deposits)
mapping (address => bool) public whitelist;
// the state controller can set this in order to disallow deposits from addresses not whitelisted before
bool public requireWhitelistingBeforeDeposit = false;
// tracks accepted deposits (whitelisted accounts)
mapping (address => uint256) public acceptedDeposits;
// tracks alien (not yet accepted) deposits (non-whitelisted accounts)
mapping (address => uint256) public alienDeposits;
// ################### EVENTS ###################
// emitted events transparently document the open funding activities.
// only deposits made by whitelisted accounts (and not followed by a refund) count.
event StateTransition(States oldState, States newState);
event Whitelisted(address addr);
event Deposit(address addr, uint256 amount);
event Refund(address addr, uint256 amount);
// emitted when the accepted deposits are fetched to an account controlled by the ATS token provider
event FetchedDeposits(uint256 amount);
// ################### MODIFIERS ###################
modifier onlyStateControl() { require(msg.sender == stateController, "no permission"); _; }
modifier onlyWhitelistControl() {
require(msg.sender == stateController || msg.sender == whitelistController, "no permission");
_;
}
modifier requireState(States _requiredState) { require(state == _requiredState, "wrong state"); _; }
// ################### CONSTRUCTOR ###################
// the contract creator is set as stateController
constructor(address _whitelistController, address _payoutAddress) public {
whitelistController = _whitelistController;
payoutAddress = _payoutAddress;
stateController = msg.sender;
}
// ################### FALLBACK FUNCTION ###################
// implements the deposit and refund actions.
function () payable public {
if(msg.value > 0) {
require(state == States.Open || state == States.Locked);
if(requireWhitelistingBeforeDeposit) {
require(whitelist[msg.sender] == true, "not whitelisted");
}
tryDeposit();
} else {
tryRefund();
}
}
// ################### PUBLIC FUNCTIONS ###################
function stateSetOpen(uint32 _minLockingTs) public
onlyStateControl
requireState(States.Init)
{
minLockingTs = _minLockingTs;
setState(States.Open);
}
function stateSetLocked() public
onlyStateControl
requireState(States.Open)
{
require(block.timestamp >= minLockingTs);
setState(States.Locked);
}
function stateSetOver() public
onlyStateControl
requireState(States.Locked)
{
setState(States.Over);
}
// state controller can change the cap. Reducing possible only if not below current deposits
function updateMaxAcceptedDeposits(uint256 _newMaxDeposits) public onlyStateControl {
require(cumAcceptedDeposits <= _newMaxDeposits);
maxCumAcceptedDeposits = _newMaxDeposits;
}
// new limit to be enforced for future deposits
function updateMinDeposit(uint256 _newMinDeposit) public onlyStateControl {
minDeposit = _newMinDeposit;
}
// option to switch between async and sync whitelisting
function setRequireWhitelistingBeforeDeposit(bool _newState) public onlyStateControl {
requireWhitelistingBeforeDeposit = _newState;
}
// Since whitelisting can occur asynchronously, an account to be whitelisted may already have deposited Ether.
// In this case the deposit is converted form alien to accepted.
// Since the deposit logic depends on the whitelisting status and since transactions are processed sequentially,
// it's ensured that at any time an account can have either (XOR) no or alien or accepted deposits and that
// the whitelisting status corresponds to the deposit status (not_whitelisted <-> alien | whitelisted <-> accepted).
// This function is idempotent.
function addToWhitelist(address _addr) public onlyWhitelistControl {
if(whitelist[_addr] != true) {
// if address has alien deposit: convert it to accepted
if(alienDeposits[_addr] > 0) {
cumAcceptedDeposits += alienDeposits[_addr];
acceptedDeposits[_addr] += alienDeposits[_addr];
cumAlienDeposits -= alienDeposits[_addr];
delete alienDeposits[_addr]; // needs to be the last statement in this block!
}
whitelist[_addr] = true;
emit Whitelisted(_addr);
}
}
// Option for batched whitelisting (for times with crowded chain).
// caller is responsible to not blow gas limit with too many addresses at once
function batchAddToWhitelist(address[] _addresses) public onlyWhitelistControl {
for (uint i = 0; i < _addresses.length; i++) {
addToWhitelist(_addresses[i]);
}
}
// transfers an alien deposit back to the sender
function refundAlienDeposit(address _addr) public onlyWhitelistControl {
// Note: this implementation requires that alienDeposits has a primitive value type.
// With a complex type, this code would produce a dangling reference.
uint256 withdrawAmount = alienDeposits[_addr];
require(withdrawAmount > 0);
delete alienDeposits[_addr]; // implies setting the value to 0
cumAlienDeposits -= withdrawAmount;
emit Refund(_addr, withdrawAmount);
_addr.transfer(withdrawAmount); // throws on failure
}
// payout of the accepted deposits to the pre-designated address, available once it's all over
function payout() public
onlyStateControl
requireState(States.Over)
{
uint256 amount = cumAcceptedDeposits;
cumAcceptedDeposits = 0;
emit FetchedDeposits(amount);
payoutAddress.transfer(amount);
// not idempotent, but multiple invocation would just trigger zero-transfers
}
// After the specified date, any of the privileged/special accounts can trigger payment of remaining funds
// to the payoutAddress. This is a safety net to minimize the risk of funds remaining stuck.
// It's not yet clear what we can / should / are allowed to do with alien deposits which aren't reclaimed.
// With this fallback in place, we have for example the option to donate them at some point.
function fallbackPayout() public {
require(msg.sender == stateController || msg.sender == whitelistController || msg.sender == payoutAddress);
require(block.timestamp > FALLBACK_PAYOUT_TS);
payoutAddress.transfer(address(this).balance);
}
// ################### INTERNAL FUNCTIONS ###################
// rule enforcement and book-keeping for incoming deposits
function tryDeposit() internal {
require(cumAcceptedDeposits + msg.value <= maxCumAcceptedDeposits);
if(whitelist[msg.sender] == true) {
require(acceptedDeposits[msg.sender] + msg.value >= minDeposit);
acceptedDeposits[msg.sender] += msg.value;
cumAcceptedDeposits += msg.value;
} else {
require(alienDeposits[msg.sender] + msg.value >= minDeposit);
alienDeposits[msg.sender] += msg.value;
cumAlienDeposits += msg.value;
}
emit Deposit(msg.sender, msg.value);
}
// rule enforcement and book-keeping for refunding requests
function tryRefund() internal {
// Note: this implementation requires that acceptedDeposits and alienDeposits have a primitive value type.
// With a complex type, this code would produce dangling references.
uint256 withdrawAmount;
if(whitelist[msg.sender] == true) {
require(state == States.Open);
withdrawAmount = acceptedDeposits[msg.sender];
require(withdrawAmount > 0);
delete acceptedDeposits[msg.sender]; // implies setting the value to 0
cumAcceptedDeposits -= withdrawAmount;
} else {
// alien deposits can be withdrawn anytime (we prefer to not touch them)
withdrawAmount = alienDeposits[msg.sender];
require(withdrawAmount > 0);
delete alienDeposits[msg.sender]; // implies setting the value to 0
cumAlienDeposits -= withdrawAmount;
}
emit Refund(msg.sender, withdrawAmount);
// do the actual transfer last as recommended since the DAO incident (Checks-Effects-Interaction pattern)
msg.sender.transfer(withdrawAmount); // throws on failure
}
function setState(States _newState) internal {
state = _newState;
emit StateTransition(state, _newState);
}
}
|
transfers an alien deposit back to the sender Note: this implementation requires that alienDeposits has a primitive value type. With a complex type, this code would produce a dangling reference.
|
function refundAlienDeposit(address _addr) public onlyWhitelistControl {
uint256 withdrawAmount = alienDeposits[_addr];
require(withdrawAmount > 0);
cumAlienDeposits -= withdrawAmount;
emit Refund(_addr, withdrawAmount);
}
| 1,041,367
|
// File: @ensdomains/ens/contracts/ENS.sol
pragma solidity >=0.4.24;
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);
// Logged when an operator is added or removed.
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external;
function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external;
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns(bytes32);
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function setApprovalForAll(address operator, bool approved) 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);
function recordExists(bytes32 node) external view returns (bool);
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// File: @ensdomains/ens/contracts/ReverseRegistrar.sol
pragma solidity ^0.5.0;
contract Resolver {
function setName(bytes32 node, string memory name) public;
}
contract ReverseRegistrar {
// namehash('addr.reverse')
bytes32 public constant ADDR_REVERSE_NODE = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2;
ENS public ens;
Resolver public defaultResolver;
/**
* @dev Constructor
* @param ensAddr The address of the ENS registry.
* @param resolverAddr The address of the default reverse resolver.
*/
constructor(ENS ensAddr, Resolver resolverAddr) public {
ens = ensAddr;
defaultResolver = resolverAddr;
// Assign ownership of the reverse record to our deployer
ReverseRegistrar oldRegistrar = ReverseRegistrar(ens.owner(ADDR_REVERSE_NODE));
if (address(oldRegistrar) != address(0x0)) {
oldRegistrar.claim(msg.sender);
}
}
/**
* @dev Transfers ownership of the reverse ENS record associated with the
* calling account.
* @param owner The address to set as the owner of the reverse record in ENS.
* @return The ENS node hash of the reverse record.
*/
function claim(address owner) public returns (bytes32) {
return claimWithResolver(owner, address(0x0));
}
/**
* @dev Transfers ownership of the reverse ENS record associated with the
* calling account.
* @param owner The address to set as the owner of the reverse record in ENS.
* @param resolver The address of the resolver to set; 0 to leave unchanged.
* @return The ENS node hash of the reverse record.
*/
function claimWithResolver(address owner, address resolver) public returns (bytes32) {
bytes32 label = sha3HexAddress(msg.sender);
bytes32 node = keccak256(abi.encodePacked(ADDR_REVERSE_NODE, label));
address currentOwner = ens.owner(node);
// Update the resolver if required
if (resolver != address(0x0) && resolver != ens.resolver(node)) {
// Transfer the name to us first if it's not already
if (currentOwner != address(this)) {
ens.setSubnodeOwner(ADDR_REVERSE_NODE, label, address(this));
currentOwner = address(this);
}
ens.setResolver(node, resolver);
}
// Update the owner if required
if (currentOwner != owner) {
ens.setSubnodeOwner(ADDR_REVERSE_NODE, label, owner);
}
return node;
}
/**
* @dev Sets the `name()` record for the reverse ENS record associated with
* the calling account. First updates the resolver to the default reverse
* resolver if necessary.
* @param name The name to set for this address.
* @return The ENS node hash of the reverse record.
*/
function setName(string memory name) public returns (bytes32) {
bytes32 node = claimWithResolver(address(this), address(defaultResolver));
defaultResolver.setName(node, name);
return node;
}
/**
* @dev Returns the node hash for a given account's reverse records.
* @param addr The address to hash
* @return The ENS node hash.
*/
function node(address addr) public pure returns (bytes32) {
return keccak256(abi.encodePacked(ADDR_REVERSE_NODE, sha3HexAddress(addr)));
}
/**
* @dev An optimised function to compute the sha3 of the lower-case
* hexadecimal representation of an Ethereum address.
* @param addr The address to hash
* @return The SHA3 hash of the lower-case hexadecimal encoding of the
* input address.
*/
function sha3HexAddress(address addr) private pure returns (bytes32 ret) {
addr;
ret; // Stop warning us about unused variables
assembly {
let lookup := 0x3031323334353637383961626364656600000000000000000000000000000000
for { let i := 40 } gt(i, 0) { } {
i := sub(i, 1)
mstore8(i, byte(and(addr, 0xf), lookup))
addr := div(addr, 0x10)
i := sub(i, 1)
mstore8(i, byte(and(addr, 0xf), lookup))
addr := div(addr, 0x10)
}
ret := keccak256(0, 40)
}
}
}
|
Sets the `name()` record for the reverse ENS record associated with the calling account. First updates the resolver to the default reverse resolver if necessary. name The name to set for this address. return The ENS node hash of the reverse record./
|
function setName(string memory name) public returns (bytes32) {
bytes32 node = claimWithResolver(address(this), address(defaultResolver));
defaultResolver.setName(node, name);
return node;
}
| 897,086
|
pragma solidity 0.4.25;
import "./TokenSSID.sol";
contract SistemaSanitario is TokenSSID {
string sanidad_nombre;
string sanidad_pais;
address public sanidad_addr;
struct Medico {
address medico;
string especialidad;
uint fechaalta;
uint fechabaja;
bool autorizado;
bool isExist;
}
struct Expediente{
uint fecha;
address medico;
string especialidad;
string dolencia;
string tratamiento;
uint duracion;
}
struct Ciudadano {
address ciudadano;
uint SSID;
uint fechaalta;
uint fechabaja;
uint estado;
bool isExist;
Expediente[] expediente;
}
struct Aseguradora {
address seguro;
string especialidad;
uint fechaalta;
uint fechabaja;
bool autorizado;
bool isExist;
}
mapping(address => Medico) public medicos;
mapping(address => Ciudadano) public ciudadanos;
mapping(address => Aseguradora) public aseguradoras;
modifier restrictedBySanidad() {
require(sanidad_addr == msg.sender, "Restringuida a Sanidad");
_;
}
modifier restrictedByMedicoAutorizado() {
require(medicos[msg.sender].autorizado, "Requiere medico autorizado");
_;
}
modifier restrictedByAseguradoraAutorizada() {
require(aseguradoras[msg.sender].autorizado, "Requiere aseguradora autorizada");
_;
}
// event utilizado para dejar en el log los datos de los expedientes insertados y consultados
event eventExpediente(
string _expediente,
address _addressMedico,
address _addressCiudadano,
uint _SSID,
uint _numExpediente,
uint _fecha
);
/**
* @dev Al contructor le pasamos como parametros nombre sel sistema sanitario y el pais para una
* ampliación de las funcionalidades
* @param _nombre string nombre sel sistema sanitario
* @param _pais string indicando el pais del sistema sanitario
*/
constructor(string _nombre, string _pais) public {
sanidad_nombre = _nombre;
sanidad_pais = _pais;
sanidad_addr = msg.sender;
}
/**
* @dev Alta de un medico, los medicos se dan de alta ellos mismos
* revert si medico ya existe
* @param _especialidad string especialidad del medico que se da de alta
*/
function altaMedico (string _especialidad) public {
address aux;
aux = msg.sender;
require(aux != sanidad_addr, "Address invalida");
require(!medicos[aux].isExist, "Medico ya existe");
medicos[aux].medico = aux;
medicos[aux].especialidad = _especialidad;
medicos[aux].fechaalta = now;
medicos[aux].autorizado = false;
medicos[aux].isExist = true;
}
/**
* @dev Consulta médico, solo Sanidad puede consultar medico
* revert si medico no existe
* @param _adrMedico address del medico a dar de alta
* @return string especialidad del medico
* @return uint fecha de alta
* @return uint fecha de baja
* @return bool si esta autorizado o no
*/
function consultaMedico(address _adrMedico) public view restrictedBySanidad returns (string, uint, uint, bool){
require(medicos[_adrMedico].isExist, "Medico no existe");
return (
medicos[_adrMedico].especialidad,
medicos[_adrMedico].fechaalta,
medicos[_adrMedico].fechabaja,
medicos[_adrMedico].autorizado
);
}
/**
* @dev Baja de un medico, solo Sanidad puede dar de baja un medico, queda desautorizado
* revert si el medico no existe
* @param _adrMedico address del medico
*/
function bajaMedico(address _adrMedico) public restrictedBySanidad {
require(medicos[_adrMedico].isExist, "Medico no existe");
medicos[_adrMedico].fechabaja = now;
medicos[_adrMedico].autorizado = false;
}
/**
* @dev Autorizar medico, solo Sanidad puede autorizar a un medico
* revert si no es sanidad quin lo ejecuta
* revert si el medico ya estaba autorizado
* revert si el medico no existe
* @param _adrMedico address del medico
*/
function autorizarMedico (address _adrMedico) public restrictedBySanidad {
address aux;
aux = msg.sender;
require(aux == sanidad_addr, "Solo Sanidad puede autorizar");
require(!medicos[_adrMedico].autorizado, "Medico ya estaba autorizado");
require(medicos[_adrMedico].isExist, "Medico no existente");
medicos[_adrMedico].autorizado = true;
}
/**
* @dev desautorizar medico, solo Sanidad puede desautorizar a un medico
* revert si no es sanidad quin lo ejecuta
* revert si el medico ya estaba desautorizado
* revert si el medico no existe
* @param _adrMedico address del medico
*/
function desautorizarMedico (address _adrMedico) public restrictedBySanidad {
address aux;
aux = msg.sender;
require(aux == sanidad_addr, "Solo Sanidad puede desautorizar");
require(medicos[_adrMedico].autorizado, "Medico ya estaba desautorizado !");
require(medicos[_adrMedico].isExist, "Medico no existente");
medicos[_adrMedico].autorizado = false;
}
/**
* @dev Alta ciudadano, solo Sanidad puede dar de alta un ciudadano, se le asigna un Token SSID
* revert si el ciudadano ya existe
* @param _adrCiudadano address del ciudadano
*/
function altaCiudadano (address _adrCiudadano) public restrictedBySanidad {
require(!ciudadanos[_adrCiudadano].isExist,"Ciudadano ya existe");
ciudadanos[_adrCiudadano].ciudadano = _adrCiudadano;
ciudadanos[_adrCiudadano].fechaalta = now;
ciudadanos[_adrCiudadano].estado = 1; // 1 Alta
ciudadanos[_adrCiudadano].isExist = true;
ciudadanos[_adrCiudadano].SSID = mintTo(_adrCiudadano);
}
/**
* @dev Baja ciudadano, solo Sanidad puede dar de baja un ciudadano
* revert si el ciudadano no existe
* @param _adrCiudadano address del ciudadano
*/
function bajaCiudadano (address _adrCiudadano) public restrictedBySanidad {
require(ciudadanos[_adrCiudadano].isExist, "Ciudadano no existe");
ciudadanos[_adrCiudadano].fechabaja = now;
ciudadanos[_adrCiudadano].estado = 2; // 2 Baja
}
/**
* @dev Modificar el estado de un ciudadano, solo Sanidad puede modificar el estado un ciudadano
* solo se permite estado: 0=desaperecido, 1=alta
* revert si el ciudadano no existe
* @param _adrCiudadano address del ciudadano
* @param _estado uint con el valor del nuevo estado
*/
function modifCiudadano (address _adrCiudadano, uint _estado) public restrictedBySanidad {
require(ciudadanos[_adrCiudadano].isExist, "Ciudadano no existe");
require(_estado <2, "Estados permitidos: 0=desaperecido, 1=alta");
ciudadanos[_adrCiudadano].fechabaja = now;
ciudadanos[_adrCiudadano].estado = _estado; // 2 Baja
}
// Solo Sanidad puede dar de alta una Aseguradora
/**
* @dev Alta aseguradora, solo Sanidad puede dar de alta una aseguradora
* revert si la aseguradora ya existe
* @param _adrAseguradora address de la aseguradora
* @param _especialidad string con la especialidad de la aseguradora
*/
function altaAseguradora (address _adrAseguradora, string _especialidad) public restrictedBySanidad {
require(!aseguradoras[_adrAseguradora].isExist,"Aseguradora ya existe");
aseguradoras[_adrAseguradora].seguro = _adrAseguradora;
aseguradoras[_adrAseguradora].especialidad = _especialidad;
aseguradoras[_adrAseguradora].fechaalta = now;
aseguradoras[_adrAseguradora].autorizado = true;
aseguradoras[_adrAseguradora].isExist = true;
}
/**
* @dev Insertar expediente, solo lo puede realizar un medico autorizado por Sanidad
* revert si el ciudadano no existe
* revert si el ciudadano es el propio medico, no se permite autodiagnosticar
* revert si el estado del ciudadano no es igual a 1 (alta)
* @param _adrCiudadano address del ciudadano al que se a diagnosticado
* @param _dolencia string con la dolencia diagnosticada
* @param _tratamiento string con el tratamiento medico
* @param _duracion uint con la duracion del tratamiento
* @dev se genera un evento con información del medico que lo ha diagnosticado, ciudadano,
* token SSID, Nº expediente y fecha
*/
function insertExpediente (address _adrCiudadano,string _dolencia,string _tratamiento,uint _duracion) public restrictedByMedicoAutorizado{
Expediente memory aux_Expediente;
uint _IDexpediente;
uint _SSID;
require(ciudadanos[_adrCiudadano].isExist, "Ciudadano no existe");
require(_adrCiudadano != msg.sender, "No se permite autodiagnosticar");
require(ciudadanos[_adrCiudadano].estado == 1, "Estado incorrecto de ciudadano");
aux_Expediente.fecha = now;
aux_Expediente.medico = msg.sender;
aux_Expediente.especialidad = medicos[msg.sender].especialidad;
aux_Expediente.dolencia = _dolencia;
aux_Expediente.tratamiento = _tratamiento;
aux_Expediente.duracion = _duracion;
_IDexpediente = ciudadanos[_adrCiudadano].expediente.push(aux_Expediente) - 1;
_SSID = ciudadanos[_adrCiudadano].SSID;
emit eventExpediente(
"Expediente insertado por:",
msg.sender,
_adrCiudadano,
_SSID,
_IDexpediente,
now
);
}
/**
* @dev Consultar expediente, solo lo puede realizar un medico autorizado por Sanidad
* revert si el ciudadano no existe
* revert si el ID del expediente no existe
* @param _adrCiudadano address del ciudadano al que se a diagnosticado
* @param _IDexpediente uint ID del expediente a consultar
* @dev se genera un evento con información del medico que lo ha consultado, ciudadano,
* token SSID, Nº expediente y fecha
* @return uint fecha del expediente
* @return address del medico que lo diagnosticó
* @return string especialidad del medico que lo diagnosticó
* @return string de la dolencia
* @return string con el tratamiento
* @return uint con el token SSID del ciudadano
*/
function consultaExpediente (address _adrCiudadano, uint _IDexpediente) public restrictedByMedicoAutorizado returns(uint,address,string,string,string,uint) {
address aux_medico;
aux_medico = msg.sender;
require(ciudadanos[_adrCiudadano].isExist, "Ciudadano no existe");
require(ciudadanos[_adrCiudadano].expediente.length > _IDexpediente, "ID expediente no existe");
emit eventExpediente(
"Expediente consultado por:",
msg.sender,
_adrCiudadano,
ciudadanos[_adrCiudadano].SSID,
_IDexpediente,
now
);
return(
ciudadanos[_adrCiudadano].expediente[_IDexpediente].fecha,
ciudadanos[_adrCiudadano].expediente[_IDexpediente].medico,
ciudadanos[_adrCiudadano].expediente[_IDexpediente].especialidad,
ciudadanos[_adrCiudadano].expediente[_IDexpediente].dolencia,
ciudadanos[_adrCiudadano].expediente[_IDexpediente].tratamiento,
ciudadanos[_adrCiudadano].SSID
);
}
/**
* @dev Consultar expediente, solo lo puede realizar una aseguradora autorizada por Sanidad
* revert si el ciudadano no existe
* revert si el ID del expediente no existe
* @param _adrCiudadano address del ciudadano al que se a diagnosticado
* @param _IDexpediente uint ID del expediente a consultar
* @dev se genera un evento con información de la aseguradora que lo ha consultado, ciudadano,
* token SSID, Nº expediente y fecha
* @return uint fecha del expediente
* @return address del medico que lo diagnosticó
* @return string especialidad del medico que lo diagnosticó
* @return string de la dolencia
* @return string con el tratamiento
* @return uint con el token SSID del ciudadano
*/
function consultaExpedienteAseguradora (address _adrCiudadano, uint _IDexpediente)
public payable restrictedByAseguradoraAutorizada returns(uint,address,string,string,string,uint) {
address aux_aseguradora;
aux_aseguradora = msg.sender;
require(msg.value >= 1000000, "Pago insuficiente");
require(ciudadanos[_adrCiudadano].isExist, "Ciudadano no existe");
require(ciudadanos[_adrCiudadano].expediente.length > _IDexpediente, "ID expediente no existe");
emit eventExpediente(
"Expediente consultado por:",
msg.sender,
_adrCiudadano,
ciudadanos[_adrCiudadano].SSID,
_IDexpediente,
now
);
return(
ciudadanos[_adrCiudadano].expediente[_IDexpediente].fecha,
ciudadanos[_adrCiudadano].expediente[_IDexpediente].medico,
ciudadanos[_adrCiudadano].expediente[_IDexpediente].especialidad,
ciudadanos[_adrCiudadano].expediente[_IDexpediente].dolencia,
ciudadanos[_adrCiudadano].expediente[_IDexpediente].tratamiento,
ciudadanos[_adrCiudadano].SSID
);
}
}
|
Baja ciudadano, solo Sanidad puede dar de baja un ciudadano revert si el ciudadano no existe _adrCiudadano address del ciudadano/
|
function bajaCiudadano (address _adrCiudadano) public restrictedBySanidad {
require(ciudadanos[_adrCiudadano].isExist, "Ciudadano no existe");
ciudadanos[_adrCiudadano].fechabaja = now;
}
| 929,011
|
./full_match/1/0x5537f945D8c3FCFDc1b8DECEEBD220FAD26aFdA8/sources/contracts/ComposableStablePool.sol
|
Pay any due protocol fees and calculate values necessary for performing the join/exit./ If the amplification factor is the same as it was during the last join/exit then we can reuse the value calculated using the "old" amplification factor. If not, then we have to calculate this now.
|
function _beforeJoinExit(uint256[] memory registeredBalances)
internal
returns (
uint256,
uint256[] memory,
uint256,
uint256
)
{
(uint256 lastJoinExitAmp, uint256 lastPostJoinExitInvariant) = getLastJoinExitData();
(
uint256 preJoinExitSupply,
uint256[] memory balances,
uint256 oldAmpPreJoinExitInvariant
) = _payProtocolFeesBeforeJoinExit(registeredBalances, lastJoinExitAmp, lastPostJoinExitInvariant);
(uint256 currentAmp, ) = _getAmplificationParameter();
uint256 preJoinExitInvariant = currentAmp == lastJoinExitAmp
? oldAmpPreJoinExitInvariant
: StableMath._calculateInvariant(currentAmp, balances);
return (preJoinExitSupply, balances, currentAmp, preJoinExitInvariant);
}
| 4,901,440
|
./full_match/1001/0xfCCf3d314806a76D405c31F45188a7A5393C119a/sources/_klaytn/contracts/KIP/token/KIP7/KIP7.sol
|
Same as {xref-KIP7-safeTransfer-address-uint256-}[`safeTransfer`], with an additional `_data` parameter which is forwarded in {IKIP7Receiver-onKIP7Received} to contract recipients. Emits a {Transfer} event/
|
function safeTransfer(
address recipient,
uint256 amount,
bytes memory _data
) public virtual override {
address owner = _msgSender();
_safeTransfer(owner, recipient, amount, _data);
}
| 16,364,092
|
./full_match/3/0xDB16AB107b4A72030fc0D7eaA5Cd4362480FD294/sources/contracts/ARTWi.sol
|
Actually perform the safeTransferFrom. _from The current owner of the NFT. _to The new owner. _tokenId The NFT to transfer. _data Additional data with no specified format, sent in call to `_to`./
|
function _safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
private
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(_from == tokenOwner, "Token not owned by given address");
require(_to != address(0), ZERO_ADDRESS);
_transfer(_to, _tokenId);
if (_to.isContract())
{
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT);
}
}
| 8,092,814
|
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;
import "./CannonState.sol";
import "./TicketFactory.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title Nifty Cannon
* @author Cliff Hall
* @notice Allows direct or deferred transfer of NFTs from one sender to one or more recipients.
* TODO: disallow volleys targeting of addresses behind Rampart
*/
contract Cannon is TicketFactory {
using SafeMath for uint256;
/**
* @notice Event emitted upon successful storage of a will-call volley.
* @param sender the sender of the volley
* @param recipient the recipient of the volley
* @param tokenContract the token contract that minted the NFTs
* @param tokenIds the ids of NFTs that were transferred
*/
event VolleyStored(address indexed sender, address indexed recipient, address tokenContract, uint256[] tokenIds);
/**
* @notice Event emitted upon successful transfer of a volley, via airdrop or pickup of a will-call.
* @param sender the sender of the volley
* @param recipient the recipient of the volley
* @param tokenContract the token contract that minted the NFTs
* @param tokenIds the ids of NFTs to be transferred
*/
event VolleyTransferred(address indexed sender, address indexed recipient, address tokenContract, uint256[] tokenIds);
/**
* @notice Event emitted upon successful storage and ticketing of a volley,
* @param sender the sender of the volley
* @param recipient the recipient of the ticket
* @param ticketId the id of the transferable ticket
* @param tokenContract the token contract that minted the NFTs
* @param tokenIds the ids of NFTs to be transferred
*/
event VolleyTicketed(address indexed sender, address indexed recipient, uint256 indexed ticketId, address tokenContract, uint256[] tokenIds);
/**
* @notice Process a Volley
* This is the Cannon's central transfer mechanism.
* It has two operating modes: Airdrop and Will-call.
* In Airdrop mode, all of the NFTs in the Volley will be transferred to the recipient, sender paying gas.
* In Will-call mode, the volley will be stored, to be later executed by the recipient, who pays the gas.
* This contract must already be approved as an operator for the NFTs specified in the Volley.
* @param _volley a valid Volley struct
*/
function processVolley(Volley memory _volley) internal returns (bool success) {
// Destructure volley props for simplicity
Mode mode = _volley.mode;
address sender = _volley.sender;
address recipient = _volley.recipient;
IERC721 tokenContract = IERC721(_volley.tokenContract);
// Ensure this contract is an approved operator for the NFTs
require(tokenContract.isApprovedForAll(sender, address(this)), "Nifty Cannon not approved to transfer sender's NFT's" );
// Handle the volley
if (mode == Mode.AIRDROP) {
// Iterate over the NFTs to be transferred
for (uint256 index = 0; index < _volley.tokenIds.length; index++) {
// Get the current token id
uint256 nft = _volley.tokenIds[index];
// Sender pays gas to transfer token directly to recipient wallet
tokenContract.safeTransferFrom(sender, recipient, nft);
}
// Emit VolleyTransferred event
emit VolleyTransferred(sender, recipient, _volley.tokenContract, _volley.tokenIds);
} else if (mode == Mode.WILLCALL) {
// Store the volley for the recipient to pickup later
willCallVolleys[recipient].push(_volley);
// Emit VolleyTransferred event
emit VolleyStored(sender, recipient, _volley.tokenContract, _volley.tokenIds);
} else if (mode == Mode.TICKET) {
// Mint a transferable ticket
uint256 ticketId = mintTicket(recipient);
Ticket memory ticket = Ticket(_volley.sender, _volley.tokenContract, ticketId, _volley.tokenIds);
transferableTickets[ticketId] = ticket;
// Emit VolleyTicketed event
emit VolleyTicketed(sender, recipient, ticketId, _volley.tokenContract, _volley.tokenIds);
}
return true;
}
/**
* @notice Pick up a Volley
* There must be one or more Volleys awaiting the recipient
* This contract must already be approved as an operator for the NFTs specified in the Volley.
* @param _index the index of the volley in the recipient's list of will-call volleys
*/
function pickupVolley(uint256 _index) internal returns (bool success) {
// Verify there are one or more waiting volleys and the specified index is valid
uint256 length = willCallVolleys[msg.sender].length;
require(length > 0, "Caller has no volleys to accept.");
require(_index < length, "Volley index out of bounds.");
// Get the volley and mark it as AIRDROP mode so it will transfer when processed
Volley memory volley = willCallVolleys[msg.sender][_index];
volley.mode = Mode.AIRDROP;
require(msg.sender == volley.recipient, "Caller not recipient.");
// If not the last, replace the current volley with the last volley and pop the array
if (length != _index + 1) {
willCallVolleys[msg.sender][_index] = willCallVolleys[msg.sender][--length];
}
willCallVolleys[msg.sender].pop();
// Process the volley
require(processVolley(volley), "Volley failed");
success = true;
}
/**
* @notice Pick up a transferable volley
* The caller must own the given ticket (an NFT)
* This contract must already be approved as an operator for the NFTs specified in the Volley.
* @param _ticketId the id of the transferable ticket
*/
function pickupTicket(uint256 _ticketId) internal returns (bool success) {
// Verify that the ticket exists and hasn't been claimed
require(_ticketId < nextTicketNumber, "Invalid ticket id.");
require(_exists(_ticketId), "Ticket has already been claimed.");
// Verify that caller is the holder of the ticket
require(msg.sender == ownerOf(_ticketId), "Caller is not the owner of the ticket.");
// Create volley from the ticket
// 1. mark it as AIRDROP mode so it will transfer when processed
// 2. set recipient to caller
Volley memory volley;
volley.mode = Mode.AIRDROP;
volley.sender = transferableTickets[_ticketId].sender;
volley.recipient = msg.sender;
volley.tokenContract = transferableTickets[_ticketId].tokenContract;
volley.tokenIds = transferableTickets[_ticketId].tokenIds;
// Burn the ticket
burnTicket(_ticketId);
// Process the volley
require(processVolley(volley), "Volley failed");
success = true;
}
/**
* @notice Fire a single Volley
* This contract must already be approved as an operator for the NFTs specified in the Volley.
* @param _volley a valid Volley struct
*/
function fireVolley(Volley memory _volley) external {
require(processVolley(_volley), "Volley failed");
}
/**
* @notice Fire multiple Volleys
* This contract must already be approved as an operator for the NFTs specified in the Volleys.
* @param _volleys an array of valid Volley structs
*/
function fireVolleys(Volley[] memory _volleys) external {
for (uint256 index = 0; index < _volleys.length; index++) {
Volley memory volley = _volleys[index];
require(processVolley(volley), "Volley failed");
}
}
/**
* @notice Claim a specific Volley awaiting the caller
* There must be one or more Volleys awaiting the recipient
* This contract must already be approved as an operator for the NFTs specified in the Volley.
* @param _index the index of the volley in the recipient's list of will-call volleys
*/
function claimVolley(uint256 _index) external {
// Pick up the specified volley
require(pickupVolley(_index), "Will call pickupVolley failed");
}
/**
* @notice Claim all Volleys awaiting the caller
* There must be one or more Volleys awaiting the caller
* This contract must already be approved as an operator for the NFTs specified in the Volley.
*/
function claimAllVolleys() external {
// Get the first volley and process it, looping until all volleys are picked up
while(willCallVolleys[msg.sender].length > 0) {
require(pickupVolley(0), "Will call pickupVolley failed");
}
}
/**
* @notice Receive a specific Volley awaiting the caller
* There must be one or more Volleys awaiting the recipient
* This contract must already be approved as an operator for the NFTs specified in the Volley.
* @param _ticketId the id of the transferable ticket
*/
function claimTicket(uint256 _ticketId) external {
// Claim the specified ticket
require(pickupTicket(_ticketId), "Ticket claim failed");
}
/**
* @notice Claim all Tickets the caller owns
* Caller must own one or more Tickets
* This contract must already be approved as an operator for the NFTs specified in the Volley.
*/
function claimAllTickets() external {
// Caller must own at least one ticket
require(balanceOf(msg.sender) > 0, "Caller owns no tickets");
// Get the first ticket and process it, looping until all volleys are picked up
while(balanceOf(msg.sender) > 0) {
require(pickupTicket(tokenOfOwnerByIndex(msg.sender, 0)), "Ticket claim failed");
}
}
/**
* @notice Check combined count of Will-call Volleys and Tickets
* @return count the total number of volleys and tickets awaiting the caller
*/
function myWillCallCount() public view returns (uint256 count) {
uint256 volleyCount = willCallVolleys[msg.sender].length;
uint256 ticketCount = balanceOf(msg.sender);
count = volleyCount.add(ticketCount);
}
/**
* @notice Get the caller's will-call volleys
* @return tickets the volleys awaiting the caller
*/
function myVolleys() public view returns (Volley[] memory) {
uint256 volleyCount = willCallVolleys[msg.sender].length;
Volley[] memory volleys = new Volley[](volleyCount);
if (volleyCount > 0) {
for (uint256 i = 0; i < volleyCount; i++) {
Volley memory volley = willCallVolleys[msg.sender][i];
volleys[i] = volley;
}
}
return volleys;
}
/**
* @notice Get the caller's transferable tickets
* @return tickets the tickets awaiting the caller
*/
function myTickets() public view returns (Ticket[] memory) {
uint256 ticketCount = balanceOf(msg.sender);
Ticket[] memory tickets = new Ticket[](ticketCount);
if (ticketCount > 0) {
for (uint256 i = 0; i < ticketCount; i++) {
uint256 ticketId = tokenOfOwnerByIndex(msg.sender, i);
Ticket memory ticket = transferableTickets[ticketId];
tickets[i] = ticket;
}
}
return tickets;
}
}
|
Pick up a Volley There must be one or more Volleys awaiting the recipient This contract must already be approved as an operator for the NFTs specified in the Volley. _index the index of the volley in the recipient's list of will-call volleys/ Verify there are one or more waiting volleys and the specified index is valid Get the volley and mark it as AIRDROP mode so it will transfer when processed If not the last, replace the current volley with the last volley and pop the array
|
function pickupVolley(uint256 _index) internal returns (bool success) {
uint256 length = willCallVolleys[msg.sender].length;
require(length > 0, "Caller has no volleys to accept.");
require(_index < length, "Volley index out of bounds.");
Volley memory volley = willCallVolleys[msg.sender][_index];
volley.mode = Mode.AIRDROP;
require(msg.sender == volley.recipient, "Caller not recipient.");
if (length != _index + 1) {
willCallVolleys[msg.sender][_index] = willCallVolleys[msg.sender][--length];
}
willCallVolleys[msg.sender].pop();
success = true;
}
| 1,069,496
|
./full_match/43113/0xd177045390B445227d8743313b0d19f8ca9ec409/sources/chainlink/v0.7/vendor/BufferChainlink.sol
|
Writes a byte string to a buffer. Resizes if doing so would exceed the capacity of the buffer. buf The buffer to append to. off The start offset to write to. data The data to append. len The number of bytes to copy. return The original buffer, for chaining./ Memory address of the buffer data Length of existing buffer data Start address = buffer address + offset + sizeof(buffer length) Update buffer length if we're extending it Copy word-length chunks while possible
|
function write(
buffer memory buf,
uint256 off,
bytes memory data,
uint256 len
) internal pure returns (buffer memory) {
require(len <= data.length);
if (off + len > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint256 dest;
uint256 src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
src := add(data, 32)
}
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))
}
return buf;
}
| 7,163,214
|
./full_match/5/0x5A5C7810444C6B392ACb012F79bCDa167F5470e1/sources/project_/contracts/ERC721MetaProxy.sol
|
Convert the metadata struct to JSON
|
function _getTokenMetaJsonBase64(
address tokenContract,
uint256 tokenId
) internal view returns (string memory) {
TokenMeta memory meta = getTokenMeta(tokenContract, tokenId);
string memory json = string(
abi.encodePacked(
'{"name":"',
meta.name,
'",',
'"description":"',
meta.description,
'",',
'"image":"',
meta.image,
'",',
'"external_url":"',
meta.external_url,
'",',
'"attributes":',
meta.attributes,
"}"
)
);
string memory base64Json = string(
abi.encodePacked(
bytes("data:application/json;base64,"),
bytes(Base64.encode(jsonBytes))
)
);
return base64Json;
}
| 11,596,238
|
pragma solidity ^0.4.11;
// ----------------------------------------------------------------------------
// Abab.io preICO
// The MIT Licence
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths, borrowed from OpenZeppelin
// ----------------------------------------------------------------------------
library SafeMath {
// ------------------------------------------------------------------------
// Add a number to another number, checking for overflows
// ------------------------------------------------------------------------
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
// ------------------------------------------------------------------------
// Subtract a number from another number, checking for underflows
// ------------------------------------------------------------------------
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address _newOwner) onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() {
if (msg.sender == newOwner) {
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals
// https://github.com/ethereum/EIPs/issues/20
// ----------------------------------------------------------------------------
contract ERC20Token is Owned {
using SafeMath for uint;
// ------------------------------------------------------------------------
// Total Supply
// ------------------------------------------------------------------------
uint256 _totalSupply = 0;
// ------------------------------------------------------------------------
// Balances for each account
// ------------------------------------------------------------------------
mapping(address => uint256) balances;
// ------------------------------------------------------------------------
// Owner of account approves the transfer of an amount to another account
// ------------------------------------------------------------------------
mapping(address => mapping (address => uint256)) allowed;
// ------------------------------------------------------------------------
// Get the total token supply
// ------------------------------------------------------------------------
function totalSupply() constant returns (uint256 totalSupply) {
totalSupply = _totalSupply;
}
// ------------------------------------------------------------------------
// Get the account balance of another account with address _owner
// ------------------------------------------------------------------------
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
// ------------------------------------------------------------------------
// Transfer the balance from owner's account to another account
// ------------------------------------------------------------------------
function transfer(address _to, uint256 _amount) returns (bool success) {
if (balances[msg.sender] >= _amount // User has balance
&& _amount > 0 // Non-zero transfer
&& balances[_to] + _amount > balances[_to] // Overflow check
) {
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
// ------------------------------------------------------------------------
// Allow _spender to withdraw from your account, multiple times, up to the
// _value amount. If this function is called again it overwrites the
// current allowance with _value.
// ------------------------------------------------------------------------
function approve(
address _spender,
uint256 _amount
) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
// ------------------------------------------------------------------------
// Spender of tokens transfer an amount of tokens from the token owner's
// balance to the spender's account. The owner of the tokens must already
// have approve(...)-d this transfer
// ------------------------------------------------------------------------
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
if (balances[_from] >= _amount // From a/c has balance
&& allowed[_from][msg.sender] >= _amount // Transfer approved
&& _amount > 0 // Non-zero transfer
&& balances[_to] + _amount > balances[_to] // Overflow check
) {
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(
address _owner,
address _spender
) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender,
uint256 _value);
}
contract AbabPreICOToken is ERC20Token {
// ------------------------------------------------------------------------
// Token information
// ------------------------------------------------------------------------
string public constant symbol = "pAA";
string public constant name = "AbabPreICOToken";
uint8 public constant decimals = 18;
uint256 public STARTDATE;
uint256 public ENDDATE;
uint256 public BUYPRICE;
uint256 public CAP;
function AbabPreICOToken() {
STARTDATE = 1499951593; // 2017-07-13T13:13:13UTC to uint256 = 1499951593
ENDDATE = 1500815593; // 2017-07-23T13:13:13UTC to uint256 = 1500815593
BUYPRICE = 4000; // in eth will actualize before start. calc $0.05 @ $200 ETH/USD // 4000 pAA per ETH
CAP = 2500*1 ether; // in eth ($500K / 0.05 ) / etherPrice
}
function ActualizePriceBeforeStart(uint256 _start, uint256 _end, uint256 _buyPrice, uint256 _cap)
onlyOwner returns (bool success)
{
require(now < STARTDATE);
STARTDATE = _start;
ENDDATE = _end;
BUYPRICE = _buyPrice;
CAP = _cap;
return true;
}
uint256 public totalEthers;
// ------------------------------------------------------------------------
// Buy tokens from the contract
// ------------------------------------------------------------------------
function () payable {
// No contributions before the start of the crowdsale
require(now >= STARTDATE);
// No contributions after the end of the crowdsale
require(now <= ENDDATE);
// No 0 contributions
require(msg.value > 0);
// Add ETH raised to total
totalEthers = totalEthers.add(msg.value);
// Cannot exceed cap
require(totalEthers <= CAP);
uint tokens = msg.value * BUYPRICE;
// Check tokens > 0
require(tokens > 0);
// Add to total supply
_totalSupply = _totalSupply.add(tokens);
// Add to balances
balances[msg.sender] = balances[msg.sender].add(tokens);
// Log events
Transfer(0x0, msg.sender, tokens);
// Move the funds to a safe wallet
owner.transfer(msg.value);
}
// ------------------------------------------------------------------------
// Transfer the balance from owner's account to another account, with a
// check that the crowdsale is finalised
// ------------------------------------------------------------------------
function transfer(address _to, uint _amount) returns (bool success) {
// Cannot transfer before crowdsale ends or cap reached
require(now > ENDDATE || totalEthers == CAP);
// Standard transfer
return super.transfer(_to, _amount);
}
// ------------------------------------------------------------------------
// Spender of tokens transfer an amount of tokens from the token owner's
// balance to another account, with a check that the crowdsale is
// finalised
// ------------------------------------------------------------------------
function transferFrom(address _from, address _to, uint _amount)
returns (bool success)
{
// Cannot transfer before crowdsale ends or cap reached
require(now > ENDDATE || totalEthers == CAP);
// Standard transferFrom
return super.transferFrom(_from, _to, _amount);
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint amount)
onlyOwner returns (bool success)
{
return ERC20Token(tokenAddress).transfer(owner, amount);
}
}
|
------------------------------------------------------------------------ Allow _spender to withdraw from your account, multiple times, up to the _value amount. If this function is called again it overwrites the current allowance with _value. ------------------------------------------------------------------------
|
function approve(
address _spender,
uint256 _amount
) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
| 1,002,725
|
pragma solidity 0.5.10;
import 'openzeppelin-eth/contracts/ownership/Ownable.sol';
import './MixinDisableAndDestroy.sol';
import '../interfaces/IUnlock.sol';
import './MixinFunds.sol';
/**
* @title Mixin for core lock data and functions.
* @author HardlyDifficult
* @dev `Mixins` are a design pattern seen in the 0x contracts. It simply
* separates logically groupings of code to ease readability.
*/
contract MixinLockCore is
Ownable,
MixinFunds,
MixinDisableAndDestroy
{
event PriceChanged(
uint oldKeyPrice,
uint keyPrice
);
event Withdrawal(
address indexed sender,
address indexed tokenAddress,
address indexed beneficiary,
uint amount
);
// Unlock Protocol address
// TODO: should we make that private/internal?
IUnlock public unlockProtocol;
// Duration in seconds for which the keys are valid, after creation
// should we take a smaller type use less gas?
// TODO: add support for a timestamp instead of duration
uint public expirationDuration;
// price in wei of the next key
// TODO: allow support for a keyPriceCalculator which could set prices dynamically
uint public keyPrice;
// Max number of keys sold if the keyReleaseMechanism is public
uint public maxNumberOfKeys;
// A count of how many new key purchases there have been
uint public totalSupply;
// The account which will receive funds on withdrawal
address public beneficiary;
// Ensure that the Lock has not sold all of its keys.
modifier notSoldOut() {
require(maxNumberOfKeys > totalSupply, 'LOCK_SOLD_OUT');
_;
}
modifier onlyOwnerOrBeneficiary()
{
require(
msg.sender == owner() || msg.sender == beneficiary,
'ONLY_LOCK_OWNER_OR_BENEFICIARY'
);
_;
}
constructor(
address _beneficiary,
uint _expirationDuration,
uint _keyPrice,
uint _maxNumberOfKeys
) internal
{
require(_expirationDuration <= 100 * 365 * 24 * 60 * 60, 'MAX_EXPIRATION_100_YEARS');
unlockProtocol = IUnlock(msg.sender); // Make sure we link back to Unlock's smart contract.
beneficiary = _beneficiary;
expirationDuration = _expirationDuration;
keyPrice = _keyPrice;
maxNumberOfKeys = _maxNumberOfKeys;
}
/**
* @dev Called by owner to withdraw all funds from the lock and send them to the `beneficiary`.
* @param _tokenAddress specifies the token address to withdraw or 0 for ETH. This is usually
* the same as `tokenAddress` in MixinFunds.
* @param _amount specifies the max amount to withdraw, which may be reduced when
* considering the available balance. Set to 0 or MAX_UINT to withdraw everything.
*
* TODO: consider allowing anybody to trigger this as long as it goes to owner anyway?
* -- however be wary of draining funds as it breaks the `cancelAndRefund` use case.
*/
function withdraw(
address _tokenAddress,
uint _amount
) external
onlyOwnerOrBeneficiary
{
uint balance = getBalance(_tokenAddress, address(this));
uint amount;
if(_amount == 0 || _amount > balance)
{
require(balance > 0, 'NOT_ENOUGH_FUNDS');
amount = balance;
}
else
{
amount = _amount;
}
emit Withdrawal(msg.sender, _tokenAddress, beneficiary, amount);
// Security: re-entrancy not a risk as this is the last line of an external function
_transfer(_tokenAddress, beneficiary, amount);
}
/**
* A function which lets the owner of the lock to change the price for future purchases.
*/
function updateKeyPrice(
uint _keyPrice
)
external
onlyOwner
onlyIfAlive
{
uint oldKeyPrice = keyPrice;
keyPrice = _keyPrice;
emit PriceChanged(oldKeyPrice, keyPrice);
}
/**
* A function which lets the owner of the lock update the beneficiary account,
* which receives funds on withdrawal.
*/
function updateBeneficiary(
address _beneficiary
) external
onlyOwnerOrBeneficiary
{
require(_beneficiary != address(0), 'INVALID_ADDRESS');
beneficiary = _beneficiary;
}
}
|
A function which lets the owner of the lock update the beneficiary account, which receives funds on withdrawal./
|
function updateBeneficiary(
address _beneficiary
) external
onlyOwnerOrBeneficiary
{
require(_beneficiary != address(0), 'INVALID_ADDRESS');
beneficiary = _beneficiary;
}
| 5,532,517
|
/*
Consumer
https://github.com/devinaconley/token-hold-example
SPDX-License-Identifier: MIT
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./IERC721Holder.sol";
/**
* @title Consumer
*
* @notice this contract implements an example "consumer" of the proposed
* held token ERC standard.
* This example consumer contract will query ERC721 ownership and balances
* including any "held" tokens
*/
contract Consumer {
using Address for address;
// members
IERC721 public token;
/**
* @param token_ address of ERC721 token
*/
constructor(address token_) {
token = IERC721(token_);
}
/**
* @notice get the functional owner of a token
* @param tokenId token id of interest
*/
function getOwner(uint256 tokenId) external view returns (address) {
// get raw owner
address owner = token.ownerOf(tokenId);
// if owner is not contract, return
if (!owner.isContract()) {
return owner;
}
try IERC165(owner).supportsInterface(0x16b900ff) returns (bool ret) {
// contract does not support token holder interface
if (!ret) {
return owner;
}
} catch {
return owner;
}
// check for held owner
address addr = IERC721Holder(owner).heldOwnerOf(address(token), tokenId);
if (addr == address(0)) {
return owner;
}
return addr;
}
/**
* @notice get the total user balance including held tokens
* @param owner user address
* @param holders list of token holder addresses
*/
function getBalance(address owner, address[] calldata holders)
external
view
returns (uint256)
{
// start with raw token balance
uint256 balance = token.balanceOf(owner);
// consider each provided token holder contract
for (uint256 i = 0; i < holders.length; i++) {
balance += IERC721Holder(holders[i]).heldBalanceOf(address(token), owner);
}
return balance;
}
}
|
get the functional owner of a token tokenId token id of interest/ get raw owner if owner is not contract, return contract does not support token holder interface
|
function getOwner(uint256 tokenId) external view returns (address) {
address owner = token.ownerOf(tokenId);
if (!owner.isContract()) {
return owner;
}
try IERC165(owner).supportsInterface(0x16b900ff) returns (bool ret) {
if (!ret) {
return owner;
}
return owner;
}
if (addr == address(0)) {
return owner;
}
return addr;
}
| 12,636,270
|
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/crowdsale/validation/CappedCrowdsale.sol";
import "openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./Pausable.sol";
import "./GoodLifeToken.sol";
import "./roles/MerchantRole.sol";
/*
* This contract implemnts a sale of the "Good Life Token". Since the contract inherited from the MintedCrowdsale contract
* only ERC20Mintable tokens can be sold by {GLTMerchantSale}.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract GLTMerchantSale is MintedCrowdsale, Ownable, MerchantRole, Pausable {
using SafeMath for uint256;
uint256 private _weiRaised;
uint256 private _EURCentWeiRate;
address payable private _owner;
GoodLifeToken private _token;
bool private stopped = false;
/*
* Constructor
* @param rate The conversion rate for WEI in EUR cent
* @param wallet The Ethereum address from which the tokens should be minted
* @param token The ERC20Mintable token which will be minted and sold by this MintedCrowdsale
*/
constructor (
uint256 rate,
address payable wallet,
//ERC20Mintable token
GoodLifeToken token
)
public
Crowdsale(rate, wallet, token) {
_EURCentWeiRate = rate;
_weiRaised = 0;
_owner = msg.sender;
_token = token;
}
//Emits an event if a token was purchased
event TokensPurchased (address indexed account, address beneficiary, uint256 amountOfTokens);
event WeiRaised (uint256 weiRaised, uint256 weiAmount);
modifier isAdmin() {
require(msg.sender == _owner);
_;
}
modifier stopInEmergency { if (!stopped) _; }
modifier onlyInEmergency { if (stopped) _; }
function amountOfETHInEUR(uint amountInEUR) internal pure returns (uint256) {
// returns $0.01 ETH wei
// For test and main net
//uint256 ethCentInWei = price.EUR(0);
uint ethCentInWei = 50000000000000;
return ethCentInWei.mul(amountInEUR).mul(100);
}
/**
* Returns the amount of tokens based on the provided amount of EUR.
* @param amountInEUR The amount in EUR currency that should be returned in amount of tokens.
* return The amount of tokens
*/
function getTokenAmount(uint256 amountInEUR, uint rateETHEUR) public view returns(uint256) {
if(rateETHEUR > 0) {
uint rateETHTokens = 15000;
return (rateETHTokens).div(rateETHEUR).mul(amountInEUR);
} else {
//multiply 'provided amountInEUR * WEI in EURCent * 100 Cent
//uint256 weiAmount = amountInEUR * 50000000000000 * 100;
uint256 weiAmount = amountInEUR.mul(50000000000000).mul(100);
return weiAmount.div(_EURCentWeiRate);
}
}
/*
* Returns the the number of weis for this GLTMerchantSale instance.
*/
function weiRaised() public view returns(uint256) {
//emit WeiRaised(_weiRaised);
return _weiRaised;
}
/**
* @dev low level token purchase
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
*
* Emits a {TokensPurchased} event.
*
* @param beneficiary Recipient of the token purchase
* @param amountInEUR Amount of EUR the tokens should be purchased for
*/
function buyTokens(address beneficiary, uint256 amountInEUR, uint rateETHEUR) public
whenNotPaused
nonReentrant
onlyOwner
stopInEmergency
onlyMerchant
payable
returns(uint256) {
uint256 weiAmount = amountOfETHInEUR(amountInEUR);
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = getTokenAmount(amountInEUR, rateETHEUR);
// update state
_weiRaised = _weiRaised.add(weiAmount);
emit WeiRaised(_weiRaised, weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(msg.sender, beneficiary, tokens);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
return tokens;
}
}
|
low level token purchase This function has a non-reentrancy guard, so it shouldn't be called by another `nonReentrant` function. Emits a {TokensPurchased} event. beneficiary Recipient of the token purchase amountInEUR Amount of EUR the tokens should be purchased for/ calculate token amount to be created update state
|
function buyTokens(address beneficiary, uint256 amountInEUR, uint rateETHEUR) public
whenNotPaused
nonReentrant
onlyOwner
stopInEmergency
onlyMerchant
payable
returns(uint256) {
uint256 weiAmount = amountOfETHInEUR(amountInEUR);
_preValidatePurchase(beneficiary, weiAmount);
uint256 tokens = getTokenAmount(amountInEUR, rateETHEUR);
_weiRaised = _weiRaised.add(weiAmount);
emit WeiRaised(_weiRaised, weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(msg.sender, beneficiary, tokens);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
return tokens;
}
| 12,787,013
|
./partial_match/1/0x72AD58f0917deB04eC8b6AdA584ABd0dBe502128/sources/StrategyQueue.sol
|
Add a strategy to the end of the queue _strategy address of strategy to add creates a new node which is inserted at the end of the strategy queue. the strategy is assigned an id and is linked to the previous tail. Note that this ID isnt necessarily the same as the position in the withdrawal queue
|
function _push(address _strategy) internal returns (uint256) {
if (strategyId[_strategy] > 0) revert StrategyExists(_strategy);
uint48 nodeId = _createNode(_strategy);
return uint256(nodeId);
}
| 3,586,922
|
/**
*Submitted for verification at Etherscan.io on 2022-04-03
*/
/**
*Submitted for verification at Etherscan.io on 2022-02-22
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
// File @openzeppelin/contracts/utils/[email protected]
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
/**
* @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 whiteed 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 whiteed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts/utils/[email protected]
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is whiteed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
/**
* @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 whites for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File @openzeppelin/contracts/utils/math/[email protected]
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_
) {
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
function walletOfOwner(address owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
uint256[] memory tokenIds = new uint256[](tokenCount);
if (tokenCount == 0)
{
return tokenIds;
}
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
tokenIds[tokenIdsIdx] = i;
tokenIdsIdx++;
if (tokenIdsIdx == tokenCount) {
return tokenIds;
}
}
}
revert("ERC721A: unable to get walletOfOwner");
}
/**
* @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 ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
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 override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: 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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
contract SLIMYS is ERC721A, Ownable {
constructor() ERC721A("SLIMYS", "S",20) {}
using SafeMath for uint256;
using Strings for uint256;
string private baseURI;
string private blindURI;
uint256 public constant BUY_LIMIT_PER_TX = 20;
uint256 public MAX_NFT_PUBLIC = 4444;
uint256 private constant MAX_NFT = 4444;
uint256 public NFTPrice = 190000000000000000; // 0.19 ETH
uint256 public NFTPriceBundle = 360000000000000000; // 0.36 ETH
bool public reveal;
bool public isActive;
bool public isPresaleActive;
bool public freeMintActive;
bytes32 public root;
uint256 public WHITELIST_MAX_MINT = 2;
mapping(address => uint256) public whiteListClaimed;
mapping(address => bool) private giveawayMintClaimed;
/*
* Function to reveal all Slimmies
*/
function revealNow()
external
onlyOwner
{
reveal = true;
}
/*
* Function setIsActive to activate/desactivate the smart contract
*/
function setIsActive(
bool _isActive
)
external
onlyOwner
{
isActive = _isActive;
}
/*
* Function setPresaleActive to activate/desactivate the whitelist/raffle presale
*/
function setPresaleActive(
bool _isActive
)
external
onlyOwner
{
isPresaleActive = _isActive;
}
/*
* Function setFreeMintActive to activate/desactivate the free mint capability
*/
function setFreeMintActive(
bool _isActive
)
external
onlyOwner
{
freeMintActive = _isActive;
}
/*
* Function to set Base and Blind URI
*/
function setURIs(
string memory _blindURI,
string memory _URI
)
external
onlyOwner
{
blindURI = _blindURI;
baseURI = _URI;
}
/*
* Function to set NFT Price
*/
function setNFTPrice(uint256 _price) external onlyOwner {
NFTPrice = _price;
}
/*
* Function to set Max NFT
*/
function setNFTmax(uint256 max) external onlyOwner {
MAX_NFT_PUBLIC = max;
}
/*
* Function to withdraw collected amount during minting by the owner
*/
function withdraw(
)
public
onlyOwner
{
uint balance = address(this).balance;
require(balance > 0, "Balance should be more then zero");
address[11] memory _team = [
0xc224301674c3fca16383f5D1F36A08e7048e4d1C,
0xe70bB226F09399407C6e59a058BEAF34e785BB75, //50% until X NFT sold
0x88132cD837e8E952Cc38c6f71E6969C6E83D1Ffb, //50% until X NFT sold
0xC89E9ecF1B2900656ECba77E1Da89600f187A50D,
0xBC3F581C6B540447D61a788B4547C66A45584097,
0x5Bca3d2c54f7cEAB7f0b8e3b05Adf46B016823fD,
0x23C625789c391463997267BDD8b21e5E266014F6,
0x73b4953783087AfB8674a7a7eB082c3DEB31aFF5,
0x4335d2Bf93309701065961e359eEd999eD2B1Ea9,
0xCeC07E954f81224414Ac0a79249fd64577a0B727,
0x6a4AE2E404d7D2EB663079b449b2Cf497c97335F
];
uint32[11] memory _teamShares = [
uint32(485),
uint32(160),
uint32(160),
uint32(30),
uint32(10),
uint32(10),
uint32(15),
uint32(10),
uint32(30),
uint32(50),
uint32(40)
];
for(uint256 i = 0; i < _team.length; i++){
payable(_team[i]).transfer((balance * _teamShares[i]) / 1000);
}
}
/*
* Function to withdraw collected amount during minting by the owner
*/
function withdrawTo(
address _to
)
public
onlyOwner
{
uint balance = address(this).balance;
require(balance > 0, "Balance should be more then zero");
payable(_to).transfer(balance);
}
/*
* Function to mint new NFTs during the public sale
* It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))
*/
function mintNFT(
uint256 _numOfTokens
)
public
payable
{
require(isActive, 'Contract is not active');
require(!isPresaleActive, 'Presale is still active');
require(_numOfTokens <= BUY_LIMIT_PER_TX, "Cannot mint above limit");
require(totalSupply().add(_numOfTokens) <= MAX_NFT_PUBLIC, "Purchase would exceed max public supply of NFTs");
require(NFTPrice.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
_safeMint(msg.sender, _numOfTokens);
}
/*
* Function to mint new NFTs during the presale
* It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))
*/
function mintNFTDuringPresale(
uint256 _numOfTokens,
bytes32[] memory _proof
)
public
payable
{
require(isActive, 'Sale is not active');
require(isPresaleActive, 'Whitelist is not active');
require(verify(_proof, bytes32(uint256(uint160(msg.sender)))), "Not whitelisted");
if (!freeMintActive){
require(totalSupply() < MAX_NFT_PUBLIC, 'All public tokens have been minted');
require(_numOfTokens <= WHITELIST_MAX_MINT, 'Cannot purchase this many tokens');
require(totalSupply().add(_numOfTokens) <= MAX_NFT_PUBLIC, 'Purchase would exceed max public supply of NFTs');
require(whiteListClaimed[msg.sender].add(_numOfTokens) <= WHITELIST_MAX_MINT, 'Purchase exceeds max whitelisted');
if(_numOfTokens==2){
require(NFTPriceBundle == msg.value, "Ether value sent is not correct");
}else{
require(NFTPrice.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
}
whiteListClaimed[msg.sender] += _numOfTokens;
_safeMint(msg.sender, _numOfTokens);
} else {
require(totalSupply() <= MAX_NFT, 'All tokens have been minted');
require(_numOfTokens == 1, 'Cannot purchase this many tokens');
require(!giveawayMintClaimed[msg.sender], 'Already claimed giveaway');
giveawayMintClaimed[msg.sender] = true;
_safeMint(msg.sender, _numOfTokens);
}
}
/*
* Function to mint NFTs for giveaway and partnerships
*/
function mintByOwner(
address _to,
uint256 _num
)
public
onlyOwner
{
require(totalSupply()+_num <= MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens");
_safeMint(_to, _num);
}
/*
* Function to mint all NFTs for giveaway and partnerships
*/
function mintMultipleByOwner(
address[] memory _to,
uint256 _num
)
public
onlyOwner
{
for(uint256 i = 0; i < _to.length; i++){
require(totalSupply()+_num <= MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens");
_safeMint(_to[i], _num);
}
}
/*
* Function to get token URI of given token ID
* URI will be blank untill totalSupply reaches MAX_NFT_PUBLIC
*/
function tokenURI(
uint256 _tokenId
)
public
view
virtual
override
returns (string memory)
{
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
if (!reveal) {
return string(abi.encodePacked(blindURI));
} else {
return string(abi.encodePacked(baseURI, _tokenId.toString()));
}
}
// Set Root for whitelist and raffle to participate in presale
function setRootAndMax(uint256 _root,uint256 _max) onlyOwner() public {
root = bytes32(_root);
WHITELIST_MAX_MINT = _max;
}
// Verify MerkleProof
function verify(bytes32[] memory proof, bytes32 leaf) public view returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = sha256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = sha256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
|
Function to mint all NFTs for giveaway and partnerships/
|
function mintMultipleByOwner(
address[] memory _to,
uint256 _num
)
public
onlyOwner
{
for(uint256 i = 0; i < _to.length; i++){
require(totalSupply()+_num <= MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens");
_safeMint(_to[i], _num);
}
}
| 10,946,445
|
./partial_match/1/0x4eDA33EA48052006850966Fc1182CF46F325501d/sources/SquidFarmer.sol
|
send referral eggsboost market to nerf squid hoarding
|
function hatchEggs(address ref) public {
require(initialized);
if (ref != address(0)) referrals[msg.sender] = ref;
uint256 eggsUsed = getMyEggs(msg.sender);
hatcherySquid[msg.sender] = SafeMath.add(hatcherySquid[msg.sender], eggsUsed);
claimedEggs[msg.sender] = 0;
lastHatch[msg.sender] = now;
claimedEggs[referrals[msg.sender]] = SafeMath.add(claimedEggs[referrals[msg.sender]], SafeMath.div(eggsUsed, 15));
marketEggs = SafeMath.add(marketEggs,SafeMath.div(eggsUsed, 10));
}
| 2,773,760
|
./full_match/5/0x2e89601fAE0fe0690e7C8cAC0c1C43a2cE48F356/sources/src/Mintpass.sol
|
Mark the token as revoked tokenId Identifier of the token
|
function revoke(uint256 tokenId) external onlyOwner {
require(isValid(tokenId), "Token is already invalid");
_revocations[tokenId] = true;
emit Revoked(tokenId);
}
| 11,629,064
|
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.2;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/lib/AddressArrayUtils.sol
// Pulled in from Cryptofin Solidity package in order to control Solidity compiler version
// https://github.com/cryptofinlabs/cryptofin-solidity/blob/master/contracts/array-utils/AddressArrayUtils.sol
pragma solidity 0.5.7;
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (0, false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
bool isIn;
(, isIn) = indexOf(A, a);
return isIn;
}
/// @return Returns index and isIn for the first occurrence starting from
/// end
function indexOfFromEnd(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = length; i > 0; i--) {
if (A[i - 1] == a) {
return (i, true);
}
}
return (0, false);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/**
* Returns the array with a appended to A.
* @param A The first array
* @param a The value to append
* @return Returns A appended by a
*/
function append(address[] memory A, address a) internal pure returns (address[] memory) {
address[] memory newAddresses = new address[](A.length + 1);
for (uint256 i = 0; i < A.length; i++) {
newAddresses[i] = A[i];
}
newAddresses[A.length] = a;
return newAddresses;
}
/**
* Returns the combination of two storage arrays.
* @param A The first array
* @param B The second array
* @return Returns A appended by a
*/
function sExtend(address[] storage A, address[] storage B) internal {
uint256 length = B.length;
for (uint256 i = 0; i < length; i++) {
A.push(B[i]);
}
}
/**
* Returns the intersection of two arrays. Arrays are treated as collections, so duplicates are kept.
* @param A The first array
* @param B The second array
* @return The intersection of the two arrays
*/
function intersect(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 length = A.length;
bool[] memory includeMap = new bool[](length);
uint256 newLength = 0;
for (uint256 i = 0; i < length; i++) {
if (contains(B, A[i])) {
includeMap[i] = true;
newLength++;
}
}
address[] memory newAddresses = new address[](newLength);
uint256 j = 0;
for (uint256 k = 0; k < length; k++) {
if (includeMap[k]) {
newAddresses[j] = A[k];
j++;
}
}
return newAddresses;
}
/**
* Returns the union of the two arrays. Order is not guaranteed.
* @param A The first array
* @param B The second array
* @return The union of the two arrays
*/
function union(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
address[] memory leftDifference = difference(A, B);
address[] memory rightDifference = difference(B, A);
address[] memory intersection = intersect(A, B);
return extend(leftDifference, extend(intersection, rightDifference));
}
/**
* Alternate implementation
* Assumes there are no duplicates
*/
function unionB(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
bool[] memory includeMap = new bool[](A.length + B.length);
uint256 count = 0;
for (uint256 i = 0; i < A.length; i++) {
includeMap[i] = true;
count++;
}
for (uint256 j = 0; j < B.length; j++) {
if (!contains(A, B[j])) {
includeMap[A.length + j] = true;
count++;
}
}
address[] memory newAddresses = new address[](count);
uint256 k = 0;
for (uint256 m = 0; m < A.length; m++) {
if (includeMap[m]) {
newAddresses[k] = A[m];
k++;
}
}
for (uint256 n = 0; n < B.length; n++) {
if (includeMap[A.length + n]) {
newAddresses[k] = B[n];
k++;
}
}
return newAddresses;
}
/**
* Computes the difference of two arrays. Assumes there are no duplicates.
* @param A The first array
* @param B The second array
* @return The difference of the two arrays
*/
function difference(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 length = A.length;
bool[] memory includeMap = new bool[](length);
uint256 count = 0;
// First count the new length because can't push for in-memory arrays
for (uint256 i = 0; i < length; i++) {
address e = A[i];
if (!contains(B, e)) {
includeMap[i] = true;
count++;
}
}
address[] memory newAddresses = new address[](count);
uint256 j = 0;
for (uint256 k = 0; k < length; k++) {
if (includeMap[k]) {
newAddresses[j] = A[k];
j++;
}
}
return newAddresses;
}
/**
* @dev Reverses storage array in place
*/
function sReverse(address[] storage A) internal {
address t;
uint256 length = A.length;
for (uint256 i = 0; i < length / 2; i++) {
t = A[i];
A[i] = A[A.length - i - 1];
A[A.length - i - 1] = t;
}
}
/**
* Removes specified index from array
* Resulting ordering is not guaranteed
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* @return Returns the new array
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert();
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
function sPop(address[] storage A, uint256 index) internal returns (address) {
uint256 length = A.length;
if (index >= length) {
revert("Error: index out of bounds");
}
address entry = A[index];
for (uint256 i = index; i < length - 1; i++) {
A[i] = A[i + 1];
}
A.length--;
return entry;
}
/**
* Deletes address at index and fills the spot with the last address.
* Order is not preserved.
* @return Returns the removed entry
*/
function sPopCheap(address[] storage A, uint256 index) internal returns (address) {
uint256 length = A.length;
if (index >= length) {
revert("Error: index out of bounds");
}
address entry = A[index];
if (index != length - 1) {
A[index] = A[length - 1];
delete A[length - 1];
}
A.length--;
return entry;
}
/**
* Deletes address at index. Works by swapping it with the last address, then deleting.
* Order is not preserved
* @param A Storage array to remove from
*/
function sRemoveCheap(address[] storage A, address a) internal {
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Error: entry not found");
} else {
sPopCheap(A, index);
return;
}
}
/**
* Returns whether or not there's a duplicate. Runs in O(n^2).
* @param A Array to search
* @return Returns true if duplicate, false otherwise
*/
function hasDuplicate(address[] memory A) internal pure returns (bool) {
if (A.length == 0) {
return false;
}
for (uint256 i = 0; i < A.length - 1; i++) {
for (uint256 j = i + 1; j < A.length; j++) {
if (A[i] == A[j]) {
return true;
}
}
}
return false;
}
/**
* Returns whether the two arrays are equal.
* @param A The first array
* @param B The second array
* @return True is the arrays are equal, false if not.
*/
function isEqual(address[] memory A, address[] memory B) internal pure returns (bool) {
if (A.length != B.length) {
return false;
}
for (uint256 i = 0; i < A.length; i++) {
if (A[i] != B[i]) {
return false;
}
}
return true;
}
/**
* Returns the elements indexed at indexArray.
* @param A The array to index
* @param indexArray The array to use to index
* @return Returns array containing elements indexed at indexArray
*/
function argGet(address[] memory A, uint256[] memory indexArray)
internal
pure
returns (address[] memory)
{
address[] memory array = new address[](indexArray.length);
for (uint256 i = 0; i < indexArray.length; i++) {
array[i] = A[indexArray[i]];
}
return array;
}
}
// File: contracts/lib/TimeLockUpgrade.sol
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title TimeLockUpgrade
* @author Set Protocol
*
* The TimeLockUpgrade contract contains a modifier for handling minimum time period updates
*/
contract TimeLockUpgrade is
Ownable
{
using SafeMath for uint256;
/* ============ State Variables ============ */
// Timelock Upgrade Period in seconds
uint256 public timeLockPeriod;
// Mapping of upgradable units and initialized timelock
mapping(bytes32 => uint256) public timeLockedUpgrades;
/* ============ Events ============ */
event UpgradeRegistered(
bytes32 _upgradeHash,
uint256 _timestamp
);
/* ============ Modifiers ============ */
modifier timeLockUpgrade() {
// If the time lock period is 0, then allow non-timebound upgrades.
// This is useful for initialization of the protocol and for testing.
if (timeLockPeriod == 0) {
_;
return;
}
// The upgrade hash is defined by the hash of the transaction call data,
// which uniquely identifies the function as well as the passed in arguments.
bytes32 upgradeHash = keccak256(
abi.encodePacked(
msg.data
)
);
uint256 registrationTime = timeLockedUpgrades[upgradeHash];
// If the upgrade hasn't been registered, register with the current time.
if (registrationTime == 0) {
timeLockedUpgrades[upgradeHash] = block.timestamp;
emit UpgradeRegistered(
upgradeHash,
block.timestamp
);
return;
}
require(
block.timestamp >= registrationTime.add(timeLockPeriod),
"TimeLockUpgrade: Time lock period must have elapsed."
);
// Reset the timestamp to 0
timeLockedUpgrades[upgradeHash] = 0;
// Run the rest of the upgrades
_;
}
/* ============ Function ============ */
/**
* Change timeLockPeriod period. Generally called after initially settings have been set up.
*
* @param _timeLockPeriod Time in seconds that upgrades need to be evaluated before execution
*/
function setTimeLockPeriod(
uint256 _timeLockPeriod
)
external
onlyOwner
{
// Only allow setting of the timeLockPeriod if the period is greater than the existing
require(
_timeLockPeriod > timeLockPeriod,
"TimeLockUpgrade: New period must be greater than existing"
);
timeLockPeriod = _timeLockPeriod;
}
}
// File: contracts/lib/Authorizable.sol
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title Authorizable
* @author Set Protocol
*
* The Authorizable contract is an inherited contract that sets permissions on certain function calls
* through the onlyAuthorized modifier. Permissions can be managed only by the Owner of the contract.
*/
contract Authorizable is
Ownable,
TimeLockUpgrade
{
using SafeMath for uint256;
using AddressArrayUtils for address[];
/* ============ State Variables ============ */
// Mapping of addresses to bool indicator of authorization
mapping (address => bool) public authorized;
// Array of authorized addresses
address[] public authorities;
/* ============ Modifiers ============ */
// Only authorized addresses can invoke functions with this modifier.
modifier onlyAuthorized {
require(
authorized[msg.sender],
"Authorizable.onlyAuthorized: Sender not included in authorities"
);
_;
}
/* ============ Events ============ */
// Event emitted when new address is authorized.
event AddressAuthorized (
address indexed authAddress,
address authorizedBy
);
// Event emitted when address is deauthorized.
event AuthorizedAddressRemoved (
address indexed addressRemoved,
address authorizedBy
);
/* ============ Setters ============ */
/**
* Add authorized address to contract. Can only be set by owner.
*
* @param _authTarget The address of the new authorized contract
*/
function addAuthorizedAddress(address _authTarget)
external
onlyOwner
timeLockUpgrade
{
// Require that address is not already authorized
require(
!authorized[_authTarget],
"Authorizable.addAuthorizedAddress: Address already registered"
);
// Set address authority to true
authorized[_authTarget] = true;
// Add address to authorities array
authorities.push(_authTarget);
// Emit authorized address event
emit AddressAuthorized(
_authTarget,
msg.sender
);
}
/**
* Remove authorized address from contract. Can only be set by owner.
*
* @param _authTarget The address to be de-permissioned
*/
function removeAuthorizedAddress(address _authTarget)
external
onlyOwner
{
// Require address is authorized
require(
authorized[_authTarget],
"Authorizable.removeAuthorizedAddress: Address not authorized"
);
// Delete address from authorized mapping
authorized[_authTarget] = false;
authorities = authorities.remove(_authTarget);
// Emit AuthorizedAddressRemoved event.
emit AuthorizedAddressRemoved(
_authTarget,
msg.sender
);
}
/* ============ Getters ============ */
/**
* Get array of authorized addresses.
*
* @return address[] Array of authorized addresses
*/
function getAuthorizedAddresses()
external
view
returns (address[] memory)
{
// Return array of authorized addresses
return authorities;
}
}
// File: contracts/lib/CommonMath.sol
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
library CommonMath {
using SafeMath for uint256;
/**
* Calculates and returns the maximum value for a uint256
*
* @return The maximum value for uint256
*/
function maxUInt256()
internal
pure
returns (uint256)
{
return 2 ** 256 - 1;
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0);
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
/**
* Checks for rounding errors and returns value of potential partial amounts of a principal
*
* @param _principal Number fractional amount is derived from
* @param _numerator Numerator of fraction
* @param _denominator Denominator of fraction
* @return uint256 Fractional amount of principal calculated
*/
function getPartialAmount(
uint256 _principal,
uint256 _numerator,
uint256 _denominator
)
internal
pure
returns (uint256)
{
// Get remainder of partial amount (if 0 not a partial amount)
uint256 remainder = mulmod(_principal, _numerator, _denominator);
// Return if not a partial amount
if (remainder == 0) {
return _principal.mul(_numerator).div(_denominator);
}
// Calculate error percentage
uint256 errPercentageTimes1000000 = remainder.mul(1000000).div(_numerator.mul(_principal));
// Require error percentage is less than 0.1%.
require(
errPercentageTimes1000000 < 1000,
"CommonMath.getPartialAmount: Rounding error exceeds bounds"
);
return _principal.mul(_numerator).div(_denominator);
}
}
// File: contracts/lib/IERC20.sol
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title IERC20
* @author Set Protocol
*
* Interface for using ERC20 Tokens. This interface is needed to interact with tokens that are not
* fully ERC20 compliant and return something other than true on successful transfers.
*/
interface IERC20 {
function balanceOf(
address _owner
)
external
view
returns (uint256);
function allowance(
address _owner,
address _spender
)
external
view
returns (uint256);
function transfer(
address _to,
uint256 _quantity
)
external;
function transferFrom(
address _from,
address _to,
uint256 _quantity
)
external;
function approve(
address _spender,
uint256 _quantity
)
external
returns (bool);
}
// File: contracts/lib/ERC20Wrapper.sol
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title ERC20Wrapper
* @author Set Protocol
*
* This library contains functions for interacting wtih ERC20 tokens, even those not fully compliant.
* For all functions we will only accept tokens that return a null or true value, any other values will
* cause the operation to revert.
*/
library ERC20Wrapper {
// ============ Internal Functions ============
/**
* Check balance owner's balance of ERC20 token
*
* @param _token The address of the ERC20 token
* @param _owner The owner who's balance is being checked
* @return uint256 The _owner's amount of tokens
*/
function balanceOf(
address _token,
address _owner
)
external
view
returns (uint256)
{
return IERC20(_token).balanceOf(_owner);
}
/**
* Checks spender's allowance to use token's on owner's behalf.
*
* @param _token The address of the ERC20 token
* @param _owner The token owner address
* @param _spender The address the allowance is being checked on
* @return uint256 The spender's allowance on behalf of owner
*/
function allowance(
address _token,
address _owner,
address _spender
)
internal
view
returns (uint256)
{
return IERC20(_token).allowance(_owner, _spender);
}
/**
* Transfers tokens from an address. Handle's tokens that return true or null.
* If other value returned, reverts.
*
* @param _token The address of the ERC20 token
* @param _to The address to transfer to
* @param _quantity The amount of tokens to transfer
*/
function transfer(
address _token,
address _to,
uint256 _quantity
)
external
{
IERC20(_token).transfer(_to, _quantity);
// Check that transfer returns true or null
require(
checkSuccess(),
"ERC20Wrapper.transfer: Bad return value"
);
}
/**
* Transfers tokens from an address (that has set allowance on the proxy).
* Handle's tokens that return true or null. If other value returned, reverts.
*
* @param _token The address of the ERC20 token
* @param _from The address to transfer from
* @param _to The address to transfer to
* @param _quantity The number of tokens to transfer
*/
function transferFrom(
address _token,
address _from,
address _to,
uint256 _quantity
)
external
{
IERC20(_token).transferFrom(_from, _to, _quantity);
// Check that transferFrom returns true or null
require(
checkSuccess(),
"ERC20Wrapper.transferFrom: Bad return value"
);
}
/**
* Grants spender ability to spend on owner's behalf.
* Handle's tokens that return true or null. If other value returned, reverts.
*
* @param _token The address of the ERC20 token
* @param _spender The address to approve for transfer
* @param _quantity The amount of tokens to approve spender for
*/
function approve(
address _token,
address _spender,
uint256 _quantity
)
internal
{
IERC20(_token).approve(_spender, _quantity);
// Check that approve returns true or null
require(
checkSuccess(),
"ERC20Wrapper.approve: Bad return value"
);
}
/**
* Ensure's the owner has granted enough allowance for system to
* transfer tokens.
*
* @param _token The address of the ERC20 token
* @param _owner The address of the token owner
* @param _spender The address to grant/check allowance for
* @param _quantity The amount to see if allowed for
*/
function ensureAllowance(
address _token,
address _owner,
address _spender,
uint256 _quantity
)
internal
{
uint256 currentAllowance = allowance(_token, _owner, _spender);
if (currentAllowance < _quantity) {
approve(
_token,
_spender,
CommonMath.maxUInt256()
);
}
}
// ============ Private Functions ============
/**
* Checks the return value of the previous function up to 32 bytes. Returns true if the previous
* function returned 0 bytes or 1.
*/
function checkSuccess(
)
private
pure
returns (bool)
{
// default to failure
uint256 returnValue = 0;
assembly {
// check number of bytes returned from last function call
switch returndatasize
// no bytes returned: assume success
case 0x0 {
returnValue := 1
}
// 32 bytes returned
case 0x20 {
// copy 32 bytes into scratch space
returndatacopy(0x0, 0x0, 0x20)
// load those bytes into returnValue
returnValue := mload(0x0)
}
// not sure what was returned: dont mark as success
default { }
}
// check if returned value is one or nothing
return returnValue == 1;
}
}
// File: contracts/core/TransferProxy.sol
/*
Copyright 2018 Set Labs Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.7;
/**
* @title TransferProxy
* @author Set Protocol
*
* The transferProxy contract is responsible for moving tokens through the system to
* assist with issuance and usage from modules.
*/
contract TransferProxy is
Authorizable
{
using SafeMath for uint256;
/* ============ External Functions ============ */
/**
* Transfers tokens from an address (that has set allowance on the proxy).
* Can only be called by Core.
*
* @param _token The address of the ERC20 token
* @param _quantity The number of tokens to transfer
* @param _from The address to transfer from
* @param _to The address to transfer to
*/
function transfer(
address _token,
uint256 _quantity,
address _from,
address _to
)
public
onlyAuthorized
{
// Call specified ERC20 contract to transfer tokens (via proxy).
if (_quantity > 0) {
// Retrieve current balance of token for the receiver
uint256 existingBalance = ERC20Wrapper.balanceOf(
_token,
_to
);
ERC20Wrapper.transferFrom(
_token,
_from,
_to,
_quantity
);
// Get new balance of transferred token for receiver
uint256 newBalance = ERC20Wrapper.balanceOf(
_token,
_to
);
// Verify transfer quantity is reflected in balance
require(
newBalance == existingBalance.add(_quantity),
"TransferProxy.transfer: Invalid post transfer balance"
);
}
}
/**
* Transfers tokens from an address (that has set allowance on the proxy).
* Can only be called by Core.
*
* @param _tokens The addresses of the ERC20 token
* @param _quantities The numbers of tokens to transfer
* @param _from The address to transfer from
* @param _to The address to transfer to
*/
function batchTransfer(
address[] calldata _tokens,
uint256[] calldata _quantities,
address _from,
address _to
)
external
onlyAuthorized
{
// Storing token count to local variable to save on invocation
uint256 tokenCount = _tokens.length;
// Confirm and empty _tokens array is not passed
require(
tokenCount > 0,
"TransferProxy.batchTransfer: Tokens must not be empty"
);
// Confirm there is one quantity for every token address
require(
tokenCount == _quantities.length,
"TransferProxy.batchTransfer: Tokens and quantities lengths mismatch"
);
for (uint256 i = 0; i < tokenCount; i++) {
if (_quantities[i] > 0) {
transfer(
_tokens[i],
_quantities[i],
_from,
_to
);
}
}
}
}
|
Checks the return value of the previous function up to 32 bytes. Returns true if the previous function returned 0 bytes or 1./ default to failure check number of bytes returned from last function call no bytes returned: assume success 32 bytes returned copy 32 bytes into scratch space load those bytes into returnValue
|
function checkSuccess(
)
private
pure
returns (bool)
{
uint256 returnValue = 0;
assembly {
switch returndatasize
case 0x0 {
returnValue := 1
}
case 0x20 {
returndatacopy(0x0, 0x0, 0x20)
returnValue := mload(0x0)
}
}
}
| 1,081,068
|
// 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 Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @dev Interface to C-folio item contracts
*/
interface IBooster {
/**
* @dev Return information about the reward state in Booster
*
* @param tokenIds The SFT or TF tokenId
*
* @return locked The total amounts locked
* @return pending The pending amounts claimable
* @return apr The APR of this lock pool
* @return secsLeft Numbers of seconds until unlock, or -1 if unlocked
*/
function getRewardInfo(uint256[] calldata tokenIds)
external
view
returns (
uint256[] memory locked,
uint256[] memory pending,
uint256[] memory apr,
uint256[] memory secsLeft
);
/**
* @dev Handles farm distribution, only callable from controller
*
* If recipient is booster contract, amount is temporarily stored and locked
* in a second call.
*
* @param farm The reward farm that the call originates from
* @param recipient The recipient of the rewards
* @param amount The amount to distribute
* @param fee The fee in 6 decimal notation
*/
function distributeFromFarm(
address farm,
address recipient,
uint256 amount,
uint32 fee
) external;
/**
* @dev Locks temporary tokens owned by recipient for a specific duration
* of seconds.
*
* @param recipient The recipient of the rewards
* @param lockPeriod The lock period in seconds
*/
function lock(address recipient, uint256 lockPeriod) external;
/**
* @dev Claim rewards either into wallet or re-lock them
*
* @param sftTokenId The tokenId that manages the rewards
* @param reLock True to re-lock existing rewards to earn more
*/
function claimRewards(uint256 sftTokenId, bool reLock) external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '../../token/interfaces/ICFolioItemCallback.sol';
/**
* @dev Interface to C-folio item contracts
*/
interface ICFolioItemHandler is ICFolioItemCallback {
/**
* @dev Called when a SFT tokens grade needs re-evaluation
*
* @param tokenId The ERC-1155 token ID. Rate is in 1E6 convention: 1E6 = 100%
* @param newRate The new value rate
*/
function sftUpgrade(uint256 tokenId, uint32 newRate) external;
/**
* @dev Called from SFTMinter after an Investment SFT is minted
*
* @param payer The approved address to get investment from
* @param sftTokenId The sftTokenId whose c-folio is the owner of investment
* @param amounts The amounts of invested assets
*/
function setupCFolio(
address payer,
uint256 sftTokenId,
uint256[] calldata amounts
) external;
//////////////////////////////////////////////////////////////////////////////
// Asset access
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Adds investments into a cFolioItem SFT
*
* Transfers amounts of assets from users wallet to the contract. In general,
* an Approval call is required before the function is called.
*
* @param baseTokenId cFolio tokenId, must be unlocked, or -1
* @param tokenId cFolioItem tokenId, must be unlocked if not in unlocked cFolio
* @param amounts Investment amounts, implementation specific
*/
function deposit(
uint256 baseTokenId,
uint256 tokenId,
uint256[] calldata amounts
) external;
/**
* @dev Removes investments from a cFolioItem SFT
*
* Withdrawn token are transfered back to msg.sender.
*
* @param baseTokenId cFolio tokenId, must be unlocked, or -1
* @param tokenId cFolioItem tokenId, must be unlocked if not in unlocked cFolio
* @param amounts Investment amounts, implementation specific
*/
function withdraw(
uint256 baseTokenId,
uint256 tokenId,
uint256[] calldata amounts
) external;
/**
* @dev Get the rewards collected by an SFT base card
*
* Calls only allowed from sftMinter.
*
* @param owner The owner of the NFT token
* @param recipient Recipient of the rewards (- fees)
* @param tokenId SFT base card tokenId, must be unlocked
*/
function getRewards(
address owner,
address recipient,
uint256 tokenId
) external;
/**
* @dev Get amounts (handler specific) for a cfolioItem
*
* @param cfolioItem address of CFolioItem contract
*/
function getAmounts(address cfolioItem)
external
view
returns (uint256[] memory);
/**
* @dev Get information obout the rewardFarm
*
* @param tokenIds List of basecard tokenIds
* @return bytes of uint256[]: total, rewardDur, rewardRateForDur, [share, earned]
*/
function getRewardInfo(uint256[] calldata tokenIds)
external
view
returns (bytes memory);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
// BOIS feature bitmask
uint256 constant LEVEL2BOIS = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000F;
uint256 constant LEVEL2WOLF = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000000000F0;
interface ISFTEvaluator {
/**
* @dev Returns the reward in 1e6 factor notation (1e6 = 100%)
*/
function rewardRate(uint256 sftTokenId) external view returns (uint32);
/**
* @dev Returns the cFolioItemType of a given cFolioItem tokenId
*/
function getCFolioItemType(uint256 tokenId) external view returns (uint256);
/**
* @dev Calculate the current reward rate, and notify TFC in case of change
*
* Optional revert on unchange to save gas on external calls.
*/
function setRewardRate(uint256 tokenId, bool revertUnchanged) external;
/**
* @dev Sets the cfolioItemType of a cfolioItem tokenId, not yet used
* sftHolder tokenId expected (without hash)
*/
function setCFolioItemType(uint256 tokenId, uint256 cfolioItemType_) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '@openzeppelin/contracts/utils/Context.sol';
import '../booster/interfaces/IBooster.sol';
import '../cfolio/interfaces/ICFolioItemHandler.sol';
import '../cfolio/interfaces/ISFTEvaluator.sol';
import '../investment/interfaces/IRewardHandler.sol';
import '../token/interfaces/IERC1155BurnMintable.sol';
import '../token/interfaces/ITradeFloor.sol';
import '../token/interfaces/IWOWSCryptofolio.sol';
import '../token/interfaces/IWOWSERC1155.sol';
import '../utils/AddressBook.sol';
import '../utils/interfaces/IAddressRegistry.sol';
import '../utils/TokenIds.sol';
contract WOWSSftMinter is Context, Ownable {
using TokenIds for uint256;
using SafeERC20 for IERC20;
//////////////////////////////////////////////////////////////////////////////
// State
//////////////////////////////////////////////////////////////////////////////
// PricePerlevel, customLevel start at 0xFF
mapping(uint16 => uint256) public _pricePerLevel;
struct CFolioItemSft {
uint256 handlerId;
uint256 price;
uint128 numMinted;
uint128 maxMintable;
}
mapping(uint256 => CFolioItemSft) public cfolioItemSfts; // C-folio type to c-folio data
ICFolioItemHandler[] private cfolioItemHandlers;
uint256 public nextCFolioItemNft = (1 << 64);
// The ERC1155 contract we are minting from
IWOWSERC1155 private immutable _sftContract;
// The cfolioItem wrapper bridge
address private immutable _cfiBridge;
// WOWS token contract
IERC20 private immutable _wowsToken;
// Booster
IBooster private immutable _booster;
// Reward handler which distributes WOWS
IRewardHandler public rewardHandler;
// TradeFloor Proxy contract
address public tradeFloor;
// SFTEvaluator to store the cfolioItemType
ISFTEvaluator public sftEvaluator;
// Set while minting CFolioToken
bool private _setupCFolio;
// 1.0 of the rewards go to distribution
uint32 private constant ALL = 1 * 1e6;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
// Emitted if a new SFT is minted
event Mint(
address indexed recipient,
uint256 tokenId,
uint256 price,
uint256 cfolioType
);
// Emitted if cFolio mint specifications (e.g. limits / price) have changed
event CFolioSpecChanged(uint256[] ids, WOWSSftMinter upgradeFrom);
// Emitted if the contract gets destroyed
event Destruct();
//////////////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Contruct WOWSSftMinter
*
* @param addressRegistry WOWS system addressRegistry
*/
constructor(IAddressRegistry addressRegistry) {
// Initialize {Ownable}
transferOwnership(
addressRegistry.getRegistryEntry(AddressBook.MARKETING_WALLET)
);
// Initialize state
_sftContract = IWOWSERC1155(
addressRegistry.getRegistryEntry(AddressBook.SFT_HOLDER)
);
_wowsToken = IERC20(
addressRegistry.getRegistryEntry(AddressBook.WOWS_TOKEN)
);
_cfiBridge = addressRegistry.getRegistryEntry(
AddressBook.CFOLIOITEM_BRIDGE_PROXY
);
rewardHandler = IRewardHandler(
addressRegistry.getRegistryEntry(AddressBook.REWARD_HANDLER)
);
_booster = IBooster(
addressRegistry.getRegistryEntry(AddressBook.WOWS_BOOSTER_PROXY)
);
}
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set prices for the given levels
*/
function setPrices(uint16[] memory levels, uint256[] memory prices)
external
onlyOwner
{
// Validate parameters
require(levels.length == prices.length, 'Length mismatch');
// Update state
for (uint256 i = 0; i < levels.length; ++i)
_pricePerLevel[levels[i]] = prices[i];
}
/**
* @dev Set new reward handler
*
* RewardHandler is by concept upgradeable / see investment::Controller.sol.
*/
function setRewardHandler(IRewardHandler newRewardHandler)
external
onlyOwner
{
// Update state
rewardHandler = newRewardHandler;
}
/**
* @dev Set Trade Floor
*/
function setTradeFloor(address tradeFloor_) external onlyOwner {
// Validate parameters
require(tradeFloor_ != address(0), 'Invalid TF');
// Update state
tradeFloor = tradeFloor_;
}
/**
* @dev Set SFT evaluator
*/
function setSFTEvaluator(ISFTEvaluator sftEvaluator_) external onlyOwner {
// Validate parameters
require(address(sftEvaluator_) != address(0), 'Invalid TF');
// Update state
sftEvaluator = sftEvaluator_;
}
/**
* @dev Set the limitations, the price and the handlers for CFolioItem SFT's
*/
function setCFolioSpec(
uint256[] calldata cFolioTypes,
address[] calldata handlers,
uint128[] calldata maxMint,
uint256[] calldata prices,
WOWSSftMinter oldMinter
) external onlyOwner {
// Validate parameters
require(
cFolioTypes.length == handlers.length &&
handlers.length == maxMint.length &&
maxMint.length == prices.length,
'Length mismatch'
);
// Update state
delete (cfolioItemHandlers);
for (uint256 i = 0; i < cFolioTypes.length; ++i) {
uint256 j = 0;
for (; j < cfolioItemHandlers.length; ++j) {
if (address(cfolioItemHandlers[j]) == handlers[i]) break;
}
if (j == cfolioItemHandlers.length) {
cfolioItemHandlers.push(ICFolioItemHandler(handlers[i]));
}
CFolioItemSft storage cfi = cfolioItemSfts[cFolioTypes[i]];
cfi.handlerId = j;
cfi.maxMintable = maxMint[i];
cfi.price = prices[i];
}
if (address(oldMinter) != address(0)) {
for (uint256 i = 0; i < cFolioTypes.length; ++i) {
(, , uint128 numMinted, ) = oldMinter.cfolioItemSfts(cFolioTypes[i]);
cfolioItemSfts[cFolioTypes[i]].numMinted = numMinted;
}
nextCFolioItemNft = oldMinter.nextCFolioItemNft();
}
// Dispatch event
emit CFolioSpecChanged(cFolioTypes, oldMinter);
}
/**
* @dev upgrades state from an existing WOWSSFTMinter
*/
function destructContract() external onlyOwner {
// Dispatch event
emit Destruct();
// Disable high-impact Slither detector "suicidal" here. Slither explains
// that "WOWSSftMinter.destructContract() allows anyone to destruct the
// contract", which is not the case due to the {Ownable-onlyOwner} modifier.
//
// slither-disable-next-line suicidal
selfdestruct(_msgSender());
}
/**
* @dev Mint one of our stock card SFTs
*
* Approval of WOWS token required before the call.
*/
function mintWowsSFT(
address recipient,
uint8 level,
uint8 cardId
) external {
// Validate parameters
require(recipient != address(0), 'Invalid recipient');
// Load state
uint256 price = _pricePerLevel[level];
// Validate state
require(price > 0, 'No price available');
// Get the next free mintable token for level / cardId
(bool success, uint256 tokenId) = _sftContract.getNextMintableTokenId(
level,
cardId
);
require(success, 'Unsufficient cards');
// Update state
_mint(recipient, tokenId, price, 0);
}
/**
* @dev Mint a custom token
*
* Approval of WOWS token required before the call.
*/
function mintCustomSFT(
address recipient,
uint8 level,
string memory uri
) external {
// Validate parameters
require(recipient != address(0), 'Invalid recipient');
// Load state
uint256 price = _pricePerLevel[0x100 + level];
// Validate state
require(price > 0, 'No price available');
// Get the next free mintable token for level / cardId
uint256 tokenId = _sftContract.getNextMintableCustomToken();
// Custom baseToken only allowed < 64Bit
require(tokenId.isBaseCard(), 'Max tokenId reached');
// Set card level and uri
_sftContract.setCustomCardLevel(tokenId, level);
_sftContract.setCustomURI(tokenId, uri);
// Update state
_mint(recipient, tokenId, price, 0);
}
/**
* @dev Mint a CFolioItem token
*
* Approval of WOWS token required before the call.
*
* Post-condition: `_setupCFolio` must be false.
*
* @param recipient Recipient of the SFT, unused if sftTokenId is != -1
* @param cfolioItemType The item type of the SFT
* @param sftTokenId If <> -1 recipient is the SFT c-folio / handler must be called
* @param investAmounts Arguments needed for the handler (in general investments).
* Investments may be zero if the user is just buying an SFT.
*/
function mintCFolioItemSFT(
address recipient,
uint256 cfolioItemType,
uint256 sftTokenId,
uint256[] calldata investAmounts
) external {
// Validate state
require(!_setupCFolio, 'Already setting up');
require(address(sftEvaluator) != address(0), 'SFTE not set');
// Validate parameters
require(recipient != address(0), 'Invalid recipient');
// Load state
CFolioItemSft storage sftData = cfolioItemSfts[cfolioItemType];
// Validate state
require(
sftData.numMinted < sftData.maxMintable,
'CFI Minter: Insufficient amount'
);
address sftCFolio = address(0);
if (sftTokenId != uint256(-1)) {
require(sftTokenId.isBaseCard(), 'Invalid sftTokenId');
// Get the CFolio contract address, it will be the final recipient
sftCFolio = _sftContract.tokenIdToAddress(sftTokenId);
require(sftCFolio != address(0), 'Bad sftTokenId');
// Intermediate owner of the minted SFT
recipient = address(this);
// Allow this contract to be an ERC1155 holder
_setupCFolio = true;
}
uint256 tokenId = nextCFolioItemNft++;
require(tokenId.isCFolioCard(), 'Invalid cfolioItem tokenId');
sftEvaluator.setCFolioItemType(tokenId, cfolioItemType);
// Update state, mint SFT token
sftData.numMinted += 1;
_mint(recipient, tokenId, sftData.price, cfolioItemType);
// Let CFolioHandler setup the new minted token
cfolioItemHandlers[sftData.handlerId].setupCFolio(
_msgSender(),
tokenId,
investAmounts
);
// Check-effects-interaction not needed, as `_setupCFolio` can't be mutated
// outside this function.
// If the SFT's c-folio is final recipient of c-folio item, we call the
// handler and lock the c-folio item in the TradeFloor contract before we
// transfer it to the SFT.
if (sftCFolio != address(0)) {
// Lock the SFT into the TradeFloor contract
IERC1155BurnMintable(address(_sftContract)).safeTransferFrom(
address(this),
address(_cfiBridge),
tokenId,
1,
abi.encodePacked(sftCFolio)
);
// Reset the temporary state which allows holding ERC1155 token
_setupCFolio = false;
}
}
/**
* @dev Claim rewards from all c-folio farms
*
* If lockPeriod > 0, Booster locks the token on behalf of sftToken and
* provides extra rewards. Otherwise rewards are distributed in
* rewardHandler.
*
* @param sftTokenId Valid SFT tokenId, must not be locked in TF
* @param lockPeriod Lock time in seconds
*/
function claimSFTRewards(uint256 sftTokenId, uint256 lockPeriod) external {
// If lockPeriod > 0 rewards are managed by booster
address cfolio = _sftContract.tokenIdToAddress(sftTokenId);
require(cfolio != address(0), 'WM: Invalid cfolio');
address receiver = lockPeriod > 0 ? cfolio : _msgSender();
bool[] memory lookup = new bool[](cfolioItemHandlers.length);
(uint256[] memory items, uint256 itemsLength) = IWOWSCryptofolio(cfolio)
.getCryptofolio(_cfiBridge);
for (uint256 i = 0; i < itemsLength; ++i) {
// Get the handler of this type
uint256 handlerId = cfolioItemSfts[
sftEvaluator.getCFolioItemType(items[i])
].handlerId;
if (!lookup[handlerId]) {
cfolioItemHandlers[handlerId].getRewards(
_msgSender(),
receiver,
sftTokenId
);
lookup[handlerId] = true;
}
}
// In case lockPeriod is set, all rewards are temporarily parked in
// booster. Lock the parked rewards for the current msg.sender.
if (lockPeriod > 0) {
_booster.lock(receiver, lockPeriod);
}
}
//////////////////////////////////////////////////////////////////////////////
// ERC1155Holder
//////////////////////////////////////////////////////////////////////////////
/**
* @dev We are a temorary token holder during CFolioToken mint step
*
* Only accept ERC1155 tokens during this setup.
*/
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) external view returns (bytes4) {
// Validate state
require(_setupCFolio, 'Only during setup');
// Call ancestor
return this.onERC1155Received.selector;
}
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Query prices for given levels
*/
function getPrices(uint16[] memory levels)
external
view
returns (uint256[] memory)
{
uint256[] memory result = new uint256[](levels.length);
for (uint256 i = 0; i < levels.length; ++i)
result[i] = _pricePerLevel[levels[i]];
return result;
}
/**
* @dev retrieve mint information about cfolioItem
*/
function getCFolioSpec(uint256[] calldata cFolioTypes)
external
view
returns (
uint256[] memory prices,
uint128[] memory numMinted,
uint128[] memory maxMintable
)
{
uint256 length = cFolioTypes.length;
prices = new uint256[](length);
numMinted = new uint128[](length);
maxMintable = new uint128[](length);
for (uint256 i; i < length; ++i) {
CFolioItemSft storage cfi = cfolioItemSfts[cFolioTypes[i]];
prices[i] = cfi.price;
numMinted[i] = cfi.numMinted;
maxMintable[i] = cfi.maxMintable;
}
}
/**
* @dev Get all tokenIds from SFT and TF contract owned by account.
*/
function getTokenIds(address account)
external
view
returns (uint256[] memory sftTokenIds, uint256[] memory tfTokenIds)
{
require(account != address(0), 'Null address');
sftTokenIds = _sftContract.getTokenIds(account);
tfTokenIds = ITradeFloor(tradeFloor).getTokenIds(account);
}
/**
* @dev Get underlying information (cFolioItems / value) for given tokenIds.
*
* @param tokenIds the tokenIds information should be queried
* @return result [%,MintTime,NumItems,[tokenId,type,numAssetValues,[assetValue]]]...
*/
function getTokenInformation(uint256[] calldata tokenIds)
external
view
returns (bytes memory result)
{
uint256[] memory cFolioItems;
uint256[] memory oneCFolioItem = new uint256[](1);
uint256 cfolioLength;
uint256 rewardRate;
uint256 timestamp;
for (uint256 i = 0; i < tokenIds.length; ++i) {
if (tokenIds[i].isBaseCard()) {
// Only main TradeFloor supported
uint256 sftTokenId = tokenIds[i].toSftTokenId();
address cfolio = _sftContract.tokenIdToAddress(sftTokenId);
if (address(cfolio) != address(0)) {
(cFolioItems, cfolioLength) = IWOWSCryptofolio(cfolio).getCryptofolio(
_cfiBridge
);
} else {
cFolioItems = oneCFolioItem;
cfolioLength = 0;
}
rewardRate = sftEvaluator.rewardRate(tokenIds[i]);
(timestamp, ) = _sftContract.getTokenData(sftTokenId);
} else {
oneCFolioItem[0] = tokenIds[i];
cfolioLength = 1;
cFolioItems = oneCFolioItem; // Reference, no copy
rewardRate = 0;
timestamp = 0;
}
result = abi.encodePacked(result, rewardRate, timestamp, cfolioLength);
for (uint256 j = 0; j < cfolioLength; ++j) {
uint256 sftTokenId = cFolioItems[j].toSftTokenId();
uint256 cfolioType = sftEvaluator.getCFolioItemType(sftTokenId);
uint256[] memory amounts;
address cfolio = _sftContract.tokenIdToAddress(sftTokenId);
if (address(cfolio) != address(0)) {
address handler = IWOWSCryptofolio(cfolio)._tradefloors(0);
if (handler != address(0))
amounts = ICFolioItemHandler(handler).getAmounts(cfolio);
}
result = abi.encodePacked(
result,
cFolioItems[j],
cfolioType,
amounts.length,
amounts
);
}
}
}
/**
* @dev Get CFIItemHandlerRewardInfo and Booster rewardInfo.
*/
function getRewardInfo(address cfih, uint256[] calldata tokenIds)
external
view
returns (
bytes memory result,
uint256[] memory boosterLocked,
uint256[] memory boosterPending,
uint256[] memory boosterApr,
uint256[] memory boosterSecsLeft
)
{
result = ICFolioItemHandler(cfih).getRewardInfo(tokenIds);
(boosterLocked, boosterPending, boosterApr, boosterSecsLeft) = _booster
.getRewardInfo(tokenIds);
}
/**
* @dev Get balances of given ERC20 addresses.
*/
function getErc20Balances(address account, address[] calldata erc20)
external
view
returns (uint256[] memory amounts)
{
amounts = new uint256[](erc20.length);
for (uint256 i = 0; i < erc20.length; ++i)
amounts[i] = erc20[i] == address(0)
? 0
: IERC20(erc20[i]).balanceOf(account);
}
/**
* @dev Get allowances of given ERC20 addresses.
*/
function getErc20Allowances(
address account,
address[] calldata spender,
address[] calldata erc20
) external view returns (uint256[] memory amounts) {
// Validate parameters
require(spender.length == erc20.length, 'Length mismatch');
amounts = new uint256[](spender.length);
for (uint256 i = 0; i < spender.length; ++i)
amounts[i] = erc20[i] == address(0)
? 0
: IERC20(erc20[i]).allowance(account, spender[i]);
}
//////////////////////////////////////////////////////////////////////////////
// Internal functionality
//////////////////////////////////////////////////////////////////////////////
function _mint(
address recipient,
uint256 tokenId,
uint256 price,
uint256 cfolioType
) internal {
// Transfer WOWS from user to reward handler
if (price > 0)
_wowsToken.safeTransferFrom(_msgSender(), address(rewardHandler), price);
// Mint the token
IERC1155BurnMintable(address(_sftContract)).mint(recipient, tokenId, 1, '');
// Distribute the rewards
if (price > 0) rewardHandler.distribute2(recipient, price, ALL);
// Log event
emit Mint(recipient, tokenId, price, cfolioType);
}
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity 0.7.6;
interface IRewardHandler {
/**
* @dev Get the amount allocated for the Booster
*
* @return The amount which is allocated for the Booster (18 decimals)
*/
function getBoosterRewards() external view returns (uint256);
/**
* @dev Transfer reward and distribute the fee
*
* This is the new implementation of distribute() which uses internal fees
* defined in the {RewardHandler} contract.
*
* @param recipient The recipient of the reward
* @param amount The amount of WOWS to transfer to the recipient
* @param fee The reward fee in 1e6 factor notation
*/
function distribute2(
address recipient,
uint256 amount,
uint32 fee
) external;
/**
* @dev Transfer reward and distribute the fee
*
* This is the current implementation, needed for backward compatibility.
*
* Current ERC1155Minter and Controller call this function, later
* reward handler clients should call the the new one with internal
* fees specified in this contract.
*
* uint32 values are in 1e6 factor notation.
*/
function distribute(
address recipient,
uint256 amount,
uint32 fee,
uint32 toTeam,
uint32 toMarketing,
uint32 toBooster,
uint32 toRewardPool
) external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @dev Interface to receive callbacks when minted tokens are burnt
*/
interface ICFolioItemCallback {
/**
* @dev Called when a TradeFloor CFolioItem is transfered
*
* In case of mint `from` is address(0).
* In case of burn `to` is address(0).
*
* cfolioHandlers are passed to let each cfolioHandler filter for its own
* token. This eliminates the need for creating separate lists.
*
* @param from The account sending the token
* @param to The account receiving the token
* @param tokenIds The ERC-1155 token IDs
* @param cfolioHandlers cFolioItem handlers
*/
function onCFolioItemsTransferedFrom(
address from,
address to,
uint256[] calldata tokenIds,
address[] calldata cfolioHandlers
) external;
/**
* @dev Append data we use later for hashing
*
* @param cfolioItem The token ID of the c-folio item
* @param current The current data being hashes
*
* @return The current data, with internal data appended
*/
function appendHash(address cfolioItem, bytes calldata current)
external
view
returns (bytes memory);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '@openzeppelin/contracts/token/ERC1155/IERC1155.sol';
interface IERC1155BurnMintable is IERC1155 {
/**
* @dev Mint amount new tokens at ID `tokenId` (MINTER_ROLE required)
*/
function mint(
address to,
uint256 tokenId,
uint256 amount,
bytes memory data
) external;
/**
* @dev Mint new token amounts at IDs `tokenIds` (MINTER_ROLE required)
*/
function mintBatch(
address to,
uint256[] calldata tokenIds,
uint256[] calldata amounts,
bytes memory data
) external;
/**
* @dev Burn value amount of tokens with ID `tokenId`.
*
* Caller must be approvedForAll.
*/
function burn(
address account,
uint256 tokenId,
uint256 value
) external;
/**
* @dev Burn `values` amounts of tokens with IDs `tokenIds`.
*
* Caller must be approvedForAll.
*/
function burnBatch(
address account,
uint256[] calldata tokenIds,
uint256[] calldata values
) external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio and tokenId interface
*/
interface ITradeFloor {
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Return all tokenIds owned by account
*/
function getTokenIds(address account)
external
view
returns (uint256[] memory);
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio interface
*/
interface IWOWSCryptofolio {
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Initialize the deployed contract after creation
*
* This is a one time call which sets _deployer to msg.sender.
* Subsequent calls reverts.
*/
function initialize() external;
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Return tradefloor at given index
*
* @param index The 0-based index in the tradefloor array
*
* @return The address of the tradefloor and position index
*/
function _tradefloors(uint256 index) external view returns (address);
/**
* @dev Return array of cryptofolio item token IDs
*
* The token IDs belong to the contract TradeFloor.
*
* @param tradefloor The TradeFloor that items belong to
*
* @return tokenIds The token IDs in scope of operator
* @return idsLength The number of valid token IDs
*/
function getCryptofolio(address tradefloor)
external
view
returns (uint256[] memory tokenIds, uint256 idsLength);
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set the owner of the underlying NFT
*
* This function is called if ownership of the parent NFT has changed.
*
* The new owner gets allowance to transfer cryptofolio items. The new owner
* is allowed to transfer / burn cryptofolio items. Make sure that allowance
* is removed from previous owner.
*
* @param owner The new owner of the underlying NFT, or address(0) if the
* underlying NFT is being burned
*/
function setOwner(address owner) external;
/**
* @dev Allow owner (of parent NFT) to approve external operators to transfer
* our cryptofolio items
*
* The NFT owner is allowed to approve operator to handle cryptofolios.
*
* @param operator The operator
* @param allow True to approve for all NFTs, false to revoke approval
*/
function setApprovalForAll(address operator, bool allow) external;
/**
* @dev Burn all cryptofolio items
*
* In case an underlying NFT is burned, we also burn the cryptofolio.
*/
function burn() external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
/**
* @notice Cryptofolio interface
*/
interface IWOWSERC1155 {
//////////////////////////////////////////////////////////////////////////////
// Getters
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Check if the specified address is a known tradefloor
*
* @param account The address to check
*
* @return True if the address is a known tradefloor, false otherwise
*/
function isTradeFloor(address account) external view returns (bool);
/**
* @dev Get the token ID of a given address
*
* A cross check is required because token ID 0 is valid.
*
* @param tokenAddress The address to convert to a token ID
*
* @return The token ID on success, or uint256(-1) if `tokenAddress` does not
* belong to a token ID
*/
function addressToTokenId(address tokenAddress)
external
view
returns (uint256);
/**
* @dev Get the address for a given token ID
*
* @param tokenId The token ID to convert
*
* @return The address, or address(0) in case the token ID does not belong
* to an NFT
*/
function tokenIdToAddress(uint256 tokenId) external view returns (address);
/**
* @dev Get the next mintable token ID for the specified card
*
* @param level The level of the card
* @param cardId The ID of the card
*
* @return bool True if a free token ID was found, false otherwise
* @return uint256 The first free token ID if one was found, or invalid otherwise
*/
function getNextMintableTokenId(uint8 level, uint8 cardId)
external
view
returns (bool, uint256);
/**
* @dev Return the next mintable custom token ID
*/
function getNextMintableCustomToken() external view returns (uint256);
/**
* @dev Return the level and the mint timestamp of tokenId
*
* @param tokenId The tokenId to query
*
* @return mintTimestamp The timestamp token was minted
* @return level The level token belongs to
*/
function getTokenData(uint256 tokenId)
external
view
returns (uint64 mintTimestamp, uint8 level);
/**
* @dev Return all tokenIds owned by account
*/
function getTokenIds(address account)
external
view
returns (uint256[] memory);
//////////////////////////////////////////////////////////////////////////////
// State modifiers
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Set the base URI for either predefined cards or custom cards
* which don't have it's own URI.
*
* The resulting uri is baseUri+[hex(tokenId)] + '.json'. where
* tokenId will be reduces to upper 16 bit (>> 16) before building the hex string.
*
*/
function setBaseMetadataURI(string memory baseContractMetadata) external;
/**
* @dev Set the contracts metadata URI
*
* @param contractMetadataURI The URI which point to the contract metadata file.
*/
function setContractMetadataURI(string memory contractMetadataURI) external;
/**
* @dev Set the URI for a custom card
*
* @param tokenId The token ID whose URI is being set.
* @param customURI The URI which point to an unique metadata file.
*/
function setCustomURI(uint256 tokenId, string memory customURI) external;
/**
* @dev Each custom card has its own level. Level will be used when
* calculating rewards and raiding power.
*
* @param tokenId The ID of the token whose level is being set
* @param cardLevel The new level of the specified token
*/
function setCustomCardLevel(uint256 tokenId, uint8 cardLevel) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
library AddressBook {
bytes32 public constant DEPLOYER = 'DEPLOYER';
bytes32 public constant TEAM_WALLET = 'TEAM_WALLET';
bytes32 public constant MARKETING_WALLET = 'MARKETING_WALLET';
bytes32 public constant UNISWAP_V2_ROUTER02 = 'UNISWAP_V2_ROUTER02';
bytes32 public constant WETH_WOWS_STAKE_FARM = 'WETH_WOWS_STAKE_FARM';
bytes32 public constant WOWS_TOKEN = 'WOWS_TOKEN';
bytes32 public constant UNISWAP_V2_PAIR = 'UNISWAP_V2_PAIR';
bytes32 public constant WOWS_BOOSTER_PROXY = 'WOWS_BOOSTER_PROXY';
bytes32 public constant REWARD_HANDLER = 'REWARD_HANDLER';
bytes32 public constant SFT_MINTER = 'SFT_MINTER';
bytes32 public constant SFT_HOLDER = 'SFT_HOLDER';
bytes32 public constant CFOLIOITEM_BRIDGE_PROXY = 'CFOLIOITEM_BRIDGE_PROXY';
bytes32 public constant BOIS_REWARDS = 'BOIS_REWARDS';
bytes32 public constant WOLVES_REWARDS = 'WOLVES_REWARDS';
bytes32 public constant SFT_EVALUATOR_PROXY = 'SFT_EVALUATOR_PROXY';
bytes32 public constant TRADE_FLOOR_PROXY = 'TRADE_FLOOR_PROXY';
bytes32 public constant CURVE_Y_TOKEN = 'CURVE_Y_TOKEN';
bytes32 public constant CURVE_Y_DEPOSIT = 'CURVE_Y_DEPOSIT';
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See LICENSE.txt for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
library TokenIds {
// 128 bit underlying hash
uint256 public constant HASH_MASK = (1 << 128) - 1;
function isBaseCard(uint256 tokenId) internal pure returns (bool) {
return (tokenId & HASH_MASK) < (1 << 64);
}
function isStockCard(uint256 tokenId) internal pure returns (bool) {
return (tokenId & HASH_MASK) < (1 << 32);
}
function isCFolioCard(uint256 tokenId) internal pure returns (bool) {
return
(tokenId & HASH_MASK) >= (1 << 64) && (tokenId & HASH_MASK) < (1 << 128);
}
function toSftTokenId(uint256 tokenId) internal pure returns (uint256) {
return tokenId & HASH_MASK;
}
function maskHash(uint256 tokenId) internal pure returns (uint256) {
return tokenId & ~HASH_MASK;
}
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
interface IAddressRegistry {
/**
* @dev Set an abitrary key / address pair into the registry
*/
function setRegistryEntry(bytes32 _key, address _location) external;
/**
* @dev Get a registry enty with by key, returns 0 address if not existing
*/
function getRegistryEntry(bytes32 _key) external view returns (address);
}
|
Set new reward handler RewardHandler is by concept upgradeable / see investment::Controller.sol./ Update state
|
function setRewardHandler(IRewardHandler newRewardHandler)
external
onlyOwner
{
rewardHandler = newRewardHandler;
}
| 10,321,984
|
/*
__ __ .__ .___ _____
/ \ / \___________| | __| _/ _____/ ____\
\ \/\/ / _ \_ __ \ | / __ | / _ \ __\
\ ( <_> ) | \/ |__/ /_/ | ( <_> ) |
\__/\ / \____/|__| |____/\____ | \____/|__|
\/ \/
__ __.__ .__ __ ________ .___
/ \ / \ |__ |__|/ |_ ____ \______ \ __ __ __| _/____ ______
\ \/\/ / | \| \ __\/ __ \ | | \| | \/ __ |/ __ \ / ___/
\ /| Y \ || | \ ___/ | ` \ | / /_/ \ ___/ \___ \
\__/\ / |___| /__||__| \___ > /_______ /____/\____ |\___ >____ >
\/ \/ \/ \/ \/ \/ \/
More like World of White DAOudes imho
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(
value <= type(uint224).max,
"SafeCast: value doesn't fit in 224 bits"
);
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(
value <= type(uint128).max,
"SafeCast: value doesn't fit in 128 bits"
);
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(
value <= type(uint96).max,
"SafeCast: value doesn't fit in 96 bits"
);
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(
value <= type(uint64).max,
"SafeCast: value doesn't fit in 64 bits"
);
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(
value <= type(uint32).max,
"SafeCast: value doesn't fit in 32 bits"
);
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(
value <= type(uint16).max,
"SafeCast: value doesn't fit in 16 bits"
);
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(
value <= type(uint8).max,
"SafeCast: value doesn't fit in 8 bits"
);
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(
value >= type(int128).min && value <= type(int128).max,
"SafeCast: value doesn't fit in 128 bits"
);
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(
value >= type(int64).min && value <= type(int64).max,
"SafeCast: value doesn't fit in 64 bits"
);
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(
value >= type(int32).min && value <= type(int32).max,
"SafeCast: value doesn't fit in 32 bits"
);
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(
value >= type(int16).min && value <= type(int16).max,
"SafeCast: value doesn't fit in 16 bits"
);
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(
value >= type(int8).min && value <= type(int8).max,
"SafeCast: value doesn't fit in 8 bits"
);
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(
value <= uint256(type(int256).max),
"SafeCast: value doesn't fit in an int256"
);
return int256(value);
}
}
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature)
internal
pure
returns (address, RecoverError)
{
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature)
internal
pure
returns (address)
{
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(
vs,
0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (
uint256(s) >
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return
keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", domainSeparator, structHash)
);
}
}
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(
typeHash,
hashedName,
hashedVersion
);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return
_buildDomainSeparator(
_TYPE_HASH,
_HASHED_NAME,
_HASHED_VERSION
);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return
keccak256(
abi.encode(
typeHash,
nameHash,
versionHash,
block.chainid,
address(this)
)
);
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash)
internal
view
virtual
returns (bytes32)
{
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev 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);
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
interface 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);
}
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
library Timers {
struct Timestamp {
uint64 _deadline;
}
function getDeadline(Timestamp memory timer)
internal
pure
returns (uint64)
{
return timer._deadline;
}
function setDeadline(Timestamp storage timer, uint64 timestamp) internal {
timer._deadline = timestamp;
}
function reset(Timestamp storage timer) internal {
timer._deadline = 0;
}
function isUnset(Timestamp memory timer) internal pure returns (bool) {
return timer._deadline == 0;
}
function isStarted(Timestamp memory timer) internal pure returns (bool) {
return timer._deadline > 0;
}
function isPending(Timestamp memory timer) internal view returns (bool) {
return timer._deadline > block.timestamp;
}
function isExpired(Timestamp memory timer) internal view returns (bool) {
return isStarted(timer) && timer._deadline <= block.timestamp;
}
struct BlockNumber {
uint64 _deadline;
}
function getDeadline(BlockNumber memory timer)
internal
pure
returns (uint64)
{
return timer._deadline;
}
function setDeadline(BlockNumber storage timer, uint64 timestamp) internal {
timer._deadline = timestamp;
}
function reset(BlockNumber storage timer) internal {
timer._deadline = 0;
}
function isUnset(BlockNumber memory timer) internal pure returns (bool) {
return timer._deadline == 0;
}
function isStarted(BlockNumber memory timer) internal pure returns (bool) {
return timer._deadline > 0;
}
function isPending(BlockNumber memory timer) internal view returns (bool) {
return timer._deadline > block.number;
}
function isExpired(BlockNumber memory timer) internal view returns (bool) {
return isStarted(timer) && timer._deadline <= block.number;
}
}
abstract contract IGovernor is IERC165 {
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/**
* @dev Emitted when a proposal is created.
*/
event ProposalCreated(
uint256 proposalId,
address proposer,
address[] targets,
uint256[] values,
string[] signatures,
bytes[] calldatas,
uint256 startBlock,
uint256 endBlock,
string description
);
/**
* @dev Emitted when a proposal is canceled.
*/
event ProposalCanceled(uint256 proposalId);
/**
* @dev Emitted when a proposal is executed.
*/
event ProposalExecuted(uint256 proposalId);
/**
* @dev Emitted when a vote is cast.
*
* Note: `support` values should be seen as buckets. There interpretation depends on the voting module used.
*/
event VoteCast(
address indexed voter,
uint256 proposalId,
uint8 support,
uint256 weight,
string reason
);
event Shout(string mouthVomit);
/**
* @notice module:core
* @dev Name of the governor instance (used in building the ERC712 domain separator).
*/
function name() public view virtual returns (string memory);
/**
* @notice module:core
* @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1"
*/
function version() public view virtual returns (string memory);
/**
* @notice module:voting
* @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to
* be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of
* key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`.
*
* There are 2 standard keys: `support` and `quorum`.
*
* - `support=bravo` refers to the vote options 0 = For, 1 = Against, 2 = Abstain, as in `GovernorBravo`.
* - `quorum=bravo` means that only For votes are counted towards quorum.
* - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum.
*
* NOTE: The string can be decoded by the standard
* https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`]
* JavaScript class.
*/
// solhint-disable-next-line func-name-mixedcase
function COUNTING_MODE() public pure virtual returns (string memory);
/**
* @notice module:core
* @dev Hashing function used to (re)build the proposal id from the proposal details..
*/
function hashProposal(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata calldatas,
bytes32 descriptionHash
) public pure virtual returns (uint256);
/**
* @notice module:core
* @dev Current state of a proposal, following Compound's convention
*/
function state(uint256 proposalId)
public
view
virtual
returns (ProposalState);
/**
* @notice module:core
* @dev block number used to retrieve user's votes and quorum.
*/
function proposalSnapshot(uint256 proposalId)
public
view
virtual
returns (uint256);
/**
* @notice module:core
* @dev timestamp at which votes close.
*/
function proposalDeadline(uint256 proposalId)
public
view
virtual
returns (uint256);
/**
* @notice module:user-config
* @dev delay, in number of block, between the proposal is created and the vote starts. This can be increassed to
* leave time for users to buy voting power, of delegate it, before the voting of a proposal starts.
*/
function votingDelay() public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev delay, in number of blocks, between the vote start and vote ends.
*
* Note: the {votingDelay} can delay the start of the vote. This must be considered when setting the voting
* duration compared to the voting delay.
*/
function votingPeriod() public view virtual returns (uint256);
/**
* @notice module:user-config
* @dev Minimum number of cast voted required for a proposal to be successful.
*
* Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the
* quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}).
*/
function quorum(uint256 blockNumber) public view virtual returns (uint256);
/**
* @notice module:reputation
* @dev Voting power of an `account` at a specific `blockNumber`.
*
* Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or
* multiple), {ERC20Votes} tokens.
*/
function getVotes(address account, uint256 blockNumber)
public
view
virtual
returns (uint256);
/**
* @notice module:voting
* @dev Returns weither `account` has cast a vote on `proposalId`.
*/
function hasVoted(uint256 proposalId, address account)
public
view
virtual
returns (bool);
/**
* @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends
* {IGovernor-votingPeriod} blocks after the voting starts.
*
* Emits a {ProposalCreated} event.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual returns (uint256 proposalId);
/**
* @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the
* deadline to be reached.
*
* Emits a {ProposalExecuted} event.
*
* Note: some module can modify the requirements for execution, for example by adding an additional timelock.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual returns (uint256 proposalId);
/**
* @dev Cast a vote
*
* Emits a {VoteCast} event.
*/
function castVote(uint256 proposalId, uint8 support)
public
virtual
returns (uint256 balance);
/**
* @dev Cast a with a reason
*
* Emits a {VoteCast} event.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual returns (uint256 balance);
/**
* @dev Cast a vote using the user cryptographic signature.
*
* Emits a {VoteCast} event.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual returns (uint256 balance);
}
interface IWorldOfWhiteDudes {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
function totalSupply() external view returns (uint256);
function maxSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @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);
function walletOfOwner(address owner)
external
view
returns (uint256[] memory);
}
abstract contract Governor is Ownable, ERC165, EIP712, IGovernor {
using SafeCast for uint256;
using Timers for Timers.BlockNumber;
IWorldOfWhiteDudes public immutable token =
IWorldOfWhiteDudes(0xD00D1e06a2680E02919f4F5c5EC5dC45d67bB0b5);
bytes32 public constant BALLOT_TYPEHASH =
keccak256("Ballot(uint256 proposalId,uint8 support)");
struct ProposalVote {
Timers.BlockNumber voteStart;
Timers.BlockNumber voteEnd;
bool executed;
bool canceled;
uint256 againstVotes;
uint256 forVotes;
uint256 abstainVotes;
uint256 maxVotes;
uint256 maxTokens;
mapping(address => uint256) voteCount;
mapping(uint256 => bool) tokenHasVoted;
}
uint256 public lastMaxTokenSupply;
uint256 public lastMaxVotes;
string private _name;
uint256 public totalProposals;
mapping(uint256 => uint256) public proposalIndexes;
mapping(uint256 => ProposalVote) internal _proposals;
mapping(uint256 => uint256) private extraVotes;
mapping(uint256 => uint256) private minusVotes;
/**
* @dev Restrict access to governor executing address. Some module might override the _executor function to make
* sure this modifier is consistant with the execution model.
*/
modifier onlyGovernance() {
require(_msgSender() == _executor(), "Governor: onlyGovernance");
_;
}
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status = _NOT_ENTERED;
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
/**
* @dev Sets the value for {name} and {version}
*/
constructor(string memory name_) EIP712(name_, version()) {
_name = name_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC165, ERC165)
returns (bool)
{
return
interfaceId == type(IGovernor).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IGovernor-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IGovernor-version}.
*/
function version() public view virtual override returns (string memory) {
return "1";
}
/**
* @dev See {IGovernor-hashProposal}.
*
* The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array
* and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id
* can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in
* advance, before the proposal is submitted.
*
* Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the
* same proposal (with same operation and same description) will have the same id if submitted on multiple governors
* accross multiple networks. This also means that in order to execute the same operation twice (on the same
* governor) the proposer will have to change the description in order to avoid proposal id conflicts.
*/
function hashProposal(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public pure virtual override returns (uint256) {
return
uint256(
keccak256(
abi.encode(targets, values, calldatas, descriptionHash)
)
);
}
function updateExtraWeights(uint256 weight, uint256[] memory tokenIds)
public
onlyOwner
{
for (uint256 i = 0; i < tokenIds.length; i++) {
extraVotes[tokenIds[i]] = weight;
}
}
function updateMinusWeights(uint256 weight, uint256[] memory tokenIds)
public
onlyOwner
{
for (uint256 i = 0; i < tokenIds.length; i++) {
minusVotes[tokenIds[i]] = weight;
}
}
function tokenVoteWeight(uint256 tokenId) internal view returns (uint256) {
return 1 + extraVotes[tokenId] - minusVotes[tokenId];
}
function updateMaxes() internal {
uint256 tokenMaxSupply = token.totalSupply();
if (lastMaxTokenSupply != tokenMaxSupply) {
for (uint256 i = lastMaxTokenSupply; i < tokenMaxSupply; i++) {
lastMaxVotes += tokenVoteWeight(i);
}
lastMaxTokenSupply = tokenMaxSupply;
}
}
function refreshMaxes() public onlyOwner {
lastMaxVotes = 0;
lastMaxTokenSupply = 0;
updateMaxes();
}
/**
* @dev See {IGovernor-state}.
*/
function state(uint256 proposalId)
public
view
virtual
override
returns (ProposalState)
{
ProposalVote storage proposal = _proposals[proposalId];
if (proposal.executed) {
return ProposalState.Executed;
} else if (proposal.canceled) {
return ProposalState.Canceled;
} else if (proposal.voteStart.isPending()) {
return ProposalState.Pending;
} else if (proposal.voteEnd.isPending()) {
return ProposalState.Active;
} else if (proposal.voteEnd.isExpired()) {
return
_quorumReached(proposalId) && _voteSucceeded(proposalId)
? ProposalState.Succeeded
: ProposalState.Defeated;
} else {
revert("Governor: unknown proposal id");
}
}
/**
* @dev See {IGovernor-proposalSnapshot}.
*/
function proposalSnapshot(uint256 proposalId)
public
view
virtual
override
returns (uint256)
{
return _proposals[proposalId].voteStart.getDeadline();
}
/**
* @dev See {IGovernor-proposalDeadline}.
*/
function proposalDeadline(uint256 proposalId)
public
view
virtual
override
returns (uint256)
{
return _proposals[proposalId].voteEnd.getDeadline();
}
/**
* @dev Amount of votes already cast passes the threshold limit.
*/
function _quorumReached(uint256 proposalId)
internal
view
virtual
returns (bool);
/**
* @dev Is the proposal successful or not.
*/
function _voteSucceeded(uint256 proposalId)
internal
view
virtual
returns (bool);
/**
* @dev Register a vote with a given support and voting weight.
*
* Note: Support is generic and can represent various things depending on the voting system used.
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support
) internal virtual returns (uint256);
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
uint256 proposalId = hashProposal(
targets,
values,
calldatas,
keccak256(bytes(description))
);
require(
targets.length == values.length,
"Governor: invalid proposal length"
);
require(
targets.length == calldatas.length,
"Governor: invalid proposal length"
);
require(targets.length > 0, "Governor: empty proposal");
updateMaxes();
ProposalVote storage proposal = _proposals[proposalId];
require(
proposal.voteStart.isUnset(),
"Governor: proposal already exists"
);
uint64 snapshot = block.number.toUint64() + votingDelay().toUint64();
uint64 deadline = snapshot + votingPeriod().toUint64();
proposal.voteStart.setDeadline(snapshot);
proposal.voteEnd.setDeadline(deadline);
proposal.maxTokens = lastMaxTokenSupply;
proposal.maxVotes = lastMaxVotes;
proposalIndexes[totalProposals] = proposalId;
totalProposals += 1;
emit ProposalCreated(
proposalId,
_msgSender(),
targets,
values,
new string[](targets.length),
calldatas,
snapshot,
deadline,
description
);
return proposalId;
}
/**
* @dev See {IGovernor-execute}.
*/
function execute(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) public payable virtual override nonReentrant returns (uint256) {
uint256 proposalId = hashProposal(
targets,
values,
calldatas,
descriptionHash
);
ProposalState status = state(proposalId);
require(
status == ProposalState.Succeeded || status == ProposalState.Queued,
"Governor: proposal not successful"
);
_proposals[proposalId].executed = true;
emit ProposalExecuted(proposalId);
_execute(proposalId, targets, values, calldatas, descriptionHash);
return proposalId;
}
/**
* @dev Internal execution mechanism. Can be overriden to implement different execution mechanism
*/
function _execute(
uint256, /* proposalId */
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 /*descriptionHash*/
) internal virtual {
string memory errorMessage = "Governor: call reverted without message";
for (uint256 i = 0; i < targets.length; ++i) {
(bool success, bytes memory returndata) = targets[i].call{
value: values[i]
}(calldatas[i]);
Address._verifyCallResult(success, returndata, errorMessage);
}
}
/**
* @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as
* canceled to allow distinguishing it from executed proposals.
*
* Emits a {IGovernor-ProposalCanceled} event.
*/
function _cancel(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
bytes32 descriptionHash
) internal virtual returns (uint256) {
uint256 proposalId = hashProposal(
targets,
values,
calldatas,
descriptionHash
);
ProposalState status = state(proposalId);
require(
status != ProposalState.Canceled &&
status != ProposalState.Expired &&
status != ProposalState.Executed,
"Governor: proposal not active"
);
_proposals[proposalId].canceled = true;
emit ProposalCanceled(proposalId);
return proposalId;
}
/**
* @dev See {IGovernor-castVote}.
*/
function castVote(uint256 proposalId, uint8 support)
public
virtual
override
returns (uint256)
{
address voter = _msgSender();
return _castVote(proposalId, voter, support, "");
}
/**
* @dev See {IGovernor-castVoteWithReason}.
*/
function castVoteWithReason(
uint256 proposalId,
uint8 support,
string calldata reason
) public virtual override returns (uint256) {
address voter = _msgSender();
return _castVote(proposalId, voter, support, reason);
}
/**
* @dev See {IGovernor-castVoteBySig}.
*/
function castVoteBySig(
uint256 proposalId,
uint8 support,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override returns (uint256) {
address voter = ECDSA.recover(
_hashTypedDataV4(
keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))
),
v,
r,
s
);
return _castVote(proposalId, voter, support, "");
}
/**
* @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve
* voting weight using {IGovernor-getVotes} and call the {_countVote} internal function.
*
* Emits a {IGovernor-VoteCast} event.
*/
function _castVote(
uint256 proposalId,
address account,
uint8 support,
string memory reason
) internal virtual returns (uint256) {
require(
state(proposalId) == ProposalState.Active,
"Governor: vote not currently active"
);
uint256 weight = _countVote(proposalId, account, support);
emit VoteCast(account, proposalId, support, weight, reason);
return weight;
}
/**
* @dev Address through which the governor executes action. Will be overloaded by module that execute actions
* through another contract such as a timelock.
*/
function _executor() internal view virtual returns (address) {
return address(this);
}
}
abstract contract GovernorProposalThreshold is Governor {
/**
* @dev See {IGovernor-propose}.
*/
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public virtual override returns (uint256) {
require(
getVotes(msg.sender, block.number - 1) >= proposalThreshold(),
"GovernorCompatibilityBravo: proposer votes below proposal threshold"
);
return super.propose(targets, values, calldatas, description);
}
/**
* @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_.
*/
function proposalThreshold() public view virtual returns (uint256);
}
abstract contract GovernorCountingSimple is Governor {
/**
* @dev Supported vote types. Matches Governor Bravo ordering.
*/
enum VoteType {
Against,
For,
Abstain
}
/**
* @dev See {IGovernor-COUNTING_MODE}.
*/
// solhint-disable-next-line func-name-mixedcase
function COUNTING_MODE()
public
pure
virtual
override
returns (string memory)
{
return "support=bravo&quorum=for,abstain";
}
function getVotes(address account, uint256)
public
view
virtual
override
returns (uint256 voteAmount)
{
uint256 tokenCount = token.balanceOf(account);
uint256 tokenId;
for (uint256 i = 0; i < tokenCount; i++) {
tokenId = token.tokenOfOwnerByIndex(account, i);
voteAmount += tokenVoteWeight(tokenId);
}
return voteAmount;
}
function votesLeft(uint256 proposalId, address account)
public
view
virtual
returns (uint256 voteAmount)
{
uint256 tokenCount = token.balanceOf(account);
uint256 tokenId;
ProposalVote storage proposalvote = _proposals[proposalId];
uint256 maxTokens = proposalvote.maxTokens;
for (uint256 i = 0; i < tokenCount; i++) {
tokenId = token.tokenOfOwnerByIndex(account, i);
if (!proposalvote.tokenHasVoted[tokenId] && tokenId < maxTokens) {
voteAmount += tokenVoteWeight(tokenId);
}
}
return voteAmount;
}
/**
* @dev See {IGovernor-hasVoted}.
*/
function hasVoted(uint256 proposalId, address account)
public
view
virtual
override
returns (bool)
{
return _proposals[proposalId].voteCount[account] > 0;
}
/**
* @dev Accessor to the internal vote counts.
*/
function proposalVotes(uint256 proposalId)
public
view
virtual
returns (
uint256 againstVotes,
uint256 forVotes,
uint256 abstainVotes
)
{
ProposalVote storage proposalvote = _proposals[proposalId];
return (
proposalvote.againstVotes,
proposalvote.forVotes,
proposalvote.abstainVotes
);
}
function getProposal(uint256 proposalId)
public
view
virtual
returns (
string memory currentState,
uint256 againstVotes,
uint256 forVotes,
uint256 abstainVotes,
uint256 totalVotes,
uint256 minQuorum,
uint256 maxVotes,
uint256 maxTokens
)
{
string[8] memory proposalStates;
proposalStates = [
"Pending",
"Active",
"Canceled",
"Defeated",
"Succeeded",
"Queued",
"Expired",
"Executed"
];
ProposalVote storage proposalvote = _proposals[proposalId];
return (
proposalStates[uint256(state(proposalId))],
proposalvote.againstVotes,
proposalvote.forVotes,
proposalvote.abstainVotes,
proposalvote.againstVotes +
proposalvote.forVotes +
proposalvote.abstainVotes,
quorum(proposalvote.maxVotes),
proposalvote.maxVotes,
proposalvote.maxTokens
);
}
function getProposalAccountVotes(uint256 proposalId, address owner)
public
view
virtual
returns (uint256 ownerVoteCount)
{
ProposalVote storage proposalvote = _proposals[proposalId];
return (proposalvote.voteCount[owner]);
}
function hasTokenVoted(uint256 proposalId, uint256 tokenId)
public
view
virtual
returns (bool tokenVoted)
{
ProposalVote storage proposalvote = _proposals[proposalId];
return (proposalvote.tokenHasVoted[tokenId]);
}
/**
* @dev See {Governor-_quorumReached}.
*/
function _quorumReached(uint256 proposalId)
internal
view
virtual
override
returns (bool)
{
ProposalVote storage proposalvote = _proposals[proposalId];
return
quorum(_proposals[proposalId].maxVotes) <=
proposalvote.forVotes + proposalvote.abstainVotes;
}
/**
* @dev See {Governor-_voteSucceeded}. In this module, the forVotes must be scritly over the againstVotes.
*/
function _voteSucceeded(uint256 proposalId)
internal
view
virtual
override
returns (bool)
{
ProposalVote storage proposalvote = _proposals[proposalId];
return proposalvote.forVotes > proposalvote.againstVotes;
}
/**
* @dev See {Governor-_countVote}. In this module, the support follows the `VoteType` enum (from Governor Bravo).
*/
function _countVote(
uint256 proposalId,
address account,
uint8 support
) internal virtual override returns (uint256 voteAmount) {
ProposalVote storage proposalvote = _proposals[proposalId];
uint256 tokenCount = token.balanceOf(account);
uint256 tokenId;
for (uint256 i = 0; i < tokenCount; i++) {
tokenId = token.tokenOfOwnerByIndex(account, i);
if (
!proposalvote.tokenHasVoted[tokenId] &&
tokenId < proposalvote.maxTokens
) {
proposalvote.tokenHasVoted[tokenId] = true;
voteAmount += tokenVoteWeight(tokenId);
}
}
require(voteAmount > 0, "GovernorVotingSimple: No votes left");
proposalvote.voteCount[account] += voteAmount;
if (support == uint8(VoteType.Against)) {
proposalvote.againstVotes += voteAmount;
} else if (support == uint8(VoteType.For)) {
proposalvote.forVotes += voteAmount;
} else if (support == uint8(VoteType.Abstain)) {
proposalvote.abstainVotes += voteAmount;
} else {
revert("GovernorVotingSimple: invalid value for enum VoteType");
}
}
}
abstract contract GovernorVotesQuorumFraction is Governor {
uint256 private _quorumNumerator;
event QuorumNumeratorUpdated(
uint256 oldQuorumNumerator,
uint256 newQuorumNumerator
);
constructor(uint256 quorumNumeratorValue) {
_updateQuorumNumerator(quorumNumeratorValue);
}
function quorumNumerator() public view virtual returns (uint256) {
return _quorumNumerator;
}
function quorumDenominator() public view virtual returns (uint256) {
return 100;
}
function quorum(uint256 totalVotes)
public
view
virtual
override
returns (uint256)
{
return (totalVotes * quorumNumerator()) / quorumDenominator();
}
function updateQuorumNumerator(uint256 newQuorumNumerator)
external
virtual
onlyGovernance
{
_updateQuorumNumerator(newQuorumNumerator);
}
function _updateQuorumNumerator(uint256 newQuorumNumerator)
internal
virtual
{
require(
newQuorumNumerator <= quorumDenominator(),
"GovernorVotesQuorumFraction: quorumNumerator over quorumDenominator"
);
uint256 oldQuorumNumerator = _quorumNumerator;
_quorumNumerator = newQuorumNumerator;
emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator);
}
}
contract WOWDGovernor is
Governor,
GovernorProposalThreshold,
GovernorCountingSimple,
GovernorVotesQuorumFraction
{
uint256 private _votingPeriod = 23000; // ~0.5 week
uint256 private _proposalThreshold = 11;
constructor() Governor("WOWDGovernor") GovernorVotesQuorumFraction(18) {}
function votingDelay() public pure override returns (uint256) {
return 1; // 1 block
}
function votingPeriod() public view override returns (uint256) {
return _votingPeriod;
}
function setVotingPeriod(uint256 newPeriod) external onlyGovernance {
_votingPeriod = newPeriod;
}
function proposalThreshold() public view override returns (uint256) {
return _proposalThreshold;
}
function setProposalThreshold(uint256 newThreshhold)
external
onlyGovernance
{
_proposalThreshold = newThreshhold;
}
// The following functions are overrides required by Solidity.
function quorum(uint256 totalVotes)
public
view
override(IGovernor, GovernorVotesQuorumFraction)
returns (uint256)
{
return super.quorum(totalVotes);
}
function getVotes(address account, uint256 blockNumber)
public
view
override(IGovernor, GovernorCountingSimple)
returns (uint256)
{
return super.getVotes(account, blockNumber);
}
function shoutOut(string memory mouthVomit) external onlyGovernance {
emit Shout(mouthVomit);
}
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) public override(Governor, GovernorProposalThreshold) returns (uint256) {
return super.propose(targets, values, calldatas, description);
}
function proposeShout(string memory description) public returns (uint256) {
return _proShout(description, 0);
}
function executeShout(string memory description) public returns (uint256) {
return _proShout(description, 1);
}
function _proShout(string memory description, uint256 exec)
private
returns (uint256)
{
bytes[] memory payload = new bytes[](1);
payload[0] = abi.encodeWithSignature("shoutOut(string)", description);
address[] memory targets = new address[](1);
targets[0] = address(this);
uint256[] memory values = new uint256[](1);
values[0] = 0;
if (exec == 1) {
return
execute(
targets,
values,
payload,
keccak256(bytes(description))
);
}
return super.propose(targets, values, payload, description);
}
function proposeNominate(
address recipient,
uint256 amountWei,
string memory description
) public returns (uint256) {
return _proNominate(recipient, amountWei, description, 0);
}
function executeNominate(
address recipient,
uint256 amountWei,
string memory description
) public returns (uint256) {
return _proNominate(recipient, amountWei, description, 1);
}
function _proNominate(
address recipient,
uint256 amountWei,
string memory description,
uint256 exec
) private returns (uint256) {
bytes[] memory payload = new bytes[](1);
address[] memory targets = new address[](1);
targets[0] = payable(recipient);
uint256[] memory values = new uint256[](1);
values[0] = amountWei;
if (exec == 1) {
return
execute(
targets,
values,
payload,
keccak256(bytes(description))
);
}
return super.propose(targets, values, payload, description);
}
function deposit() external payable {}
fallback() external payable {}
receive() external payable {}
}
|
See {IGovernor-hasVoted}./
|
function hasVoted(uint256 proposalId, address account)
public
view
virtual
override
returns (bool)
{
return _proposals[proposalId].voteCount[account] > 0;
}
| 14,851,109
|
pragma solidity ^0.5.8;
interface IERC20 {
function TRANSFER724(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE450(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM582(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TOTALSUPPLY554() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF56(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE828(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
event TRANSFER888(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL427(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function MUL717(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV665(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function SUB307(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD782(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD290(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function TOTALSUPPLY554() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF56(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE828(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER724(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER626(msg.sender, to, value);
return true;
}
function APPROVE450(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit APPROVAL427(msg.sender, spender, value);
return true;
}
function TRANSFERFROM582(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_allowed[from][msg.sender] = _allowed[from][msg.sender].SUB307(value);
_TRANSFER626(from, to, value);
emit APPROVAL427(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function INCREASEALLOWANCE446(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].ADD782(addedValue);
emit APPROVAL427(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function DECREASEALLOWANCE961(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].SUB307(subtractedValue);
emit APPROVAL427(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _TRANSFER626(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB307(value);
_balances[to] = _balances[to].ADD782(value);
emit TRANSFER888(from, to, value);
}
function _MINT544(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.ADD782(value);
_balances[account] = _balances[account].ADD782(value);
emit TRANSFER888(address(0), account, value);
}
function _BURN975(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0));
_totalSupply = _totalSupply.SUB307(value);
_balances[account] = _balances[account].SUB307(value);
emit TRANSFER888(account, address(0), value);
}
function _BURNFROM846(address account, uint256 value) internal { //inject NONSTANDARD NAMING
_allowed[account][msg.sender] = _allowed[account][msg.sender].SUB307(value);
_BURN975(account, value);
emit APPROVAL427(account, msg.sender, _allowed[account][msg.sender]);
}
}
contract ReentrancyGuard {
uint256 private _guardCounter;
constructor() public {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
modifier NONREENTRANT386() { //inject NONSTANDARD NAMING
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
contract WrappedCF is ERC20, ReentrancyGuard {
// OpenZeppelin's SafeMath library is used for all arithmetic operations to avoid overflows/underflows.
using SafeMath for uint256;
event DEPOSITCHAINFACEANDMINTTOKEN337( //inject NONSTANDARD NAMING
uint256 chainFaceId
);
event BURNTOKENANDWITHDRAWCHAINFACE646( //inject NONSTANDARD NAMING
uint256 chainFaceId
);
uint256[] private depositedChainFacesArray;
mapping (uint256 => bool) private chainFaceIsDepositedInContract;
uint8 constant public decimals546 = 18; //inject NONSTANDARD NAMING
string constant public name676 = "Wrapped ChainFaces"; //inject NONSTANDARD NAMING
string constant public symbol233 = "WCF"; //inject NONSTANDARD NAMING
address public chainFaceCoreAddress = 0x91047Abf3cAb8da5A9515c8750Ab33B4f1560a7A;
ChainFaceCore chainFaceCore;
function DEPOSITCHAINFACESANDMINTTOKENS562(uint256[] calldata _chainFaceIds) external NONREENTRANT386 { //inject NONSTANDARD NAMING
require(_chainFaceIds.length > 0, 'you must submit an array with at least one element');
for(uint i = 0; i < _chainFaceIds.length; i++){
uint256 chainFaceToDeposit = _chainFaceIds[i];
require(msg.sender == chainFaceCore.OWNEROF414(chainFaceToDeposit), 'you do not own this ChainFace');
require(chainFaceCore.chainFaceIndexToApproved(chainFaceToDeposit) == address(this), 'you must approve() this contract to give it permission to withdraw this ChainFace before you can deposit a ChainFace');
chainFaceCore.TRANSFERFROM582(msg.sender, address(this), chainFaceToDeposit);
_PUSHCHAINFACE471(chainFaceToDeposit);
emit DEPOSITCHAINFACEANDMINTTOKEN337(chainFaceToDeposit);
}
_MINT544(msg.sender, (_chainFaceIds.length).MUL717(10**18));
}
function BURNTOKENSANDWITHDRAWCHAINFACES175(uint256[] calldata _chainFaceIds, address[] calldata _destinationAddresses) external NONREENTRANT386 { //inject NONSTANDARD NAMING
require(_chainFaceIds.length == _destinationAddresses.length, 'you did not provide a destination address for each of the ChainFaces you wish to withdraw');
require(_chainFaceIds.length > 0, 'you must submit an array with at least one element');
uint256 numTokensToBurn = _chainFaceIds.length;
require(BALANCEOF56(msg.sender) >= numTokensToBurn.MUL717(10**18), 'you do not own enough tokens to withdraw this many ERC721 ChainFaces');
_BURN975(msg.sender, numTokensToBurn.MUL717(10**18));
for(uint i = 0; i < numTokensToBurn; i++){
uint256 chainFaceToWithdraw = _chainFaceIds[i];
if(chainFaceToWithdraw == 0){
chainFaceToWithdraw = _POPCHAINFACE288();
} else {
require(chainFaceIsDepositedInContract[chainFaceToWithdraw] == true, 'this chainFace has already been withdrawn');
require(address(this) == chainFaceCore.OWNEROF414(chainFaceToWithdraw), 'the contract does not own this ChainFace');
chainFaceIsDepositedInContract[chainFaceToWithdraw] = false;
}
chainFaceCore.TRANSFER724(_destinationAddresses[i], chainFaceToWithdraw);
emit BURNTOKENANDWITHDRAWCHAINFACE646(chainFaceToWithdraw);
}
}
function _PUSHCHAINFACE471(uint256 _chainFaceIds) internal { //inject NONSTANDARD NAMING
depositedChainFacesArray.push(_chainFaceIds);
chainFaceIsDepositedInContract[_chainFaceIds] = true;
}
function _POPCHAINFACE288() internal returns(uint256){ //inject NONSTANDARD NAMING
require(depositedChainFacesArray.length > 0, 'there are no ChainFaces in the array');
uint256 chainFaceId = depositedChainFacesArray[depositedChainFacesArray.length - 1];
depositedChainFacesArray.length--;
while(chainFaceIsDepositedInContract[chainFaceId] == false){
chainFaceId = depositedChainFacesArray[depositedChainFacesArray.length - 1];
depositedChainFacesArray.length--;
}
chainFaceIsDepositedInContract[chainFaceId] = false;
return chainFaceId;
}
function BATCHREMOVEWITHDRAWNCHAINFACESFROMSTORAGE793(uint256 _numSlotsToCheck) external { //inject NONSTANDARD NAMING
require(_numSlotsToCheck <= depositedChainFacesArray.length, 'you are trying to batch remove more slots than exist in the array');
uint256 arrayIndex = depositedChainFacesArray.length;
for(uint i = 0; i < _numSlotsToCheck; i++){
arrayIndex = arrayIndex.SUB307(1);
uint256 chainFaceId = depositedChainFacesArray[arrayIndex];
if(chainFaceIsDepositedInContract[chainFaceId] == false){
depositedChainFacesArray.length--;
} else {
return;
}
}
}
constructor() public {
chainFaceCore = ChainFaceCore(chainFaceCoreAddress);
}
function() external payable {}
}
contract ChainFaceCore {
function OWNEROF414(uint256 _tokenId) public view returns (address owner); //inject NONSTANDARD NAMING
function TRANSFERFROM582(address _from, address _to, uint256 _tokenId) external; //inject NONSTANDARD NAMING
function TRANSFER724(address _to, uint256 _tokenId) external; //inject NONSTANDARD NAMING
mapping (uint256 => address) public chainFaceIndexToApproved;
}
|
inject NONSTANDARD NAMING
|
function INCREASEALLOWANCE446(address spender, uint256 addedValue) public returns (bool) {
| 2,579,022
|
pragma solidity 0.4.18;
import "zeppelin-solidity/contracts/ownership/Ownable.sol";
/**
* The TokenRegistry is a basic registry mapping token symbols
* to their known, deployed addresses on the current blockchain.
*
* Note that the TokenRegistry does *not* mediate any of the
* core protocol's business logic, but, rather, is a helpful
* utility for Terms Contracts to use in encoding, decoding, and
* resolving the addresses of currently deployed tokens.
*
* At this point in time, administration of the Token Registry is
* under Dharma Labs' control. With more sophisticated decentralized
* governance mechanisms, we intend to shift ownership of this utility
* contract to the Dharma community.
*/
contract TokenRegistry is Ownable {
mapping (bytes32 => address) public symbolHashToTokenAddress;
mapping (bytes32 => uint) public symbolHashToTokenIndex;
string[256] public tokenSymbolList;
uint8 public tokenSymbolListLength;
/**
* Maps the given symbol to the given token address.
*/
function setTokenAddress(string symbol, address token) public onlyOwner {
require(tokenSymbolListLength < 256);
bytes32 symbolHash = keccak256(symbol);
if (symbolHashToTokenAddress[symbolHash] == address(0)) {
tokenSymbolList[tokenSymbolListLength] = symbol;
symbolHashToTokenIndex[symbolHash] = tokenSymbolListLength;
tokenSymbolListLength++;
}
symbolHashToTokenAddress[symbolHash] = token;
}
/**
* Given a symbol, resolves the current address of the token the symbol is mapped to.
*/
function getTokenAddressBySymbol(string symbol) public view returns (address) {
return symbolHashToTokenAddress[keccak256(symbol)];
}
/**
* Given the known index of a token within the registry's symbol list,
* returns the address of the token mapped to the symbol at that index.
*
* This is a useful utility for compactly encoding the address of a token into a
* TermsContractParameters string -- by encoding a token by its index in a
* a 256 slot array, we can represent a token by a 1 byte uint instead of a 20 byte address.
*/
function getTokenAddressByIndex(uint index) public view returns (address) {
string storage symbol = tokenSymbolList[index];
return symbolHashToTokenAddress[keccak256(symbol)];
}
/**
* Given a symbol, resolves the index of the token the symbol is mapped to within the registry's
* symbol list.
*/
function getTokenIndexBySymbol(string symbol) public view returns (uint) {
return symbolHashToTokenIndex[keccak256(symbol)];
}
/**
* Given an index, resolves the symbol of the token at that index in the registry's
* token symbol list.
*/
function getTokenSymbolByIndex(uint index) public view returns (string) {
return tokenSymbolList[index];
}
}
|
Given a symbol, resolves the current address of the token the symbol is mapped to./
|
function getTokenAddressBySymbol(string symbol) public view returns (address) {
return symbolHashToTokenAddress[keccak256(symbol)];
}
| 2,528,066
|
./partial_match/100/0x82A89e47c9f4342B1C33887e1783a091796D7978/sources/BancorMarketMaker.sol
|
Add `_collateral.symbol(): string` as a whitelisted collateral token _collateral The address of the collateral token to be whitelisted _virtualSupply The virtual supply to be used for that collateral token [in wei] _virtualBalance The virtual balance to be used for that collateral token [in wei] _reserveRatio The reserve ratio to be used for that collateral token [in PPM]/
|
function addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio)
external auth(CONTROLLER_ROLE)
{
require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL);
require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED);
require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO);
_addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio);
}
| 16,661,692
|
./full_match/43113/0x29FB6CA56d7F4485eCBaf0AEd941d52E7A662307/sources/contracts/protocol/SetToken.sol
|
PRIVELEGED MODULE FUNCTION. Decreases the "account" balance by the "quantity". _burn checks that the "account" already has the required "quantity"./
|
function burn(address _account, uint256 _quantity) external onlyModule whenLockedOnlyLocker {
_burn(_account, _quantity);
}
| 7,191,736
|
/**
*Submitted for verification at Etherscan.io on 2021-04-27
*/
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like 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/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4);
}
// File: @openzeppelin/contracts/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @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 override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
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/utils/EnumerableSet.sol
// SPDX-License-Identifier: MIT
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/utils/EnumerableMap.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
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);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// File: @openzeppelin/contracts/utils/Counters.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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 {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: @openzeppelin/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
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: contracts/AlohaNFTv1.sol
pragma solidity 0.6.6;
contract AlohaNFTv1 is ERC721, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
mapping (uint256 => uint256) private _tokenImages;
mapping (uint256 => uint256) private _tokenRarities;
mapping (uint256 => uint256) private _tokenBackgrounds;
constructor(
string memory name,
string memory symbol,
string memory baseURI
) public ERC721(name, symbol) {
_setBaseURI(baseURI);
}
/**
* @dev Mints a new ALOHA NFT for a wallet.
*/
function awardItem(
address wallet,
uint256 tokenImage,
uint256 tokenRarity,
uint256 tokenBackground
)
public
onlyOwner()
returns (uint256)
{
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(wallet, newItemId);
_setTokenImage(newItemId, tokenImage);
_setTokenRarity(newItemId, tokenRarity);
_setTokenBackground(newItemId, tokenBackground);
return newItemId;
}
function _setTokenImage(uint256 tokenId, uint256 _tokenImage) internal virtual {
require(_exists(tokenId), "ERC721Metadata: Image set of nonexistent token");
_tokenImages[tokenId] = _tokenImage;
}
function _setTokenRarity(uint256 tokenId, uint256 _tokenRarity) internal virtual {
require(_exists(tokenId), "ERC721Metadata: Rarity set of nonexistent token");
_tokenRarities[tokenId] = _tokenRarity;
}
function _setTokenBackground(uint256 tokenId, uint256 _tokenBackground) internal virtual {
require(_exists(tokenId), "ERC721Metadata: Background set of nonexistent token");
_tokenBackgrounds[tokenId] = _tokenBackground;
}
function tokenImage(uint256 tokenId) public view returns (uint256) {
require(_exists(tokenId), "ERC721Metadata: Image query for nonexistent token");
return _tokenImages[tokenId];
}
function tokenRarity(uint256 tokenId) public view returns (uint256) {
require(_exists(tokenId), "ERC721Metadata: Rarity query for nonexistent token");
return _tokenRarities[tokenId];
}
function tokenBackground(uint256 tokenId) public view returns (uint256) {
require(_exists(tokenId), "ERC721Metadata: Background query for nonexistent token");
return _tokenBackgrounds[tokenId];
}
}
// File: contracts/AlohaNFT.sol
pragma solidity 0.6.6;
contract AlohaNFTv2 is ERC721, AccessControl {
using SafeMath for uint256;
using SafeMath for uint8;
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
bytes32 public constant MINTER = keccak256("MINTER");
address alohaNFTv1;
mapping (uint256 => bool) public migratedTokens;
mapping (uint256 => uint256) private _tokenRarities;
mapping (uint256 => uint256) private _tokenImages;
mapping (uint256 => uint256) private _tokenBackgrounds;
constructor(
address _alohaNFTv1
) public ERC721("ALOHA NFT", "ANFT") {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
alohaNFTv1 = _alohaNFTv1;
}
/**
* @dev Mints a new ALOHA NFT for a wallet.
*/
function awardItem(
address wallet,
uint256 rarity,
uint256 image,
uint256 background
)
public
returns (uint256)
{
require(hasRole(MINTER, msg.sender), 'AlohaNFT: Only for role MINTER');
_tokenIds.increment();
uint256 newTokenId = _tokenIds.current();
_mint(wallet, newTokenId);
_setTokenImage(newTokenId, image);
_setTokenRarity(newTokenId, rarity);
_setTokenBackground(newTokenId, background);
return newTokenId;
}
/**
* @dev Returns the rarity for token.
*/
function tokenRarity(uint256 tokenId) public view returns (uint256) {
require(_exists(tokenId), "AlohaNFT: Query for nonexistent token");
return _tokenRarities[tokenId];
}
/**
* @dev Returns the image for token.
*/
function tokenImage(uint256 tokenId) public view returns (uint256) {
require(_exists(tokenId), "AlohaNFT: Query for nonexistent token");
return _tokenImages[tokenId];
}
/**
* @dev Returns the background for token.
*/
function tokenBackground(uint256 tokenId) public view returns (uint256) {
require(_exists(tokenId), "AlohaNFT: Query for nonexistent token");
return _tokenBackgrounds[tokenId];
}
/**
* @dev Aloha NFT v1 => Aloha NFT v2.
*/
function migrateToken(uint256 v1TokenId) public returns (uint256) {
require(!migratedTokens[v1TokenId], "AlohaNFT: Token already migrated");
uint256 v1TokenRarity = AlohaNFTv1(alohaNFTv1).tokenRarity(v1TokenId);
uint256 v1TokenImage = AlohaNFTv1(alohaNFTv1).tokenImage(v1TokenId);
uint256 v1TokenBackground = AlohaNFTv1(alohaNFTv1).tokenBackground(v1TokenId);
address v1TokenOwner = AlohaNFTv1(alohaNFTv1).ownerOf(v1TokenId);
_tokenIds.increment();
uint256 newTokenId = _tokenIds.current();
migratedTokens[v1TokenId] = true;
AlohaNFTv1(alohaNFTv1).transferFrom(v1TokenOwner, address(this), v1TokenId);
_mint(v1TokenOwner, newTokenId);
_setTokenImage(newTokenId, v1TokenImage);
_setTokenRarity(newTokenId, v1TokenRarity);
_setTokenBackground(newTokenId, v1TokenBackground);
return newTokenId;
}
/**
* @dev Updates the base URI
*/
function setBaseURI(string memory _baseURI) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), 'AlohaNFT: Only for role DEFAULT_ADMIN_ROLE');
_setBaseURI(_baseURI);
}
function _setTokenRarity(uint256 tokenId, uint256 _tokenRarity) internal virtual {
require(_exists(tokenId), "ERC721Metadata: Rarity set of nonexistent token");
_tokenRarities[tokenId] = _tokenRarity;
}
function _setTokenImage(uint256 tokenId, uint256 _tokenImage) internal virtual {
require(_exists(tokenId), "AlohaNFT: Image set for nonexistent token");
_tokenImages[tokenId] = _tokenImage;
}
function _setTokenBackground(uint256 tokenId, uint256 _tokenBackground) internal virtual {
require(_exists(tokenId), "AlohaNFT: Background set for nonexistent token");
_tokenBackgrounds[tokenId] = _tokenBackground;
}
}
|
Mints a new ALOHA NFT for a wallet./
|
function awardItem(
address wallet,
uint256 tokenImage,
uint256 tokenRarity,
uint256 tokenBackground
)
public
onlyOwner()
returns (uint256)
{
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(wallet, newItemId);
_setTokenImage(newItemId, tokenImage);
_setTokenRarity(newItemId, tokenRarity);
_setTokenBackground(newItemId, tokenBackground);
return newItemId;
}
| 1,965,440
|
pragma solidity 0.4.24;
pragma experimental "v0.5.0";
/*
Copyright 2018 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// File: openzeppelin-solidity/contracts/math/Math.sol
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 _a, uint64 _b) internal pure returns (uint64) {
return _a >= _b ? _a : _b;
}
function min64(uint64 _a, uint64 _b) internal pure returns (uint64) {
return _a < _b ? _a : _b;
}
function max256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a >= _b ? _a : _b;
}
function min256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/lib/AccessControlledBase.sol
/**
* @title AccessControlledBase
* @author dYdX
*
* Base functionality for access control. Requires an implementation to
* provide a way to grant and optionally revoke access
*/
contract AccessControlledBase {
// ============ State Variables ============
mapping (address => bool) public authorized;
// ============ Events ============
event AccessGranted(
address who
);
event AccessRevoked(
address who
);
// ============ Modifiers ============
modifier requiresAuthorization() {
require(
authorized[msg.sender],
"AccessControlledBase#requiresAuthorization: Sender not authorized"
);
_;
}
}
// File: contracts/lib/StaticAccessControlled.sol
/**
* @title StaticAccessControlled
* @author dYdX
*
* Allows for functions to be access controled
* Permissions cannot be changed after a grace period
*/
contract StaticAccessControlled is AccessControlledBase, Ownable {
using SafeMath for uint256;
// ============ State Variables ============
// Timestamp after which no additional access can be granted
uint256 public GRACE_PERIOD_EXPIRATION;
// ============ Constructor ============
constructor(
uint256 gracePeriod
)
public
Ownable()
{
GRACE_PERIOD_EXPIRATION = block.timestamp.add(gracePeriod);
}
// ============ Owner-Only State-Changing Functions ============
function grantAccess(
address who
)
external
onlyOwner
{
require(
block.timestamp < GRACE_PERIOD_EXPIRATION,
"StaticAccessControlled#grantAccess: Cannot grant access after grace period"
);
emit AccessGranted(who);
authorized[who] = true;
}
}
// File: contracts/lib/GeneralERC20.sol
/**
* @title GeneralERC20
* @author dYdX
*
* Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so
* that we dont automatically revert when calling non-compliant tokens that have no return value for
* transfer(), transferFrom(), or approve().
*/
interface GeneralERC20 {
function totalSupply(
)
external
view
returns (uint256);
function balanceOf(
address who
)
external
view
returns (uint256);
function allowance(
address owner,
address spender
)
external
view
returns (uint256);
function transfer(
address to,
uint256 value
)
external;
function transferFrom(
address from,
address to,
uint256 value
)
external;
function approve(
address spender,
uint256 value
)
external;
}
// File: contracts/lib/TokenInteract.sol
/**
* @title TokenInteract
* @author dYdX
*
* This library contains functions for interacting with ERC20 tokens
*/
library TokenInteract {
function balanceOf(
address token,
address owner
)
internal
view
returns (uint256)
{
return GeneralERC20(token).balanceOf(owner);
}
function allowance(
address token,
address owner,
address spender
)
internal
view
returns (uint256)
{
return GeneralERC20(token).allowance(owner, spender);
}
function approve(
address token,
address spender,
uint256 amount
)
internal
{
GeneralERC20(token).approve(spender, amount);
require(
checkSuccess(),
"TokenInteract#approve: Approval failed"
);
}
function transfer(
address token,
address to,
uint256 amount
)
internal
{
address from = address(this);
if (
amount == 0
|| from == to
) {
return;
}
GeneralERC20(token).transfer(to, amount);
require(
checkSuccess(),
"TokenInteract#transfer: Transfer failed"
);
}
function transferFrom(
address token,
address from,
address to,
uint256 amount
)
internal
{
if (
amount == 0
|| from == to
) {
return;
}
GeneralERC20(token).transferFrom(from, to, amount);
require(
checkSuccess(),
"TokenInteract#transferFrom: TransferFrom failed"
);
}
// ============ Private Helper-Functions ============
/**
* Checks the return value of the previous function up to 32 bytes. Returns true if the previous
* function returned 0 bytes or 32 bytes that are not all-zero.
*/
function checkSuccess(
)
private
pure
returns (bool)
{
uint256 returnValue = 0;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
// check number of bytes returned from last function call
switch returndatasize
// no bytes returned: assume success
case 0x0 {
returnValue := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// copy 32 bytes into scratch space
returndatacopy(0x0, 0x0, 0x20)
// load those bytes into returnValue
returnValue := mload(0x0)
}
// not sure what was returned: dont mark as success
default { }
}
return returnValue != 0;
}
}
// File: contracts/margin/TokenProxy.sol
/**
* @title TokenProxy
* @author dYdX
*
* Used to transfer tokens between addresses which have set allowance on this contract.
*/
contract TokenProxy is StaticAccessControlled {
using SafeMath for uint256;
// ============ Constructor ============
constructor(
uint256 gracePeriod
)
public
StaticAccessControlled(gracePeriod)
{}
// ============ Authorized-Only State Changing Functions ============
/**
* Transfers tokens from an address (that has set allowance on the proxy) to another address.
*
* @param token The address of the ERC20 token
* @param from The address to transfer token from
* @param to The address to transfer tokens to
* @param value The number of tokens to transfer
*/
function transferTokens(
address token,
address from,
address to,
uint256 value
)
external
requiresAuthorization
{
TokenInteract.transferFrom(
token,
from,
to,
value
);
}
// ============ Public Constant Functions ============
/**
* Getter function to get the amount of token that the proxy is able to move for a particular
* address. The minimum of 1) the balance of that address and 2) the allowance given to proxy.
*
* @param who The owner of the tokens
* @param token The address of the ERC20 token
* @return The number of tokens able to be moved by the proxy from the address specified
*/
function available(
address who,
address token
)
external
view
returns (uint256)
{
return Math.min256(
TokenInteract.allowance(token, who, address(this)),
TokenInteract.balanceOf(token, who)
);
}
}
// File: contracts/margin/Vault.sol
/**
* @title Vault
* @author dYdX
*
* Holds and transfers tokens in vaults denominated by id
*
* Vault only supports ERC20 tokens, and will not accept any tokens that require
* a tokenFallback or equivalent function (See ERC223, ERC777, etc.)
*/
contract Vault is StaticAccessControlled
{
using SafeMath for uint256;
// ============ Events ============
event ExcessTokensWithdrawn(
address indexed token,
address indexed to,
address caller
);
// ============ State Variables ============
// Address of the TokenProxy contract. Used for moving tokens.
address public TOKEN_PROXY;
// Map from vault ID to map from token address to amount of that token attributed to the
// particular vault ID.
mapping (bytes32 => mapping (address => uint256)) public balances;
// Map from token address to total amount of that token attributed to some account.
mapping (address => uint256) public totalBalances;
// ============ Constructor ============
constructor(
address proxy,
uint256 gracePeriod
)
public
StaticAccessControlled(gracePeriod)
{
TOKEN_PROXY = proxy;
}
// ============ Owner-Only State-Changing Functions ============
/**
* Allows the owner to withdraw any excess tokens sent to the vault by unconventional means,
* including (but not limited-to) token airdrops. Any tokens moved to the vault by TOKEN_PROXY
* will be accounted for and will not be withdrawable by this function.
*
* @param token ERC20 token address
* @param to Address to transfer tokens to
* @return Amount of tokens withdrawn
*/
function withdrawExcessToken(
address token,
address to
)
external
onlyOwner
returns (uint256)
{
uint256 actualBalance = TokenInteract.balanceOf(token, address(this));
uint256 accountedBalance = totalBalances[token];
uint256 withdrawableBalance = actualBalance.sub(accountedBalance);
require(
withdrawableBalance != 0,
"Vault#withdrawExcessToken: Withdrawable token amount must be non-zero"
);
TokenInteract.transfer(token, to, withdrawableBalance);
emit ExcessTokensWithdrawn(token, to, msg.sender);
return withdrawableBalance;
}
// ============ Authorized-Only State-Changing Functions ============
/**
* Transfers tokens from an address (that has approved the proxy) to the vault.
*
* @param id The vault which will receive the tokens
* @param token ERC20 token address
* @param from Address from which the tokens will be taken
* @param amount Number of the token to be sent
*/
function transferToVault(
bytes32 id,
address token,
address from,
uint256 amount
)
external
requiresAuthorization
{
// First send tokens to this contract
TokenProxy(TOKEN_PROXY).transferTokens(
token,
from,
address(this),
amount
);
// Then increment balances
balances[id][token] = balances[id][token].add(amount);
totalBalances[token] = totalBalances[token].add(amount);
// This should always be true. If not, something is very wrong
assert(totalBalances[token] >= balances[id][token]);
validateBalance(token);
}
/**
* Transfers a certain amount of funds to an address.
*
* @param id The vault from which to send the tokens
* @param token ERC20 token address
* @param to Address to transfer tokens to
* @param amount Number of the token to be sent
*/
function transferFromVault(
bytes32 id,
address token,
address to,
uint256 amount
)
external
requiresAuthorization
{
// Next line also asserts that (balances[id][token] >= amount);
balances[id][token] = balances[id][token].sub(amount);
// Next line also asserts that (totalBalances[token] >= amount);
totalBalances[token] = totalBalances[token].sub(amount);
// This should always be true. If not, something is very wrong
assert(totalBalances[token] >= balances[id][token]);
// Do the sending
TokenInteract.transfer(token, to, amount); // asserts transfer succeeded
// Final validation
validateBalance(token);
}
// ============ Private Helper-Functions ============
/**
* Verifies that this contract is in control of at least as many tokens as accounted for
*
* @param token Address of ERC20 token
*/
function validateBalance(
address token
)
private
view
{
// The actual balance could be greater than totalBalances[token] because anyone
// can send tokens to the contract's address which cannot be accounted for
assert(TokenInteract.balanceOf(token, address(this)) >= totalBalances[token]);
}
}
// File: contracts/lib/ReentrancyGuard.sol
/**
* @title ReentrancyGuard
* @author dYdX
*
* Optimized version of the well-known ReentrancyGuard contract
*/
contract ReentrancyGuard {
uint256 private _guardCounter = 1;
modifier nonReentrant() {
uint256 localCounter = _guardCounter + 1;
_guardCounter = localCounter;
_;
require(
_guardCounter == localCounter,
"Reentrancy check failure"
);
}
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// File: contracts/lib/Fraction.sol
/**
* @title Fraction
* @author dYdX
*
* This library contains implementations for fraction structs.
*/
library Fraction {
struct Fraction128 {
uint128 num;
uint128 den;
}
}
// File: contracts/lib/FractionMath.sol
/**
* @title FractionMath
* @author dYdX
*
* This library contains safe math functions for manipulating fractions.
*/
library FractionMath {
using SafeMath for uint256;
using SafeMath for uint128;
/**
* Returns a Fraction128 that is equal to a + b
*
* @param a The first Fraction128
* @param b The second Fraction128
* @return The result (sum)
*/
function add(
Fraction.Fraction128 memory a,
Fraction.Fraction128 memory b
)
internal
pure
returns (Fraction.Fraction128 memory)
{
uint256 left = a.num.mul(b.den);
uint256 right = b.num.mul(a.den);
uint256 denominator = a.den.mul(b.den);
// if left + right overflows, prevent overflow
if (left + right < left) {
left = left.div(2);
right = right.div(2);
denominator = denominator.div(2);
}
return bound(left.add(right), denominator);
}
/**
* Returns a Fraction128 that is equal to a - (1/2)^d
*
* @param a The Fraction128
* @param d The power of (1/2)
* @return The result
*/
function sub1Over(
Fraction.Fraction128 memory a,
uint128 d
)
internal
pure
returns (Fraction.Fraction128 memory)
{
if (a.den % d == 0) {
return bound(
a.num.sub(a.den.div(d)),
a.den
);
}
return bound(
a.num.mul(d).sub(a.den),
a.den.mul(d)
);
}
/**
* Returns a Fraction128 that is equal to a / d
*
* @param a The first Fraction128
* @param d The divisor
* @return The result (quotient)
*/
function div(
Fraction.Fraction128 memory a,
uint128 d
)
internal
pure
returns (Fraction.Fraction128 memory)
{
if (a.num % d == 0) {
return bound(
a.num.div(d),
a.den
);
}
return bound(
a.num,
a.den.mul(d)
);
}
/**
* Returns a Fraction128 that is equal to a * b.
*
* @param a The first Fraction128
* @param b The second Fraction128
* @return The result (product)
*/
function mul(
Fraction.Fraction128 memory a,
Fraction.Fraction128 memory b
)
internal
pure
returns (Fraction.Fraction128 memory)
{
return bound(
a.num.mul(b.num),
a.den.mul(b.den)
);
}
/**
* Returns a fraction from two uint256's. Fits them into uint128 if necessary.
*
* @param num The numerator
* @param den The denominator
* @return The Fraction128 that matches num/den most closely
*/
/* solium-disable-next-line security/no-assign-params */
function bound(
uint256 num,
uint256 den
)
internal
pure
returns (Fraction.Fraction128 memory)
{
uint256 max = num > den ? num : den;
uint256 first128Bits = (max >> 128);
if (first128Bits != 0) {
first128Bits += 1;
num /= first128Bits;
den /= first128Bits;
}
assert(den != 0); // coverage-enable-line
assert(den < 2**128);
assert(num < 2**128);
return Fraction.Fraction128({
num: uint128(num),
den: uint128(den)
});
}
/**
* Returns an in-memory copy of a Fraction128
*
* @param a The Fraction128 to copy
* @return A copy of the Fraction128
*/
function copy(
Fraction.Fraction128 memory a
)
internal
pure
returns (Fraction.Fraction128 memory)
{
validate(a);
return Fraction.Fraction128({ num: a.num, den: a.den });
}
// ============ Private Helper-Functions ============
/**
* Asserts that a Fraction128 is valid (i.e. the denominator is non-zero)
*
* @param a The Fraction128 to validate
*/
function validate(
Fraction.Fraction128 memory a
)
private
pure
{
assert(a.den != 0); // coverage-enable-line
}
}
// File: contracts/lib/Exponent.sol
/**
* @title Exponent
* @author dYdX
*
* This library contains an implementation for calculating e^X for arbitrary fraction X
*/
library Exponent {
using SafeMath for uint256;
using FractionMath for Fraction.Fraction128;
// ============ Constants ============
// 2**128 - 1
uint128 constant public MAX_NUMERATOR = 340282366920938463463374607431768211455;
// Number of precomputed integers, X, for E^((1/2)^X)
uint256 constant public MAX_PRECOMPUTE_PRECISION = 32;
// Number of precomputed integers, X, for E^X
uint256 constant public NUM_PRECOMPUTED_INTEGERS = 32;
// ============ Public Implementation Functions ============
/**
* Returns e^X for any fraction X
*
* @param X The exponent
* @param precomputePrecision Accuracy of precomputed terms
* @param maclaurinPrecision Accuracy of Maclaurin terms
* @return e^X
*/
function exp(
Fraction.Fraction128 memory X,
uint256 precomputePrecision,
uint256 maclaurinPrecision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
require(
precomputePrecision <= MAX_PRECOMPUTE_PRECISION,
"Exponent#exp: Precompute precision over maximum"
);
Fraction.Fraction128 memory Xcopy = X.copy();
if (Xcopy.num == 0) { // e^0 = 1
return ONE();
}
// get the integer value of the fraction (example: 9/4 is 2.25 so has integerValue of 2)
uint256 integerX = uint256(Xcopy.num).div(Xcopy.den);
// if X is less than 1, then just calculate X
if (integerX == 0) {
return expHybrid(Xcopy, precomputePrecision, maclaurinPrecision);
}
// get e^integerX
Fraction.Fraction128 memory expOfInt =
getPrecomputedEToThe(integerX % NUM_PRECOMPUTED_INTEGERS);
while (integerX >= NUM_PRECOMPUTED_INTEGERS) {
expOfInt = expOfInt.mul(getPrecomputedEToThe(NUM_PRECOMPUTED_INTEGERS));
integerX -= NUM_PRECOMPUTED_INTEGERS;
}
// multiply e^integerX by e^decimalX
Fraction.Fraction128 memory decimalX = Fraction.Fraction128({
num: Xcopy.num % Xcopy.den,
den: Xcopy.den
});
return expHybrid(decimalX, precomputePrecision, maclaurinPrecision).mul(expOfInt);
}
/**
* Returns e^X for any X < 1. Multiplies precomputed values to get close to the real value, then
* Maclaurin Series approximation to reduce error.
*
* @param X Exponent
* @param precomputePrecision Accuracy of precomputed terms
* @param maclaurinPrecision Accuracy of Maclaurin terms
* @return e^X
*/
function expHybrid(
Fraction.Fraction128 memory X,
uint256 precomputePrecision,
uint256 maclaurinPrecision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(precomputePrecision <= MAX_PRECOMPUTE_PRECISION);
assert(X.num < X.den);
// will also throw if precomputePrecision is larger than the array length in getDenominator
Fraction.Fraction128 memory Xtemp = X.copy();
if (Xtemp.num == 0) { // e^0 = 1
return ONE();
}
Fraction.Fraction128 memory result = ONE();
uint256 d = 1; // 2^i
for (uint256 i = 1; i <= precomputePrecision; i++) {
d *= 2;
// if Fraction > 1/d, subtract 1/d and multiply result by precomputed e^(1/d)
if (d.mul(Xtemp.num) >= Xtemp.den) {
Xtemp = Xtemp.sub1Over(uint128(d));
result = result.mul(getPrecomputedEToTheHalfToThe(i));
}
}
return result.mul(expMaclaurin(Xtemp, maclaurinPrecision));
}
/**
* Returns e^X for any X, using Maclaurin Series approximation
*
* e^X = SUM(X^n / n!) for n >= 0
* e^X = 1 + X/1! + X^2/2! + X^3/3! ...
*
* @param X Exponent
* @param precision Accuracy of Maclaurin terms
* @return e^X
*/
function expMaclaurin(
Fraction.Fraction128 memory X,
uint256 precision
)
internal
pure
returns (Fraction.Fraction128 memory)
{
Fraction.Fraction128 memory Xcopy = X.copy();
if (Xcopy.num == 0) { // e^0 = 1
return ONE();
}
Fraction.Fraction128 memory result = ONE();
Fraction.Fraction128 memory Xtemp = ONE();
for (uint256 i = 1; i <= precision; i++) {
Xtemp = Xtemp.mul(Xcopy.div(uint128(i)));
result = result.add(Xtemp);
}
return result;
}
/**
* Returns a fraction roughly equaling E^((1/2)^x) for integer x
*/
function getPrecomputedEToTheHalfToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(x <= MAX_PRECOMPUTE_PRECISION);
uint128 denominator = [
125182886983370532117250726298150828301,
206391688497133195273760705512282642279,
265012173823417992016237332255925138361,
300298134811882980317033350418940119802,
319665700530617779809390163992561606014,
329812979126047300897653247035862915816,
335006777809430963166468914297166288162,
337634268532609249517744113622081347950,
338955731696479810470146282672867036734,
339618401537809365075354109784799900812,
339950222128463181389559457827561204959,
340116253979683015278260491021941090650,
340199300311581465057079429423749235412,
340240831081268226777032180141478221816,
340261598367316729254995498374473399540,
340271982485676106947851156443492415142,
340277174663693808406010255284800906112,
340279770782412691177936847400746725466,
340281068849199706686796915841848278311,
340281717884450116236033378667952410919,
340282042402539547492367191008339680733,
340282204661700319870089970029119685699,
340282285791309720262481214385569134454,
340282326356121674011576912006427792656,
340282346638529464274601981200276914173,
340282356779733812753265346086924801364,
340282361850336100329388676752133324799,
340282364385637272451648746721404212564,
340282365653287865596328444437856608255,
340282366287113163939555716675618384724,
340282366604025813553891209601455838559,
340282366762482138471739420386372790954,
340282366841710300958333641874363209044
][x];
return Fraction.Fraction128({
num: MAX_NUMERATOR,
den: denominator
});
}
/**
* Returns a fraction roughly equaling E^(x) for integer x
*/
function getPrecomputedEToThe(
uint256 x
)
internal
pure
returns (Fraction.Fraction128 memory)
{
assert(x <= NUM_PRECOMPUTED_INTEGERS);
uint128 denominator = [
340282366920938463463374607431768211455,
125182886983370532117250726298150828301,
46052210507670172419625860892627118820,
16941661466271327126146327822211253888,
6232488952727653950957829210887653621,
2292804553036637136093891217529878878,
843475657686456657683449904934172134,
310297353591408453462393329342695980,
114152017036184782947077973323212575,
41994180235864621538772677139808695,
15448795557622704876497742989562086,
5683294276510101335127414470015662,
2090767122455392675095471286328463,
769150240628514374138961856925097,
282954560699298259527814398449860,
104093165666968799599694528310221,
38293735615330848145349245349513,
14087478058534870382224480725096,
5182493555688763339001418388912,
1906532833141383353974257736699,
701374233231058797338605168652,
258021160973090761055471434334,
94920680509187392077350434438,
34919366901332874995585576427,
12846117181722897538509298435,
4725822410035083116489797150,
1738532907279185132707372378,
639570514388029575350057932,
235284843422800231081973821,
86556456714490055457751527,
31842340925906738090071268,
11714142585413118080082437,
4309392228124372433711936
][x];
return Fraction.Fraction128({
num: MAX_NUMERATOR,
den: denominator
});
}
// ============ Private Helper-Functions ============
function ONE()
private
pure
returns (Fraction.Fraction128 memory)
{
return Fraction.Fraction128({ num: 1, den: 1 });
}
}
// File: contracts/lib/MathHelpers.sol
/**
* @title MathHelpers
* @author dYdX
*
* This library helps with common math functions in Solidity
*/
library MathHelpers {
using SafeMath for uint256;
/**
* Calculates partial value given a numerator and denominator.
*
* @param numerator Numerator
* @param denominator Denominator
* @param target Value to calculate partial of
* @return target * numerator / denominator
*/
function getPartialAmount(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256)
{
return numerator.mul(target).div(denominator);
}
/**
* Calculates partial value given a numerator and denominator, rounded up.
*
* @param numerator Numerator
* @param denominator Denominator
* @param target Value to calculate partial of
* @return Rounded-up result of target * numerator / denominator
*/
function getPartialAmountRoundedUp(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256)
{
return divisionRoundedUp(numerator.mul(target), denominator);
}
/**
* Calculates division given a numerator and denominator, rounded up.
*
* @param numerator Numerator.
* @param denominator Denominator.
* @return Rounded-up result of numerator / denominator
*/
function divisionRoundedUp(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
assert(denominator != 0); // coverage-enable-line
if (numerator == 0) {
return 0;
}
return numerator.sub(1).div(denominator).add(1);
}
/**
* Calculates and returns the maximum value for a uint256 in solidity
*
* @return The maximum value for uint256
*/
function maxUint256(
)
internal
pure
returns (uint256)
{
return 2 ** 256 - 1;
}
/**
* Calculates and returns the maximum value for a uint256 in solidity
*
* @return The maximum value for uint256
*/
function maxUint32(
)
internal
pure
returns (uint32)
{
return 2 ** 32 - 1;
}
/**
* Returns the number of bits in a uint256. That is, the lowest number, x, such that n >> x == 0
*
* @param n The uint256 to get the number of bits in
* @return The number of bits in n
*/
function getNumBits(
uint256 n
)
internal
pure
returns (uint256)
{
uint256 first = 0;
uint256 last = 256;
while (first < last) {
uint256 check = (first + last) / 2;
if ((n >> check) == 0) {
last = check;
} else {
first = check + 1;
}
}
assert(first <= 256);
return first;
}
}
// File: contracts/margin/impl/InterestImpl.sol
/**
* @title InterestImpl
* @author dYdX
*
* A library that calculates continuously compounded interest for principal, time period, and
* interest rate.
*/
library InterestImpl {
using SafeMath for uint256;
using FractionMath for Fraction.Fraction128;
// ============ Constants ============
uint256 constant DEFAULT_PRECOMPUTE_PRECISION = 11;
uint256 constant DEFAULT_MACLAURIN_PRECISION = 5;
uint256 constant MAXIMUM_EXPONENT = 80;
uint128 constant E_TO_MAXIUMUM_EXPONENT = 55406223843935100525711733958316613;
// ============ Public Implementation Functions ============
/**
* Returns total tokens owed after accruing interest. Continuously compounding and accurate to
* roughly 10^18 decimal places. Continuously compounding interest follows the formula:
* I = P * e^(R*T)
*
* @param principal Principal of the interest calculation
* @param interestRate Annual nominal interest percentage times 10**6.
* (example: 5% = 5e6)
* @param secondsOfInterest Number of seconds that interest has been accruing
* @return Total amount of tokens owed. Greater than tokenAmount.
*/
function getCompoundedInterest(
uint256 principal,
uint256 interestRate,
uint256 secondsOfInterest
)
public
pure
returns (uint256)
{
uint256 numerator = interestRate.mul(secondsOfInterest);
uint128 denominator = (10**8) * (365 * 1 days);
// interestRate and secondsOfInterest should both be uint32
assert(numerator < 2**128);
// fraction representing (Rate * Time)
Fraction.Fraction128 memory rt = Fraction.Fraction128({
num: uint128(numerator),
den: denominator
});
// calculate e^(RT)
Fraction.Fraction128 memory eToRT;
if (numerator.div(denominator) >= MAXIMUM_EXPONENT) {
// degenerate case: cap calculation
eToRT = Fraction.Fraction128({
num: E_TO_MAXIUMUM_EXPONENT,
den: 1
});
} else {
// normal case: calculate e^(RT)
eToRT = Exponent.exp(
rt,
DEFAULT_PRECOMPUTE_PRECISION,
DEFAULT_MACLAURIN_PRECISION
);
}
// e^X for positive X should be greater-than or equal to 1
assert(eToRT.num >= eToRT.den);
return safeMultiplyUint256ByFraction(principal, eToRT);
}
// ============ Private Helper-Functions ============
/**
* Returns n * f, trying to prevent overflow as much as possible. Assumes that the numerator
* and denominator of f are less than 2**128.
*/
function safeMultiplyUint256ByFraction(
uint256 n,
Fraction.Fraction128 memory f
)
private
pure
returns (uint256)
{
uint256 term1 = n.div(2 ** 128); // first 128 bits
uint256 term2 = n % (2 ** 128); // second 128 bits
// uncommon scenario, requires n >= 2**128. calculates term1 = term1 * f
if (term1 > 0) {
term1 = term1.mul(f.num);
uint256 numBits = MathHelpers.getNumBits(term1);
// reduce rounding error by shifting all the way to the left before dividing
term1 = MathHelpers.divisionRoundedUp(
term1 << (uint256(256).sub(numBits)),
f.den);
// continue shifting or reduce shifting to get the right number
if (numBits > 128) {
term1 = term1 << (numBits.sub(128));
} else if (numBits < 128) {
term1 = term1 >> (uint256(128).sub(numBits));
}
}
// calculates term2 = term2 * f
term2 = MathHelpers.getPartialAmountRoundedUp(
f.num,
f.den,
term2
);
return term1.add(term2);
}
}
// File: contracts/margin/impl/MarginState.sol
/**
* @title MarginState
* @author dYdX
*
* Contains state for the Margin contract. Also used by libraries that implement Margin functions.
*/
library MarginState {
struct State {
// Address of the Vault contract
address VAULT;
// Address of the TokenProxy contract
address TOKEN_PROXY;
// Mapping from loanHash -> amount, which stores the amount of a loan which has
// already been filled.
mapping (bytes32 => uint256) loanFills;
// Mapping from loanHash -> amount, which stores the amount of a loan which has
// already been canceled.
mapping (bytes32 => uint256) loanCancels;
// Mapping from positionId -> Position, which stores all the open margin positions.
mapping (bytes32 => MarginCommon.Position) positions;
// Mapping from positionId -> bool, which stores whether the position has previously been
// open, but is now closed.
mapping (bytes32 => bool) closedPositions;
// Mapping from positionId -> uint256, which stores the total amount of owedToken that has
// ever been repaid to the lender for each position. Does not reset.
mapping (bytes32 => uint256) totalOwedTokenRepaidToLender;
}
}
// File: contracts/margin/interfaces/lender/LoanOwner.sol
/**
* @title LoanOwner
* @author dYdX
*
* Interface that smart contracts must implement in order to own loans on behalf of other accounts.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface LoanOwner {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive ownership of a loan sell via the
* transferLoan function or the atomic-assign to the "owner" field in a loan offering.
*
* @param from Address of the previous owner
* @param positionId Unique ID of the position
* @return This address to keep ownership, a different address to pass-on ownership
*/
function receiveLoanOwnership(
address from,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/owner/PositionOwner.sol
/**
* @title PositionOwner
* @author dYdX
*
* Interface that smart contracts must implement in order to own position on behalf of other
* accounts
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface PositionOwner {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive ownership of a position via the
* transferPosition function or the atomic-assign to the "owner" field when opening a position.
*
* @param from Address of the previous owner
* @param positionId Unique ID of the position
* @return This address to keep ownership, a different address to pass-on ownership
*/
function receivePositionOwnership(
address from,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/TransferInternal.sol
/**
* @title TransferInternal
* @author dYdX
*
* This library contains the implementation for transferring ownership of loans and positions.
*/
library TransferInternal {
// ============ Events ============
/**
* Ownership of a loan was transferred to a new address
*/
event LoanTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
/**
* Ownership of a postion was transferred to a new address
*/
event PositionTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
// ============ Internal Implementation Functions ============
/**
* Returns either the address of the new loan owner, or the address to which they wish to
* pass ownership of the loan. This function does not actually set the state of the position
*
* @param positionId The Unique ID of the position
* @param oldOwner The previous owner of the loan
* @param newOwner The intended owner of the loan
* @return The address that the intended owner wishes to assign the loan to (may be
* the same as the intended owner).
*/
function grantLoanOwnership(
bytes32 positionId,
address oldOwner,
address newOwner
)
internal
returns (address)
{
// log event except upon position creation
if (oldOwner != address(0)) {
emit LoanTransferred(positionId, oldOwner, newOwner);
}
if (AddressUtils.isContract(newOwner)) {
address nextOwner =
LoanOwner(newOwner).receiveLoanOwnership(oldOwner, positionId);
if (nextOwner != newOwner) {
return grantLoanOwnership(positionId, newOwner, nextOwner);
}
}
require(
newOwner != address(0),
"TransferInternal#grantLoanOwnership: New owner did not consent to owning loan"
);
return newOwner;
}
/**
* Returns either the address of the new position owner, or the address to which they wish to
* pass ownership of the position. This function does not actually set the state of the position
*
* @param positionId The Unique ID of the position
* @param oldOwner The previous owner of the position
* @param newOwner The intended owner of the position
* @return The address that the intended owner wishes to assign the position to (may
* be the same as the intended owner).
*/
function grantPositionOwnership(
bytes32 positionId,
address oldOwner,
address newOwner
)
internal
returns (address)
{
// log event except upon position creation
if (oldOwner != address(0)) {
emit PositionTransferred(positionId, oldOwner, newOwner);
}
if (AddressUtils.isContract(newOwner)) {
address nextOwner =
PositionOwner(newOwner).receivePositionOwnership(oldOwner, positionId);
if (nextOwner != newOwner) {
return grantPositionOwnership(positionId, newOwner, nextOwner);
}
}
require(
newOwner != address(0),
"TransferInternal#grantPositionOwnership: New owner did not consent to owning position"
);
return newOwner;
}
}
// File: contracts/lib/TimestampHelper.sol
/**
* @title TimestampHelper
* @author dYdX
*
* Helper to get block timestamps in other formats
*/
library TimestampHelper {
function getBlockTimestamp32()
internal
view
returns (uint32)
{
// Should not still be in-use in the year 2106
assert(uint256(uint32(block.timestamp)) == block.timestamp);
assert(block.timestamp > 0);
return uint32(block.timestamp);
}
}
// File: contracts/margin/impl/MarginCommon.sol
/**
* @title MarginCommon
* @author dYdX
*
* This library contains common functions for implementations of public facing Margin functions
*/
library MarginCommon {
using SafeMath for uint256;
// ============ Structs ============
struct Position {
address owedToken; // Immutable
address heldToken; // Immutable
address lender;
address owner;
uint256 principal;
uint256 requiredDeposit;
uint32 callTimeLimit; // Immutable
uint32 startTimestamp; // Immutable, cannot be 0
uint32 callTimestamp;
uint32 maxDuration; // Immutable
uint32 interestRate; // Immutable
uint32 interestPeriod; // Immutable
}
struct LoanOffering {
address owedToken;
address heldToken;
address payer;
address owner;
address taker;
address positionOwner;
address feeRecipient;
address lenderFeeToken;
address takerFeeToken;
LoanRates rates;
uint256 expirationTimestamp;
uint32 callTimeLimit;
uint32 maxDuration;
uint256 salt;
bytes32 loanHash;
bytes signature;
}
struct LoanRates {
uint256 maxAmount;
uint256 minAmount;
uint256 minHeldToken;
uint256 lenderFee;
uint256 takerFee;
uint32 interestRate;
uint32 interestPeriod;
}
// ============ Internal Implementation Functions ============
function storeNewPosition(
MarginState.State storage state,
bytes32 positionId,
Position memory position,
address loanPayer
)
internal
{
assert(!positionHasExisted(state, positionId));
assert(position.owedToken != address(0));
assert(position.heldToken != address(0));
assert(position.owedToken != position.heldToken);
assert(position.owner != address(0));
assert(position.lender != address(0));
assert(position.maxDuration != 0);
assert(position.interestPeriod <= position.maxDuration);
assert(position.callTimestamp == 0);
assert(position.requiredDeposit == 0);
state.positions[positionId].owedToken = position.owedToken;
state.positions[positionId].heldToken = position.heldToken;
state.positions[positionId].principal = position.principal;
state.positions[positionId].callTimeLimit = position.callTimeLimit;
state.positions[positionId].startTimestamp = TimestampHelper.getBlockTimestamp32();
state.positions[positionId].maxDuration = position.maxDuration;
state.positions[positionId].interestRate = position.interestRate;
state.positions[positionId].interestPeriod = position.interestPeriod;
state.positions[positionId].owner = TransferInternal.grantPositionOwnership(
positionId,
(position.owner != msg.sender) ? msg.sender : address(0),
position.owner
);
state.positions[positionId].lender = TransferInternal.grantLoanOwnership(
positionId,
(position.lender != loanPayer) ? loanPayer : address(0),
position.lender
);
}
function getPositionIdFromNonce(
uint256 nonce
)
internal
view
returns (bytes32)
{
return keccak256(abi.encodePacked(msg.sender, nonce));
}
function getUnavailableLoanOfferingAmountImpl(
MarginState.State storage state,
bytes32 loanHash
)
internal
view
returns (uint256)
{
return state.loanFills[loanHash].add(state.loanCancels[loanHash]);
}
function cleanupPosition(
MarginState.State storage state,
bytes32 positionId
)
internal
{
delete state.positions[positionId];
state.closedPositions[positionId] = true;
}
function calculateOwedAmount(
Position storage position,
uint256 closeAmount,
uint256 endTimestamp
)
internal
view
returns (uint256)
{
uint256 timeElapsed = calculateEffectiveTimeElapsed(position, endTimestamp);
return InterestImpl.getCompoundedInterest(
closeAmount,
position.interestRate,
timeElapsed
);
}
/**
* Calculates time elapsed rounded up to the nearest interestPeriod
*/
function calculateEffectiveTimeElapsed(
Position storage position,
uint256 timestamp
)
internal
view
returns (uint256)
{
uint256 elapsed = timestamp.sub(position.startTimestamp);
// round up to interestPeriod
uint256 period = position.interestPeriod;
if (period > 1) {
elapsed = MathHelpers.divisionRoundedUp(elapsed, period).mul(period);
}
// bound by maxDuration
return Math.min256(
elapsed,
position.maxDuration
);
}
function calculateLenderAmountForIncreasePosition(
Position storage position,
uint256 principalToAdd,
uint256 endTimestamp
)
internal
view
returns (uint256)
{
uint256 timeElapsed = calculateEffectiveTimeElapsedForNewLender(position, endTimestamp);
return InterestImpl.getCompoundedInterest(
principalToAdd,
position.interestRate,
timeElapsed
);
}
function getLoanOfferingHash(
LoanOffering loanOffering
)
internal
view
returns (bytes32)
{
return keccak256(
abi.encodePacked(
address(this),
loanOffering.owedToken,
loanOffering.heldToken,
loanOffering.payer,
loanOffering.owner,
loanOffering.taker,
loanOffering.positionOwner,
loanOffering.feeRecipient,
loanOffering.lenderFeeToken,
loanOffering.takerFeeToken,
getValuesHash(loanOffering)
)
);
}
function getPositionBalanceImpl(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns(uint256)
{
return Vault(state.VAULT).balances(positionId, state.positions[positionId].heldToken);
}
function containsPositionImpl(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (bool)
{
return state.positions[positionId].startTimestamp != 0;
}
function positionHasExisted(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (bool)
{
return containsPositionImpl(state, positionId) || state.closedPositions[positionId];
}
function getPositionFromStorage(
MarginState.State storage state,
bytes32 positionId
)
internal
view
returns (Position storage)
{
Position storage position = state.positions[positionId];
require(
position.startTimestamp != 0,
"MarginCommon#getPositionFromStorage: The position does not exist"
);
return position;
}
// ============ Private Helper-Functions ============
/**
* Calculates time elapsed rounded down to the nearest interestPeriod
*/
function calculateEffectiveTimeElapsedForNewLender(
Position storage position,
uint256 timestamp
)
private
view
returns (uint256)
{
uint256 elapsed = timestamp.sub(position.startTimestamp);
// round down to interestPeriod
uint256 period = position.interestPeriod;
if (period > 1) {
elapsed = elapsed.div(period).mul(period);
}
// bound by maxDuration
return Math.min256(
elapsed,
position.maxDuration
);
}
function getValuesHash(
LoanOffering loanOffering
)
private
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
loanOffering.rates.maxAmount,
loanOffering.rates.minAmount,
loanOffering.rates.minHeldToken,
loanOffering.rates.lenderFee,
loanOffering.rates.takerFee,
loanOffering.expirationTimestamp,
loanOffering.salt,
loanOffering.callTimeLimit,
loanOffering.maxDuration,
loanOffering.rates.interestRate,
loanOffering.rates.interestPeriod
)
);
}
}
// File: contracts/margin/interfaces/PayoutRecipient.sol
/**
* @title PayoutRecipient
* @author dYdX
*
* Interface that smart contracts must implement in order to be the payoutRecipient in a
* closePosition transaction.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface PayoutRecipient {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to receive payout from being the payoutRecipient
* in a closePosition transaction. May redistribute any payout as necessary. Throws on error.
*
* @param positionId Unique ID of the position
* @param closeAmount Amount of the position that was closed
* @param closer Address of the account or contract that closed the position
* @param positionOwner Address of the owner of the position
* @param heldToken Address of the ERC20 heldToken
* @param payout Number of tokens received from the payout
* @param totalHeldToken Total amount of heldToken removed from vault during close
* @param payoutInHeldToken True if payout is in heldToken, false if in owedToken
* @return True if approved by the receiver
*/
function receiveClosePositionPayout(
bytes32 positionId,
uint256 closeAmount,
address closer,
address positionOwner,
address heldToken,
uint256 payout,
uint256 totalHeldToken,
bool payoutInHeldToken
)
external
/* onlyMargin */
returns (bool);
}
// File: contracts/margin/interfaces/lender/CloseLoanDelegator.sol
/**
* @title CloseLoanDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses close a loan
* owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface CloseLoanDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call
* closeWithoutCounterparty().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that (at most) the specified amount of the loan was
* successfully closed.
*
* @param closer Address of the caller of closeWithoutCounterparty()
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param positionId Unique ID of the position
* @param requestedAmount Requested principal amount of the loan to close
* @return 1) This address to accept, a different address to ask that contract
* 2) The maximum amount that this contract is allowing
*/
function closeLoanOnBehalfOf(
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 requestedAmount
)
external
/* onlyMargin */
returns (address, uint256);
}
// File: contracts/margin/interfaces/owner/ClosePositionDelegator.sol
/**
* @title ClosePositionDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses close a position
* owned by the smart contract, allowing more complex logic to control positions.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface ClosePositionDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call closePosition().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that (at-most) the specified amount of the position
* was successfully closed.
*
* @param closer Address of the caller of the closePosition() function
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param positionId Unique ID of the position
* @param requestedAmount Requested principal amount of the position to close
* @return 1) This address to accept, a different address to ask that contract
* 2) The maximum amount that this contract is allowing
*/
function closeOnBehalfOf(
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 requestedAmount
)
external
/* onlyMargin */
returns (address, uint256);
}
// File: contracts/margin/impl/ClosePositionShared.sol
/**
* @title ClosePositionShared
* @author dYdX
*
* This library contains shared functionality between ClosePositionImpl and
* CloseWithoutCounterpartyImpl
*/
library ClosePositionShared {
using SafeMath for uint256;
// ============ Structs ============
struct CloseTx {
bytes32 positionId;
uint256 originalPrincipal;
uint256 closeAmount;
uint256 owedTokenOwed;
uint256 startingHeldTokenBalance;
uint256 availableHeldToken;
address payoutRecipient;
address owedToken;
address heldToken;
address positionOwner;
address positionLender;
address exchangeWrapper;
bool payoutInHeldToken;
}
// ============ Internal Implementation Functions ============
function closePositionStateUpdate(
MarginState.State storage state,
CloseTx memory transaction
)
internal
{
// Delete the position, or just decrease the principal
if (transaction.closeAmount == transaction.originalPrincipal) {
MarginCommon.cleanupPosition(state, transaction.positionId);
} else {
assert(
transaction.originalPrincipal == state.positions[transaction.positionId].principal
);
state.positions[transaction.positionId].principal =
transaction.originalPrincipal.sub(transaction.closeAmount);
}
}
function sendTokensToPayoutRecipient(
MarginState.State storage state,
ClosePositionShared.CloseTx memory transaction,
uint256 buybackCostInHeldToken,
uint256 receivedOwedToken
)
internal
returns (uint256)
{
uint256 payout;
if (transaction.payoutInHeldToken) {
// Send remaining heldToken to payoutRecipient
payout = transaction.availableHeldToken.sub(buybackCostInHeldToken);
Vault(state.VAULT).transferFromVault(
transaction.positionId,
transaction.heldToken,
transaction.payoutRecipient,
payout
);
} else {
assert(transaction.exchangeWrapper != address(0));
payout = receivedOwedToken.sub(transaction.owedTokenOwed);
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
transaction.exchangeWrapper,
transaction.payoutRecipient,
payout
);
}
if (AddressUtils.isContract(transaction.payoutRecipient)) {
require(
PayoutRecipient(transaction.payoutRecipient).receiveClosePositionPayout(
transaction.positionId,
transaction.closeAmount,
msg.sender,
transaction.positionOwner,
transaction.heldToken,
payout,
transaction.availableHeldToken,
transaction.payoutInHeldToken
),
"ClosePositionShared#sendTokensToPayoutRecipient: Payout recipient does not consent"
);
}
// The ending heldToken balance of the vault should be the starting heldToken balance
// minus the available heldToken amount
assert(
MarginCommon.getPositionBalanceImpl(state, transaction.positionId)
== transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken)
);
return payout;
}
function createCloseTx(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bool isWithoutCounterparty
)
internal
returns (CloseTx memory)
{
// Validate
require(
payoutRecipient != address(0),
"ClosePositionShared#createCloseTx: Payout recipient cannot be 0"
);
require(
requestedAmount > 0,
"ClosePositionShared#createCloseTx: Requested close amount cannot be 0"
);
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
uint256 closeAmount = getApprovedAmount(
position,
positionId,
requestedAmount,
payoutRecipient,
isWithoutCounterparty
);
return parseCloseTx(
state,
position,
positionId,
closeAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
isWithoutCounterparty
);
}
// ============ Private Helper-Functions ============
function getApprovedAmount(
MarginCommon.Position storage position,
bytes32 positionId,
uint256 requestedAmount,
address payoutRecipient,
bool requireLenderApproval
)
private
returns (uint256)
{
// Ensure enough principal
uint256 allowedAmount = Math.min256(requestedAmount, position.principal);
// Ensure owner consent
allowedAmount = closePositionOnBehalfOfRecurse(
position.owner,
msg.sender,
payoutRecipient,
positionId,
allowedAmount
);
// Ensure lender consent
if (requireLenderApproval) {
allowedAmount = closeLoanOnBehalfOfRecurse(
position.lender,
msg.sender,
payoutRecipient,
positionId,
allowedAmount
);
}
assert(allowedAmount > 0);
assert(allowedAmount <= position.principal);
assert(allowedAmount <= requestedAmount);
return allowedAmount;
}
function closePositionOnBehalfOfRecurse(
address contractAddr,
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 closeAmount
)
private
returns (uint256)
{
// no need to ask for permission
if (closer == contractAddr) {
return closeAmount;
}
(
address newContractAddr,
uint256 newCloseAmount
) = ClosePositionDelegator(contractAddr).closeOnBehalfOf(
closer,
payoutRecipient,
positionId,
closeAmount
);
require(
newCloseAmount <= closeAmount,
"ClosePositionShared#closePositionRecurse: newCloseAmount is greater than closeAmount"
);
require(
newCloseAmount > 0,
"ClosePositionShared#closePositionRecurse: newCloseAmount is zero"
);
if (newContractAddr != contractAddr) {
closePositionOnBehalfOfRecurse(
newContractAddr,
closer,
payoutRecipient,
positionId,
newCloseAmount
);
}
return newCloseAmount;
}
function closeLoanOnBehalfOfRecurse(
address contractAddr,
address closer,
address payoutRecipient,
bytes32 positionId,
uint256 closeAmount
)
private
returns (uint256)
{
// no need to ask for permission
if (closer == contractAddr) {
return closeAmount;
}
(
address newContractAddr,
uint256 newCloseAmount
) = CloseLoanDelegator(contractAddr).closeLoanOnBehalfOf(
closer,
payoutRecipient,
positionId,
closeAmount
);
require(
newCloseAmount <= closeAmount,
"ClosePositionShared#closeLoanRecurse: newCloseAmount is greater than closeAmount"
);
require(
newCloseAmount > 0,
"ClosePositionShared#closeLoanRecurse: newCloseAmount is zero"
);
if (newContractAddr != contractAddr) {
closeLoanOnBehalfOfRecurse(
newContractAddr,
closer,
payoutRecipient,
positionId,
newCloseAmount
);
}
return newCloseAmount;
}
// ============ Parsing Functions ============
function parseCloseTx(
MarginState.State storage state,
MarginCommon.Position storage position,
bytes32 positionId,
uint256 closeAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bool isWithoutCounterparty
)
private
view
returns (CloseTx memory)
{
uint256 startingHeldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId);
uint256 availableHeldToken = MathHelpers.getPartialAmount(
closeAmount,
position.principal,
startingHeldTokenBalance
);
uint256 owedTokenOwed = 0;
if (!isWithoutCounterparty) {
owedTokenOwed = MarginCommon.calculateOwedAmount(
position,
closeAmount,
block.timestamp
);
}
return CloseTx({
positionId: positionId,
originalPrincipal: position.principal,
closeAmount: closeAmount,
owedTokenOwed: owedTokenOwed,
startingHeldTokenBalance: startingHeldTokenBalance,
availableHeldToken: availableHeldToken,
payoutRecipient: payoutRecipient,
owedToken: position.owedToken,
heldToken: position.heldToken,
positionOwner: position.owner,
positionLender: position.lender,
exchangeWrapper: exchangeWrapper,
payoutInHeldToken: payoutInHeldToken
});
}
}
// File: contracts/margin/interfaces/ExchangeWrapper.sol
/**
* @title ExchangeWrapper
* @author dYdX
*
* Contract interface that Exchange Wrapper smart contracts must implement in order to interface
* with other smart contracts through a common interface.
*/
interface ExchangeWrapper {
// ============ Public Functions ============
/**
* Exchange some amount of takerToken for makerToken.
*
* @param tradeOriginator Address of the initiator of the trade (however, this value
* cannot always be trusted as it is set at the discretion of the
* msg.sender)
* @param receiver Address to set allowance on once the trade has completed
* @param makerToken Address of makerToken, the token to receive
* @param takerToken Address of takerToken, the token to pay
* @param requestedFillAmount Amount of takerToken being paid
* @param orderData Arbitrary bytes data for any information to pass to the exchange
* @return The amount of makerToken received
*/
function exchange(
address tradeOriginator,
address receiver,
address makerToken,
address takerToken,
uint256 requestedFillAmount,
bytes orderData
)
external
returns (uint256);
/**
* Get amount of takerToken required to buy a certain amount of makerToken for a given trade.
* Should match the takerToken amount used in exchangeForAmount. If the order cannot provide
* exactly desiredMakerToken, then it must return the price to buy the minimum amount greater
* than desiredMakerToken
*
* @param makerToken Address of makerToken, the token to receive
* @param takerToken Address of takerToken, the token to pay
* @param desiredMakerToken Amount of makerToken requested
* @param orderData Arbitrary bytes data for any information to pass to the exchange
* @return Amount of takerToken the needed to complete the transaction
*/
function getExchangeCost(
address makerToken,
address takerToken,
uint256 desiredMakerToken,
bytes orderData
)
external
view
returns (uint256);
}
// File: contracts/margin/impl/ClosePositionImpl.sol
/**
* @title ClosePositionImpl
* @author dYdX
*
* This library contains the implementation for the closePosition function of Margin
*/
library ClosePositionImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
// ============ Public Implementation Functions ============
function closePositionImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bytes memory orderData
)
public
returns (uint256, uint256, uint256)
{
ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
false
);
(
uint256 buybackCostInHeldToken,
uint256 receivedOwedToken
) = returnOwedTokensToLender(
state,
transaction,
orderData
);
uint256 payout = ClosePositionShared.sendTokensToPayoutRecipient(
state,
transaction,
buybackCostInHeldToken,
receivedOwedToken
);
ClosePositionShared.closePositionStateUpdate(state, transaction);
logEventOnClose(
transaction,
buybackCostInHeldToken,
payout
);
return (
transaction.closeAmount,
payout,
transaction.owedTokenOwed
);
}
// ============ Private Helper-Functions ============
function returnOwedTokensToLender(
MarginState.State storage state,
ClosePositionShared.CloseTx memory transaction,
bytes memory orderData
)
private
returns (uint256, uint256)
{
uint256 buybackCostInHeldToken = 0;
uint256 receivedOwedToken = 0;
uint256 lenderOwedToken = transaction.owedTokenOwed;
// Setting exchangeWrapper to 0x000... indicates owedToken should be taken directly
// from msg.sender
if (transaction.exchangeWrapper == address(0)) {
require(
transaction.payoutInHeldToken,
"ClosePositionImpl#returnOwedTokensToLender: Cannot payout in owedToken"
);
// No DEX Order; send owedTokens directly from the closer to the lender
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
msg.sender,
transaction.positionLender,
lenderOwedToken
);
} else {
// Buy back owedTokens using DEX Order and send to lender
(buybackCostInHeldToken, receivedOwedToken) = buyBackOwedToken(
state,
transaction,
orderData
);
// If no owedToken needed for payout: give lender all owedToken, even if more than owed
if (transaction.payoutInHeldToken) {
assert(receivedOwedToken >= lenderOwedToken);
lenderOwedToken = receivedOwedToken;
}
// Transfer owedToken from the exchange wrapper to the lender
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.owedToken,
transaction.exchangeWrapper,
transaction.positionLender,
lenderOwedToken
);
}
state.totalOwedTokenRepaidToLender[transaction.positionId] =
state.totalOwedTokenRepaidToLender[transaction.positionId].add(lenderOwedToken);
return (buybackCostInHeldToken, receivedOwedToken);
}
function buyBackOwedToken(
MarginState.State storage state,
ClosePositionShared.CloseTx transaction,
bytes memory orderData
)
private
returns (uint256, uint256)
{
// Ask the exchange wrapper the cost in heldToken to buy back the close
// amount of owedToken
uint256 buybackCostInHeldToken;
if (transaction.payoutInHeldToken) {
buybackCostInHeldToken = ExchangeWrapper(transaction.exchangeWrapper)
.getExchangeCost(
transaction.owedToken,
transaction.heldToken,
transaction.owedTokenOwed,
orderData
);
// Require enough available heldToken to pay for the buyback
require(
buybackCostInHeldToken <= transaction.availableHeldToken,
"ClosePositionImpl#buyBackOwedToken: Not enough available heldToken"
);
} else {
buybackCostInHeldToken = transaction.availableHeldToken;
}
// Send the requisite heldToken to do the buyback from vault to exchange wrapper
Vault(state.VAULT).transferFromVault(
transaction.positionId,
transaction.heldToken,
transaction.exchangeWrapper,
buybackCostInHeldToken
);
// Trade the heldToken for the owedToken
uint256 receivedOwedToken = ExchangeWrapper(transaction.exchangeWrapper).exchange(
msg.sender,
state.TOKEN_PROXY,
transaction.owedToken,
transaction.heldToken,
buybackCostInHeldToken,
orderData
);
require(
receivedOwedToken >= transaction.owedTokenOwed,
"ClosePositionImpl#buyBackOwedToken: Did not receive enough owedToken"
);
return (buybackCostInHeldToken, receivedOwedToken);
}
function logEventOnClose(
ClosePositionShared.CloseTx transaction,
uint256 buybackCostInHeldToken,
uint256 payout
)
private
{
emit PositionClosed(
transaction.positionId,
msg.sender,
transaction.payoutRecipient,
transaction.closeAmount,
transaction.originalPrincipal.sub(transaction.closeAmount),
transaction.owedTokenOwed,
payout,
buybackCostInHeldToken,
transaction.payoutInHeldToken
);
}
}
// File: contracts/margin/impl/CloseWithoutCounterpartyImpl.sol
/**
* @title CloseWithoutCounterpartyImpl
* @author dYdX
*
* This library contains the implementation for the closeWithoutCounterpartyImpl function of
* Margin
*/
library CloseWithoutCounterpartyImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
// ============ Public Implementation Functions ============
function closeWithoutCounterpartyImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
public
returns (uint256, uint256)
{
ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
address(0),
true,
true
);
uint256 heldTokenPayout = ClosePositionShared.sendTokensToPayoutRecipient(
state,
transaction,
0, // No buyback cost
0 // Did not receive any owedToken
);
ClosePositionShared.closePositionStateUpdate(state, transaction);
logEventOnCloseWithoutCounterparty(transaction);
return (
transaction.closeAmount,
heldTokenPayout
);
}
// ============ Private Helper-Functions ============
function logEventOnCloseWithoutCounterparty(
ClosePositionShared.CloseTx transaction
)
private
{
emit PositionClosed(
transaction.positionId,
msg.sender,
transaction.payoutRecipient,
transaction.closeAmount,
transaction.originalPrincipal.sub(transaction.closeAmount),
0,
transaction.availableHeldToken,
0,
true
);
}
}
// File: contracts/margin/interfaces/owner/DepositCollateralDelegator.sol
/**
* @title DepositCollateralDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses deposit heldTokens
* into a position owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface DepositCollateralDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call depositCollateral().
*
* @param depositor Address of the caller of the depositCollateral() function
* @param positionId Unique ID of the position
* @param amount Requested deposit amount
* @return This address to accept, a different address to ask that contract
*/
function depositCollateralOnBehalfOf(
address depositor,
bytes32 positionId,
uint256 amount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/DepositCollateralImpl.sol
/**
* @title DepositCollateralImpl
* @author dYdX
*
* This library contains the implementation for the deposit function of Margin
*/
library DepositCollateralImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* Additional collateral for a position was posted by the owner
*/
event AdditionalCollateralDeposited(
bytes32 indexed positionId,
uint256 amount,
address depositor
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
// ============ Public Implementation Functions ============
function depositCollateralImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 depositAmount
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
depositAmount > 0,
"DepositCollateralImpl#depositCollateralImpl: Deposit amount cannot be 0"
);
// Ensure owner consent
depositCollateralOnBehalfOfRecurse(
position.owner,
msg.sender,
positionId,
depositAmount
);
Vault(state.VAULT).transferToVault(
positionId,
position.heldToken,
msg.sender,
depositAmount
);
// cancel margin call if applicable
bool marginCallCanceled = false;
uint256 requiredDeposit = position.requiredDeposit;
if (position.callTimestamp > 0 && requiredDeposit > 0) {
if (depositAmount >= requiredDeposit) {
position.requiredDeposit = 0;
position.callTimestamp = 0;
marginCallCanceled = true;
} else {
position.requiredDeposit = position.requiredDeposit.sub(depositAmount);
}
}
emit AdditionalCollateralDeposited(
positionId,
depositAmount,
msg.sender
);
if (marginCallCanceled) {
emit MarginCallCanceled(
positionId,
position.lender,
msg.sender,
depositAmount
);
}
}
// ============ Private Helper-Functions ============
function depositCollateralOnBehalfOfRecurse(
address contractAddr,
address depositor,
bytes32 positionId,
uint256 amount
)
private
{
// no need to ask for permission
if (depositor == contractAddr) {
return;
}
address newContractAddr =
DepositCollateralDelegator(contractAddr).depositCollateralOnBehalfOf(
depositor,
positionId,
amount
);
// if not equal, recurse
if (newContractAddr != contractAddr) {
depositCollateralOnBehalfOfRecurse(
newContractAddr,
depositor,
positionId,
amount
);
}
}
}
// File: contracts/margin/interfaces/lender/ForceRecoverCollateralDelegator.sol
/**
* @title ForceRecoverCollateralDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses
* forceRecoverCollateral() a loan owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface ForceRecoverCollateralDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call
* forceRecoverCollateral().
*
* NOTE: If not returning zero address (or not reverting), this contract must assume that Margin
* will either revert the entire transaction or that the collateral was forcibly recovered.
*
* @param recoverer Address of the caller of the forceRecoverCollateral() function
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return This address to accept, a different address to ask that contract
*/
function forceRecoverCollateralOnBehalfOf(
address recoverer,
bytes32 positionId,
address recipient
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/ForceRecoverCollateralImpl.sol
/**
* @title ForceRecoverCollateralImpl
* @author dYdX
*
* This library contains the implementation for the forceRecoverCollateral function of Margin
*/
library ForceRecoverCollateralImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* Collateral for a position was forcibly recovered
*/
event CollateralForceRecovered(
bytes32 indexed positionId,
address indexed recipient,
uint256 amount
);
// ============ Public Implementation Functions ============
function forceRecoverCollateralImpl(
MarginState.State storage state,
bytes32 positionId,
address recipient
)
public
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
// Can only force recover after either:
// 1) The loan was called and the call period has elapsed
// 2) The maxDuration of the position has elapsed
require( /* solium-disable-next-line */
(
position.callTimestamp > 0
&& block.timestamp >= uint256(position.callTimestamp).add(position.callTimeLimit)
) || (
block.timestamp >= uint256(position.startTimestamp).add(position.maxDuration)
),
"ForceRecoverCollateralImpl#forceRecoverCollateralImpl: Cannot recover yet"
);
// Ensure lender consent
forceRecoverCollateralOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId,
recipient
);
// Send the tokens
uint256 heldTokenRecovered = MarginCommon.getPositionBalanceImpl(state, positionId);
Vault(state.VAULT).transferFromVault(
positionId,
position.heldToken,
recipient,
heldTokenRecovered
);
// Delete the position
// NOTE: Since position is a storage pointer, this will also set all fields on
// the position variable to 0
MarginCommon.cleanupPosition(
state,
positionId
);
// Log an event
emit CollateralForceRecovered(
positionId,
recipient,
heldTokenRecovered
);
return heldTokenRecovered;
}
// ============ Private Helper-Functions ============
function forceRecoverCollateralOnBehalfOfRecurse(
address contractAddr,
address recoverer,
bytes32 positionId,
address recipient
)
private
{
// no need to ask for permission
if (recoverer == contractAddr) {
return;
}
address newContractAddr =
ForceRecoverCollateralDelegator(contractAddr).forceRecoverCollateralOnBehalfOf(
recoverer,
positionId,
recipient
);
if (newContractAddr != contractAddr) {
forceRecoverCollateralOnBehalfOfRecurse(
newContractAddr,
recoverer,
positionId,
recipient
);
}
}
}
// File: contracts/lib/TypedSignature.sol
/**
* @title TypedSignature
* @author dYdX
*
* Allows for ecrecovery of signed hashes with three different prepended messages:
* 1) ""
* 2) "\x19Ethereum Signed Message:\n32"
* 3) "\x19Ethereum Signed Message:\n\x20"
*/
library TypedSignature {
// Solidity does not offer guarantees about enum values, so we define them explicitly
uint8 private constant SIGTYPE_INVALID = 0;
uint8 private constant SIGTYPE_ECRECOVER_DEC = 1;
uint8 private constant SIGTYPE_ECRECOVER_HEX = 2;
uint8 private constant SIGTYPE_UNSUPPORTED = 3;
// prepended message with the length of the signed hash in hexadecimal
bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20";
// prepended message with the length of the signed hash in decimal
bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32";
/**
* Gives the address of the signer of a hash. Allows for three common prepended strings.
*
* @param hash Hash that was signed (does not include prepended message)
* @param signatureWithType Type and ECDSA signature with structure: {1:type}{1:v}{32:r}{32:s}
* @return address of the signer of the hash
*/
function recover(
bytes32 hash,
bytes signatureWithType
)
internal
pure
returns (address)
{
require(
signatureWithType.length == 66,
"SignatureValidator#validateSignature: invalid signature length"
);
uint8 sigType = uint8(signatureWithType[0]);
require(
sigType > uint8(SIGTYPE_INVALID),
"SignatureValidator#validateSignature: invalid signature type"
);
require(
sigType < uint8(SIGTYPE_UNSUPPORTED),
"SignatureValidator#validateSignature: unsupported signature type"
);
uint8 v = uint8(signatureWithType[1]);
bytes32 r;
bytes32 s;
/* solium-disable-next-line security/no-inline-assembly */
assembly {
r := mload(add(signatureWithType, 34))
s := mload(add(signatureWithType, 66))
}
bytes32 signedHash;
if (sigType == SIGTYPE_ECRECOVER_DEC) {
signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash));
} else {
assert(sigType == SIGTYPE_ECRECOVER_HEX);
signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash));
}
return ecrecover(
signedHash,
v,
r,
s
);
}
}
// File: contracts/margin/interfaces/LoanOfferingVerifier.sol
/**
* @title LoanOfferingVerifier
* @author dYdX
*
* Interface that smart contracts must implement to be able to make off-chain generated
* loan offerings.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface LoanOfferingVerifier {
/**
* Function a smart contract must implement to be able to consent to a loan. The loan offering
* will be generated off-chain. The "loan owner" address will own the loan-side of the resulting
* position.
*
* If true is returned, and no errors are thrown by the Margin contract, the loan will have
* occurred. This means that verifyLoanOffering can also be used to update internal contract
* state on a loan.
*
* @param addresses Array of addresses:
*
* [0] = owedToken
* [1] = heldToken
* [2] = loan payer
* [3] = loan owner
* [4] = loan taker
* [5] = loan positionOwner
* [6] = loan fee recipient
* [7] = loan lender fee token
* [8] = loan taker fee token
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param positionId Unique ID of the position
* @param signature Arbitrary bytes; may or may not be an ECDSA signature
* @return This address to accept, a different address to ask that contract
*/
function verifyLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/BorrowShared.sol
/**
* @title BorrowShared
* @author dYdX
*
* This library contains shared functionality between OpenPositionImpl and IncreasePositionImpl.
* Both use a Loan Offering and a DEX Order to open or increase a position.
*/
library BorrowShared {
using SafeMath for uint256;
// ============ Structs ============
struct Tx {
bytes32 positionId;
address owner;
uint256 principal;
uint256 lenderAmount;
MarginCommon.LoanOffering loanOffering;
address exchangeWrapper;
bool depositInHeldToken;
uint256 depositAmount;
uint256 collateralAmount;
uint256 heldTokenFromSell;
}
// ============ Internal Implementation Functions ============
/**
* Validate the transaction before exchanging heldToken for owedToken
*/
function validateTxPreSell(
MarginState.State storage state,
Tx memory transaction
)
internal
{
assert(transaction.lenderAmount >= transaction.principal);
require(
transaction.principal > 0,
"BorrowShared#validateTxPreSell: Positions with 0 principal are not allowed"
);
// If the taker is 0x0 then any address can take it. Otherwise only the taker can use it.
if (transaction.loanOffering.taker != address(0)) {
require(
msg.sender == transaction.loanOffering.taker,
"BorrowShared#validateTxPreSell: Invalid loan offering taker"
);
}
// If the positionOwner is 0x0 then any address can be set as the position owner.
// Otherwise only the specified positionOwner can be set as the position owner.
if (transaction.loanOffering.positionOwner != address(0)) {
require(
transaction.owner == transaction.loanOffering.positionOwner,
"BorrowShared#validateTxPreSell: Invalid position owner"
);
}
// Require the loan offering to be approved by the payer
if (AddressUtils.isContract(transaction.loanOffering.payer)) {
getConsentFromSmartContractLender(transaction);
} else {
require(
transaction.loanOffering.payer == TypedSignature.recover(
transaction.loanOffering.loanHash,
transaction.loanOffering.signature
),
"BorrowShared#validateTxPreSell: Invalid loan offering signature"
);
}
// Validate the amount is <= than max and >= min
uint256 unavailable = MarginCommon.getUnavailableLoanOfferingAmountImpl(
state,
transaction.loanOffering.loanHash
);
require(
transaction.lenderAmount.add(unavailable) <= transaction.loanOffering.rates.maxAmount,
"BorrowShared#validateTxPreSell: Loan offering does not have enough available"
);
require(
transaction.lenderAmount >= transaction.loanOffering.rates.minAmount,
"BorrowShared#validateTxPreSell: Lender amount is below loan offering minimum amount"
);
require(
transaction.loanOffering.owedToken != transaction.loanOffering.heldToken,
"BorrowShared#validateTxPreSell: owedToken cannot be equal to heldToken"
);
require(
transaction.owner != address(0),
"BorrowShared#validateTxPreSell: Position owner cannot be 0"
);
require(
transaction.loanOffering.owner != address(0),
"BorrowShared#validateTxPreSell: Loan owner cannot be 0"
);
require(
transaction.loanOffering.expirationTimestamp > block.timestamp,
"BorrowShared#validateTxPreSell: Loan offering is expired"
);
require(
transaction.loanOffering.maxDuration > 0,
"BorrowShared#validateTxPreSell: Loan offering has 0 maximum duration"
);
require(
transaction.loanOffering.rates.interestPeriod <= transaction.loanOffering.maxDuration,
"BorrowShared#validateTxPreSell: Loan offering interestPeriod > maxDuration"
);
// The minimum heldToken is validated after executing the sell
// Position and loan ownership is validated in TransferInternal
}
/**
* Validate the transaction after exchanging heldToken for owedToken, pay out fees, and store
* how much of the loan was used.
*/
function doPostSell(
MarginState.State storage state,
Tx memory transaction
)
internal
{
validateTxPostSell(transaction);
// Transfer feeTokens from trader and lender
transferLoanFees(state, transaction);
// Update global amounts for the loan
state.loanFills[transaction.loanOffering.loanHash] =
state.loanFills[transaction.loanOffering.loanHash].add(transaction.lenderAmount);
}
/**
* Sells the owedToken from the lender (and from the deposit if in owedToken) using the
* exchangeWrapper, then puts the resulting heldToken into the vault. Only trades for
* maxHeldTokenToBuy of heldTokens at most.
*/
function doSell(
MarginState.State storage state,
Tx transaction,
bytes orderData,
uint256 maxHeldTokenToBuy
)
internal
returns (uint256)
{
// Move owedTokens from lender to exchange wrapper
pullOwedTokensFromLender(state, transaction);
// Sell just the lender's owedToken (if trader deposit is in heldToken)
// Otherwise sell both the lender's owedToken and the trader's deposit in owedToken
uint256 sellAmount = transaction.depositInHeldToken ?
transaction.lenderAmount :
transaction.lenderAmount.add(transaction.depositAmount);
// Do the trade, taking only the maxHeldTokenToBuy if more is returned
uint256 heldTokenFromSell = Math.min256(
maxHeldTokenToBuy,
ExchangeWrapper(transaction.exchangeWrapper).exchange(
msg.sender,
state.TOKEN_PROXY,
transaction.loanOffering.heldToken,
transaction.loanOffering.owedToken,
sellAmount,
orderData
)
);
// Move the tokens to the vault
Vault(state.VAULT).transferToVault(
transaction.positionId,
transaction.loanOffering.heldToken,
transaction.exchangeWrapper,
heldTokenFromSell
);
// Update collateral amount
transaction.collateralAmount = transaction.collateralAmount.add(heldTokenFromSell);
return heldTokenFromSell;
}
/**
* Take the owedToken deposit from the trader and give it to the exchange wrapper so that it can
* be sold for heldToken.
*/
function doDepositOwedToken(
MarginState.State storage state,
Tx transaction
)
internal
{
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.loanOffering.owedToken,
msg.sender,
transaction.exchangeWrapper,
transaction.depositAmount
);
}
/**
* Take the heldToken deposit from the trader and move it to the vault.
*/
function doDepositHeldToken(
MarginState.State storage state,
Tx transaction
)
internal
{
Vault(state.VAULT).transferToVault(
transaction.positionId,
transaction.loanOffering.heldToken,
msg.sender,
transaction.depositAmount
);
// Update collateral amount
transaction.collateralAmount = transaction.collateralAmount.add(transaction.depositAmount);
}
// ============ Private Helper-Functions ============
function validateTxPostSell(
Tx transaction
)
private
pure
{
uint256 expectedCollateral = transaction.depositInHeldToken ?
transaction.heldTokenFromSell.add(transaction.depositAmount) :
transaction.heldTokenFromSell;
assert(transaction.collateralAmount == expectedCollateral);
uint256 loanOfferingMinimumHeldToken = MathHelpers.getPartialAmountRoundedUp(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.minHeldToken
);
require(
transaction.collateralAmount >= loanOfferingMinimumHeldToken,
"BorrowShared#validateTxPostSell: Loan offering minimum held token not met"
);
}
function getConsentFromSmartContractLender(
Tx transaction
)
private
{
verifyLoanOfferingRecurse(
transaction.loanOffering.payer,
getLoanOfferingAddresses(transaction),
getLoanOfferingValues256(transaction),
getLoanOfferingValues32(transaction),
transaction.positionId,
transaction.loanOffering.signature
);
}
function verifyLoanOfferingRecurse(
address contractAddr,
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
private
{
address newContractAddr = LoanOfferingVerifier(contractAddr).verifyLoanOffering(
addresses,
values256,
values32,
positionId,
signature
);
if (newContractAddr != contractAddr) {
verifyLoanOfferingRecurse(
newContractAddr,
addresses,
values256,
values32,
positionId,
signature
);
}
}
function pullOwedTokensFromLender(
MarginState.State storage state,
Tx transaction
)
private
{
// Transfer owedToken to the exchange wrapper
TokenProxy(state.TOKEN_PROXY).transferTokens(
transaction.loanOffering.owedToken,
transaction.loanOffering.payer,
transaction.exchangeWrapper,
transaction.lenderAmount
);
}
function transferLoanFees(
MarginState.State storage state,
Tx transaction
)
private
{
// 0 fee address indicates no fees
if (transaction.loanOffering.feeRecipient == address(0)) {
return;
}
TokenProxy proxy = TokenProxy(state.TOKEN_PROXY);
uint256 lenderFee = MathHelpers.getPartialAmount(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.lenderFee
);
uint256 takerFee = MathHelpers.getPartialAmount(
transaction.lenderAmount,
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.takerFee
);
if (lenderFee > 0) {
proxy.transferTokens(
transaction.loanOffering.lenderFeeToken,
transaction.loanOffering.payer,
transaction.loanOffering.feeRecipient,
lenderFee
);
}
if (takerFee > 0) {
proxy.transferTokens(
transaction.loanOffering.takerFeeToken,
msg.sender,
transaction.loanOffering.feeRecipient,
takerFee
);
}
}
function getLoanOfferingAddresses(
Tx transaction
)
private
pure
returns (address[9])
{
return [
transaction.loanOffering.owedToken,
transaction.loanOffering.heldToken,
transaction.loanOffering.payer,
transaction.loanOffering.owner,
transaction.loanOffering.taker,
transaction.loanOffering.positionOwner,
transaction.loanOffering.feeRecipient,
transaction.loanOffering.lenderFeeToken,
transaction.loanOffering.takerFeeToken
];
}
function getLoanOfferingValues256(
Tx transaction
)
private
pure
returns (uint256[7])
{
return [
transaction.loanOffering.rates.maxAmount,
transaction.loanOffering.rates.minAmount,
transaction.loanOffering.rates.minHeldToken,
transaction.loanOffering.rates.lenderFee,
transaction.loanOffering.rates.takerFee,
transaction.loanOffering.expirationTimestamp,
transaction.loanOffering.salt
];
}
function getLoanOfferingValues32(
Tx transaction
)
private
pure
returns (uint32[4])
{
return [
transaction.loanOffering.callTimeLimit,
transaction.loanOffering.maxDuration,
transaction.loanOffering.rates.interestRate,
transaction.loanOffering.rates.interestPeriod
];
}
}
// File: contracts/margin/interfaces/lender/IncreaseLoanDelegator.sol
/**
* @title IncreaseLoanDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to own loans on behalf of other accounts.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface IncreaseLoanDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to allow additional value to be added onto
* an owned loan. Margin will call this on the owner of a loan during increasePosition().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the loan size was successfully increased.
*
* @param payer Lender adding additional funds to the position
* @param positionId Unique ID of the position
* @param principalAdded Principal amount to be added to the position
* @param lentAmount Amount of owedToken lent by the lender (principal plus interest, or
* zero if increaseWithoutCounterparty() is used).
* @return This address to accept, a different address to ask that contract
*/
function increaseLoanOnBehalfOf(
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 lentAmount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/owner/IncreasePositionDelegator.sol
/**
* @title IncreasePositionDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to own position on behalf of other
* accounts
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface IncreasePositionDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to allow additional value to be added onto
* an owned position. Margin will call this on the owner of a position during increasePosition()
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the position size was successfully increased.
*
* @param trader Address initiating the addition of funds to the position
* @param positionId Unique ID of the position
* @param principalAdded Amount of principal to be added to the position
* @return This address to accept, a different address to ask that contract
*/
function increasePositionOnBehalfOf(
address trader,
bytes32 positionId,
uint256 principalAdded
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/IncreasePositionImpl.sol
/**
* @title IncreasePositionImpl
* @author dYdX
*
* This library contains the implementation for the increasePosition function of Margin
*/
library IncreasePositionImpl {
using SafeMath for uint256;
// ============ Events ============
/*
* A position was increased
*/
event PositionIncreased(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
address positionOwner,
address loanOwner,
bytes32 loanHash,
address loanFeeRecipient,
uint256 amountBorrowed,
uint256 principalAdded,
uint256 heldTokenFromSell,
uint256 depositAmount,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function increasePositionImpl(
MarginState.State storage state,
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature,
bytes orderData
)
public
returns (uint256)
{
// Also ensures that the position exists
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
BorrowShared.Tx memory transaction = parseIncreasePositionTx(
position,
positionId,
addresses,
values256,
values32,
depositInHeldToken,
signature
);
validateIncrease(state, transaction, position);
doBorrowAndSell(state, transaction, orderData);
updateState(
position,
transaction.positionId,
transaction.principal,
transaction.lenderAmount,
transaction.loanOffering.payer
);
// LOG EVENT
recordPositionIncreased(transaction, position);
return transaction.lenderAmount;
}
function increaseWithoutCounterpartyImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 principalToAdd
)
public
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
// Disallow adding 0 principal
require(
principalToAdd > 0,
"IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot add 0 principal"
);
// Disallow additions after maximum duration
require(
block.timestamp < uint256(position.startTimestamp).add(position.maxDuration),
"IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot increase after maxDuration"
);
uint256 heldTokenAmount = getCollateralNeededForAddedPrincipal(
state,
position,
positionId,
principalToAdd
);
Vault(state.VAULT).transferToVault(
positionId,
position.heldToken,
msg.sender,
heldTokenAmount
);
updateState(
position,
positionId,
principalToAdd,
0, // lent amount
msg.sender
);
emit PositionIncreased(
positionId,
msg.sender,
msg.sender,
position.owner,
position.lender,
"",
address(0),
0,
principalToAdd,
0,
heldTokenAmount,
true
);
return heldTokenAmount;
}
// ============ Private Helper-Functions ============
function doBorrowAndSell(
MarginState.State storage state,
BorrowShared.Tx memory transaction,
bytes orderData
)
private
{
// Calculate the number of heldTokens to add
uint256 collateralToAdd = getCollateralNeededForAddedPrincipal(
state,
state.positions[transaction.positionId],
transaction.positionId,
transaction.principal
);
// Do pre-exchange validations
BorrowShared.validateTxPreSell(state, transaction);
// Calculate and deposit owedToken
uint256 maxHeldTokenFromSell = MathHelpers.maxUint256();
if (!transaction.depositInHeldToken) {
transaction.depositAmount =
getOwedTokenDeposit(transaction, collateralToAdd, orderData);
BorrowShared.doDepositOwedToken(state, transaction);
maxHeldTokenFromSell = collateralToAdd;
}
// Sell owedToken for heldToken using the exchange wrapper
transaction.heldTokenFromSell = BorrowShared.doSell(
state,
transaction,
orderData,
maxHeldTokenFromSell
);
// Calculate and deposit heldToken
if (transaction.depositInHeldToken) {
require(
transaction.heldTokenFromSell <= collateralToAdd,
"IncreasePositionImpl#doBorrowAndSell: DEX order gives too much heldToken"
);
transaction.depositAmount = collateralToAdd.sub(transaction.heldTokenFromSell);
BorrowShared.doDepositHeldToken(state, transaction);
}
// Make sure the actual added collateral is what is expected
assert(transaction.collateralAmount == collateralToAdd);
// Do post-exchange validations
BorrowShared.doPostSell(state, transaction);
}
function getOwedTokenDeposit(
BorrowShared.Tx transaction,
uint256 collateralToAdd,
bytes orderData
)
private
view
returns (uint256)
{
uint256 totalOwedToken = ExchangeWrapper(transaction.exchangeWrapper).getExchangeCost(
transaction.loanOffering.heldToken,
transaction.loanOffering.owedToken,
collateralToAdd,
orderData
);
require(
transaction.lenderAmount <= totalOwedToken,
"IncreasePositionImpl#getOwedTokenDeposit: Lender amount is more than required"
);
return totalOwedToken.sub(transaction.lenderAmount);
}
function validateIncrease(
MarginState.State storage state,
BorrowShared.Tx transaction,
MarginCommon.Position storage position
)
private
view
{
assert(MarginCommon.containsPositionImpl(state, transaction.positionId));
require(
position.callTimeLimit <= transaction.loanOffering.callTimeLimit,
"IncreasePositionImpl#validateIncrease: Loan callTimeLimit is less than the position"
);
// require the position to end no later than the loanOffering's maximum acceptable end time
uint256 positionEndTimestamp = uint256(position.startTimestamp).add(position.maxDuration);
uint256 offeringEndTimestamp = block.timestamp.add(transaction.loanOffering.maxDuration);
require(
positionEndTimestamp <= offeringEndTimestamp,
"IncreasePositionImpl#validateIncrease: Loan end timestamp is less than the position"
);
require(
block.timestamp < positionEndTimestamp,
"IncreasePositionImpl#validateIncrease: Position has passed its maximum duration"
);
}
function getCollateralNeededForAddedPrincipal(
MarginState.State storage state,
MarginCommon.Position storage position,
bytes32 positionId,
uint256 principalToAdd
)
private
view
returns (uint256)
{
uint256 heldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId);
return MathHelpers.getPartialAmountRoundedUp(
principalToAdd,
position.principal,
heldTokenBalance
);
}
function updateState(
MarginCommon.Position storage position,
bytes32 positionId,
uint256 principalAdded,
uint256 owedTokenLent,
address loanPayer
)
private
{
position.principal = position.principal.add(principalAdded);
address owner = position.owner;
address lender = position.lender;
// Ensure owner consent
increasePositionOnBehalfOfRecurse(
owner,
msg.sender,
positionId,
principalAdded
);
// Ensure lender consent
increaseLoanOnBehalfOfRecurse(
lender,
loanPayer,
positionId,
principalAdded,
owedTokenLent
);
}
function increasePositionOnBehalfOfRecurse(
address contractAddr,
address trader,
bytes32 positionId,
uint256 principalAdded
)
private
{
// Assume owner approval if not a smart contract and they increased their own position
if (trader == contractAddr && !AddressUtils.isContract(contractAddr)) {
return;
}
address newContractAddr =
IncreasePositionDelegator(contractAddr).increasePositionOnBehalfOf(
trader,
positionId,
principalAdded
);
if (newContractAddr != contractAddr) {
increasePositionOnBehalfOfRecurse(
newContractAddr,
trader,
positionId,
principalAdded
);
}
}
function increaseLoanOnBehalfOfRecurse(
address contractAddr,
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 amountLent
)
private
{
// Assume lender approval if not a smart contract and they increased their own loan
if (payer == contractAddr && !AddressUtils.isContract(contractAddr)) {
return;
}
address newContractAddr =
IncreaseLoanDelegator(contractAddr).increaseLoanOnBehalfOf(
payer,
positionId,
principalAdded,
amountLent
);
if (newContractAddr != contractAddr) {
increaseLoanOnBehalfOfRecurse(
newContractAddr,
payer,
positionId,
principalAdded,
amountLent
);
}
}
function recordPositionIncreased(
BorrowShared.Tx transaction,
MarginCommon.Position storage position
)
private
{
emit PositionIncreased(
transaction.positionId,
msg.sender,
transaction.loanOffering.payer,
position.owner,
position.lender,
transaction.loanOffering.loanHash,
transaction.loanOffering.feeRecipient,
transaction.lenderAmount,
transaction.principal,
transaction.heldTokenFromSell,
transaction.depositAmount,
transaction.depositInHeldToken
);
}
// ============ Parsing Functions ============
function parseIncreasePositionTx(
MarginCommon.Position storage position,
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature
)
private
view
returns (BorrowShared.Tx memory)
{
uint256 principal = values256[7];
uint256 lenderAmount = MarginCommon.calculateLenderAmountForIncreasePosition(
position,
principal,
block.timestamp
);
assert(lenderAmount >= principal);
BorrowShared.Tx memory transaction = BorrowShared.Tx({
positionId: positionId,
owner: position.owner,
principal: principal,
lenderAmount: lenderAmount,
loanOffering: parseLoanOfferingFromIncreasePositionTx(
position,
addresses,
values256,
values32,
signature
),
exchangeWrapper: addresses[6],
depositInHeldToken: depositInHeldToken,
depositAmount: 0, // set later
collateralAmount: 0, // set later
heldTokenFromSell: 0 // set later
});
return transaction;
}
function parseLoanOfferingFromIncreasePositionTx(
MarginCommon.Position storage position,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bytes signature
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: position.owedToken,
heldToken: position.heldToken,
payer: addresses[0],
owner: position.lender,
taker: addresses[1],
positionOwner: addresses[2],
feeRecipient: addresses[3],
lenderFeeToken: addresses[4],
takerFeeToken: addresses[5],
rates: parseLoanOfferingRatesFromIncreasePositionTx(position, values256),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: signature
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferingRatesFromIncreasePositionTx(
MarginCommon.Position storage position,
uint256[8] values256
)
private
view
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
lenderFee: values256[3],
takerFee: values256[4],
interestRate: position.interestRate,
interestPeriod: position.interestPeriod
});
return rates;
}
}
// File: contracts/margin/impl/MarginStorage.sol
/**
* @title MarginStorage
* @author dYdX
*
* This contract serves as the storage for the entire state of MarginStorage
*/
contract MarginStorage {
MarginState.State state;
}
// File: contracts/margin/impl/LoanGetters.sol
/**
* @title LoanGetters
* @author dYdX
*
* A collection of public constant getter functions that allows reading of the state of any loan
* offering stored in the dYdX protocol.
*/
contract LoanGetters is MarginStorage {
// ============ Public Constant Functions ============
/**
* Gets the principal amount of a loan offering that is no longer available.
*
* @param loanHash Unique hash of the loan offering
* @return The total unavailable amount of the loan offering, which is equal to the
* filled amount plus the canceled amount.
*/
function getLoanUnavailableAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanHash);
}
/**
* Gets the total amount of owed token lent for a loan.
*
* @param loanHash Unique hash of the loan offering
* @return The total filled amount of the loan offering.
*/
function getLoanFilledAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return state.loanFills[loanHash];
}
/**
* Gets the amount of a loan offering that has been canceled.
*
* @param loanHash Unique hash of the loan offering
* @return The total canceled amount of the loan offering.
*/
function getLoanCanceledAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return state.loanCancels[loanHash];
}
}
// File: contracts/margin/interfaces/lender/CancelMarginCallDelegator.sol
/**
* @title CancelMarginCallDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses cancel a
* margin-call for a loan owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface CancelMarginCallDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call cancelMarginCall().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the margin-call was successfully canceled.
*
* @param canceler Address of the caller of the cancelMarginCall function
* @param positionId Unique ID of the position
* @return This address to accept, a different address to ask that contract
*/
function cancelMarginCallOnBehalfOf(
address canceler,
bytes32 positionId
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/interfaces/lender/MarginCallDelegator.sol
/**
* @title MarginCallDelegator
* @author dYdX
*
* Interface that smart contracts must implement in order to let other addresses margin-call a loan
* owned by the smart contract.
*
* NOTE: Any contract implementing this interface should also use OnlyMargin to control access
* to these functions
*/
interface MarginCallDelegator {
// ============ Public Interface functions ============
/**
* Function a contract must implement in order to let other addresses call marginCall().
*
* NOTE: If not returning zero (or not reverting), this contract must assume that Margin will
* either revert the entire transaction or that the loan was successfully margin-called.
*
* @param caller Address of the caller of the marginCall function
* @param positionId Unique ID of the position
* @param depositAmount Amount of heldToken deposit that will be required to cancel the call
* @return This address to accept, a different address to ask that contract
*/
function marginCallOnBehalfOf(
address caller,
bytes32 positionId,
uint256 depositAmount
)
external
/* onlyMargin */
returns (address);
}
// File: contracts/margin/impl/LoanImpl.sol
/**
* @title LoanImpl
* @author dYdX
*
* This library contains the implementation for the following functions of Margin:
*
* - marginCall
* - cancelMarginCallImpl
* - cancelLoanOffering
*/
library LoanImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was margin-called
*/
event MarginCallInitiated(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 requiredDeposit
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
/**
* A loan offering was canceled before it was used. Any amount less than the
* total for the loan offering can be canceled.
*/
event LoanOfferingCanceled(
bytes32 indexed loanHash,
address indexed payer,
address indexed feeRecipient,
uint256 cancelAmount
);
// ============ Public Implementation Functions ============
function marginCallImpl(
MarginState.State storage state,
bytes32 positionId,
uint256 requiredDeposit
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
position.callTimestamp == 0,
"LoanImpl#marginCallImpl: The position has already been margin-called"
);
// Ensure lender consent
marginCallOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId,
requiredDeposit
);
position.callTimestamp = TimestampHelper.getBlockTimestamp32();
position.requiredDeposit = requiredDeposit;
emit MarginCallInitiated(
positionId,
position.lender,
position.owner,
requiredDeposit
);
}
function cancelMarginCallImpl(
MarginState.State storage state,
bytes32 positionId
)
public
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
position.callTimestamp > 0,
"LoanImpl#cancelMarginCallImpl: Position has not been margin-called"
);
// Ensure lender consent
cancelMarginCallOnBehalfOfRecurse(
position.lender,
msg.sender,
positionId
);
state.positions[positionId].callTimestamp = 0;
state.positions[positionId].requiredDeposit = 0;
emit MarginCallCanceled(
positionId,
position.lender,
position.owner,
0
);
}
function cancelLoanOfferingImpl(
MarginState.State storage state,
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
uint256 cancelAmount
)
public
returns (uint256)
{
MarginCommon.LoanOffering memory loanOffering = parseLoanOffering(
addresses,
values256,
values32
);
require(
msg.sender == loanOffering.payer,
"LoanImpl#cancelLoanOfferingImpl: Only loan offering payer can cancel"
);
require(
loanOffering.expirationTimestamp > block.timestamp,
"LoanImpl#cancelLoanOfferingImpl: Loan offering has already expired"
);
uint256 remainingAmount = loanOffering.rates.maxAmount.sub(
MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanOffering.loanHash)
);
uint256 amountToCancel = Math.min256(remainingAmount, cancelAmount);
// If the loan was already fully canceled, then just return 0 amount was canceled
if (amountToCancel == 0) {
return 0;
}
state.loanCancels[loanOffering.loanHash] =
state.loanCancels[loanOffering.loanHash].add(amountToCancel);
emit LoanOfferingCanceled(
loanOffering.loanHash,
loanOffering.payer,
loanOffering.feeRecipient,
amountToCancel
);
return amountToCancel;
}
// ============ Private Helper-Functions ============
function marginCallOnBehalfOfRecurse(
address contractAddr,
address who,
bytes32 positionId,
uint256 requiredDeposit
)
private
{
// no need to ask for permission
if (who == contractAddr) {
return;
}
address newContractAddr =
MarginCallDelegator(contractAddr).marginCallOnBehalfOf(
msg.sender,
positionId,
requiredDeposit
);
if (newContractAddr != contractAddr) {
marginCallOnBehalfOfRecurse(
newContractAddr,
who,
positionId,
requiredDeposit
);
}
}
function cancelMarginCallOnBehalfOfRecurse(
address contractAddr,
address who,
bytes32 positionId
)
private
{
// no need to ask for permission
if (who == contractAddr) {
return;
}
address newContractAddr =
CancelMarginCallDelegator(contractAddr).cancelMarginCallOnBehalfOf(
msg.sender,
positionId
);
if (newContractAddr != contractAddr) {
cancelMarginCallOnBehalfOfRecurse(
newContractAddr,
who,
positionId
);
}
}
// ============ Parsing Functions ============
function parseLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: addresses[0],
heldToken: addresses[1],
payer: addresses[2],
owner: addresses[3],
taker: addresses[4],
positionOwner: addresses[5],
feeRecipient: addresses[6],
lenderFeeToken: addresses[7],
takerFeeToken: addresses[8],
rates: parseLoanOfferRates(values256, values32),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: new bytes(0)
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferRates(
uint256[7] values256,
uint32[4] values32
)
private
pure
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
interestRate: values32[2],
lenderFee: values256[3],
takerFee: values256[4],
interestPeriod: values32[3]
});
return rates;
}
}
// File: contracts/margin/impl/MarginAdmin.sol
/**
* @title MarginAdmin
* @author dYdX
*
* Contains admin functions for the Margin contract
* The owner can put Margin into various close-only modes, which will disallow new position creation
*/
contract MarginAdmin is Ownable {
// ============ Enums ============
// All functionality enabled
uint8 private constant OPERATION_STATE_OPERATIONAL = 0;
// Only closing functions + cancelLoanOffering allowed (marginCall, closePosition,
// cancelLoanOffering, closePositionDirectly, forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY = 1;
// Only closing functions allowed (marginCall, closePosition, closePositionDirectly,
// forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2;
// Only closing functions allowed (marginCall, closePositionDirectly, forceRecoverCollateral)
uint8 private constant OPERATION_STATE_CLOSE_DIRECTLY_ONLY = 3;
// This operation state (and any higher) is invalid
uint8 private constant OPERATION_STATE_INVALID = 4;
// ============ Events ============
/**
* Event indicating the operation state has changed
*/
event OperationStateChanged(
uint8 from,
uint8 to
);
// ============ State Variables ============
uint8 public operationState;
// ============ Constructor ============
constructor()
public
Ownable()
{
operationState = OPERATION_STATE_OPERATIONAL;
}
// ============ Modifiers ============
modifier onlyWhileOperational() {
require(
operationState == OPERATION_STATE_OPERATIONAL,
"MarginAdmin#onlyWhileOperational: Can only call while operational"
);
_;
}
modifier cancelLoanOfferingStateControl() {
require(
operationState == OPERATION_STATE_OPERATIONAL
|| operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY,
"MarginAdmin#cancelLoanOfferingStateControl: Invalid operation state"
);
_;
}
modifier closePositionStateControl() {
require(
operationState == OPERATION_STATE_OPERATIONAL
|| operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY
|| operationState == OPERATION_STATE_CLOSE_ONLY,
"MarginAdmin#closePositionStateControl: Invalid operation state"
);
_;
}
modifier closePositionDirectlyStateControl() {
_;
}
// ============ Owner-Only State-Changing Functions ============
function setOperationState(
uint8 newState
)
external
onlyOwner
{
require(
newState < OPERATION_STATE_INVALID,
"MarginAdmin#setOperationState: newState is not a valid operation state"
);
if (newState != operationState) {
emit OperationStateChanged(
operationState,
newState
);
operationState = newState;
}
}
}
// File: contracts/margin/impl/MarginEvents.sol
/**
* @title MarginEvents
* @author dYdX
*
* Contains events for the Margin contract.
*
* NOTE: Any Margin function libraries that use events will need to both define the event here
* and copy the event into the library itself as libraries don't support sharing events
*/
contract MarginEvents {
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
/*
* A position was increased
*/
event PositionIncreased(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
address positionOwner,
address loanOwner,
bytes32 loanHash,
address loanFeeRecipient,
uint256 amountBorrowed,
uint256 principalAdded,
uint256 heldTokenFromSell,
uint256 depositAmount,
bool depositInHeldToken
);
/**
* A position was closed or partially closed
*/
event PositionClosed(
bytes32 indexed positionId,
address indexed closer,
address indexed payoutRecipient,
uint256 closeAmount,
uint256 remainingAmount,
uint256 owedTokenPaidToLender,
uint256 payoutAmount,
uint256 buybackCostInHeldToken,
bool payoutInHeldToken
);
/**
* Collateral for a position was forcibly recovered
*/
event CollateralForceRecovered(
bytes32 indexed positionId,
address indexed recipient,
uint256 amount
);
/**
* A position was margin-called
*/
event MarginCallInitiated(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 requiredDeposit
);
/**
* A margin call was canceled
*/
event MarginCallCanceled(
bytes32 indexed positionId,
address indexed lender,
address indexed owner,
uint256 depositAmount
);
/**
* A loan offering was canceled before it was used. Any amount less than the
* total for the loan offering can be canceled.
*/
event LoanOfferingCanceled(
bytes32 indexed loanHash,
address indexed payer,
address indexed feeRecipient,
uint256 cancelAmount
);
/**
* Additional collateral for a position was posted by the owner
*/
event AdditionalCollateralDeposited(
bytes32 indexed positionId,
uint256 amount,
address depositor
);
/**
* Ownership of a loan was transferred to a new address
*/
event LoanTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
/**
* Ownership of a position was transferred to a new address
*/
event PositionTransferred(
bytes32 indexed positionId,
address indexed from,
address indexed to
);
}
// File: contracts/margin/impl/OpenPositionImpl.sol
/**
* @title OpenPositionImpl
* @author dYdX
*
* This library contains the implementation for the openPosition function of Margin
*/
library OpenPositionImpl {
using SafeMath for uint256;
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function openPositionImpl(
MarginState.State storage state,
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature,
bytes orderData
)
public
returns (bytes32)
{
BorrowShared.Tx memory transaction = parseOpenTx(
addresses,
values256,
values32,
depositInHeldToken,
signature
);
require(
!MarginCommon.positionHasExisted(state, transaction.positionId),
"OpenPositionImpl#openPositionImpl: positionId already exists"
);
doBorrowAndSell(state, transaction, orderData);
// Before doStoreNewPosition() so that PositionOpened event is before Transferred events
recordPositionOpened(
transaction
);
doStoreNewPosition(
state,
transaction
);
return transaction.positionId;
}
// ============ Private Helper-Functions ============
function doBorrowAndSell(
MarginState.State storage state,
BorrowShared.Tx memory transaction,
bytes orderData
)
private
{
BorrowShared.validateTxPreSell(state, transaction);
if (transaction.depositInHeldToken) {
BorrowShared.doDepositHeldToken(state, transaction);
} else {
BorrowShared.doDepositOwedToken(state, transaction);
}
transaction.heldTokenFromSell = BorrowShared.doSell(
state,
transaction,
orderData,
MathHelpers.maxUint256()
);
BorrowShared.doPostSell(state, transaction);
}
function doStoreNewPosition(
MarginState.State storage state,
BorrowShared.Tx memory transaction
)
private
{
MarginCommon.storeNewPosition(
state,
transaction.positionId,
MarginCommon.Position({
owedToken: transaction.loanOffering.owedToken,
heldToken: transaction.loanOffering.heldToken,
lender: transaction.loanOffering.owner,
owner: transaction.owner,
principal: transaction.principal,
requiredDeposit: 0,
callTimeLimit: transaction.loanOffering.callTimeLimit,
startTimestamp: 0,
callTimestamp: 0,
maxDuration: transaction.loanOffering.maxDuration,
interestRate: transaction.loanOffering.rates.interestRate,
interestPeriod: transaction.loanOffering.rates.interestPeriod
}),
transaction.loanOffering.payer
);
}
function recordPositionOpened(
BorrowShared.Tx transaction
)
private
{
emit PositionOpened(
transaction.positionId,
msg.sender,
transaction.loanOffering.payer,
transaction.loanOffering.loanHash,
transaction.loanOffering.owedToken,
transaction.loanOffering.heldToken,
transaction.loanOffering.feeRecipient,
transaction.principal,
transaction.heldTokenFromSell,
transaction.depositAmount,
transaction.loanOffering.rates.interestRate,
transaction.loanOffering.callTimeLimit,
transaction.loanOffering.maxDuration,
transaction.depositInHeldToken
);
}
// ============ Parsing Functions ============
function parseOpenTx(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature
)
private
view
returns (BorrowShared.Tx memory)
{
BorrowShared.Tx memory transaction = BorrowShared.Tx({
positionId: MarginCommon.getPositionIdFromNonce(values256[9]),
owner: addresses[0],
principal: values256[7],
lenderAmount: values256[7],
loanOffering: parseLoanOffering(
addresses,
values256,
values32,
signature
),
exchangeWrapper: addresses[10],
depositInHeldToken: depositInHeldToken,
depositAmount: values256[8],
collateralAmount: 0, // set later
heldTokenFromSell: 0 // set later
});
return transaction;
}
function parseLoanOffering(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bytes signature
)
private
view
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({
owedToken: addresses[1],
heldToken: addresses[2],
payer: addresses[3],
owner: addresses[4],
taker: addresses[5],
positionOwner: addresses[6],
feeRecipient: addresses[7],
lenderFeeToken: addresses[8],
takerFeeToken: addresses[9],
rates: parseLoanOfferRates(values256, values32),
expirationTimestamp: values256[5],
callTimeLimit: values32[0],
maxDuration: values32[1],
salt: values256[6],
loanHash: 0,
signature: signature
});
loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering);
return loanOffering;
}
function parseLoanOfferRates(
uint256[10] values256,
uint32[4] values32
)
private
pure
returns (MarginCommon.LoanRates memory)
{
MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({
maxAmount: values256[0],
minAmount: values256[1],
minHeldToken: values256[2],
lenderFee: values256[3],
takerFee: values256[4],
interestRate: values32[2],
interestPeriod: values32[3]
});
return rates;
}
}
// File: contracts/margin/impl/OpenWithoutCounterpartyImpl.sol
/**
* @title OpenWithoutCounterpartyImpl
* @author dYdX
*
* This library contains the implementation for the openWithoutCounterparty
* function of Margin
*/
library OpenWithoutCounterpartyImpl {
// ============ Structs ============
struct Tx {
bytes32 positionId;
address positionOwner;
address owedToken;
address heldToken;
address loanOwner;
uint256 principal;
uint256 deposit;
uint32 callTimeLimit;
uint32 maxDuration;
uint32 interestRate;
uint32 interestPeriod;
}
// ============ Events ============
/**
* A position was opened
*/
event PositionOpened(
bytes32 indexed positionId,
address indexed trader,
address indexed lender,
bytes32 loanHash,
address owedToken,
address heldToken,
address loanFeeRecipient,
uint256 principal,
uint256 heldTokenFromSell,
uint256 depositAmount,
uint256 interestRate,
uint32 callTimeLimit,
uint32 maxDuration,
bool depositInHeldToken
);
// ============ Public Implementation Functions ============
function openWithoutCounterpartyImpl(
MarginState.State storage state,
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
public
returns (bytes32)
{
Tx memory openTx = parseTx(
addresses,
values256,
values32
);
validate(
state,
openTx
);
Vault(state.VAULT).transferToVault(
openTx.positionId,
openTx.heldToken,
msg.sender,
openTx.deposit
);
recordPositionOpened(
openTx
);
doStoreNewPosition(
state,
openTx
);
return openTx.positionId;
}
// ============ Private Helper-Functions ============
function doStoreNewPosition(
MarginState.State storage state,
Tx memory openTx
)
private
{
MarginCommon.storeNewPosition(
state,
openTx.positionId,
MarginCommon.Position({
owedToken: openTx.owedToken,
heldToken: openTx.heldToken,
lender: openTx.loanOwner,
owner: openTx.positionOwner,
principal: openTx.principal,
requiredDeposit: 0,
callTimeLimit: openTx.callTimeLimit,
startTimestamp: 0,
callTimestamp: 0,
maxDuration: openTx.maxDuration,
interestRate: openTx.interestRate,
interestPeriod: openTx.interestPeriod
}),
msg.sender
);
}
function validate(
MarginState.State storage state,
Tx memory openTx
)
private
view
{
require(
!MarginCommon.positionHasExisted(state, openTx.positionId),
"openWithoutCounterpartyImpl#validate: positionId already exists"
);
require(
openTx.principal > 0,
"openWithoutCounterpartyImpl#validate: principal cannot be 0"
);
require(
openTx.owedToken != address(0),
"openWithoutCounterpartyImpl#validate: owedToken cannot be 0"
);
require(
openTx.owedToken != openTx.heldToken,
"openWithoutCounterpartyImpl#validate: owedToken cannot be equal to heldToken"
);
require(
openTx.positionOwner != address(0),
"openWithoutCounterpartyImpl#validate: positionOwner cannot be 0"
);
require(
openTx.loanOwner != address(0),
"openWithoutCounterpartyImpl#validate: loanOwner cannot be 0"
);
require(
openTx.maxDuration > 0,
"openWithoutCounterpartyImpl#validate: maxDuration cannot be 0"
);
require(
openTx.interestPeriod <= openTx.maxDuration,
"openWithoutCounterpartyImpl#validate: interestPeriod must be <= maxDuration"
);
}
function recordPositionOpened(
Tx memory openTx
)
private
{
emit PositionOpened(
openTx.positionId,
msg.sender,
msg.sender,
bytes32(0),
openTx.owedToken,
openTx.heldToken,
address(0),
openTx.principal,
0,
openTx.deposit,
openTx.interestRate,
openTx.callTimeLimit,
openTx.maxDuration,
true
);
}
// ============ Parsing Functions ============
function parseTx(
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
private
view
returns (Tx memory)
{
Tx memory openTx = Tx({
positionId: MarginCommon.getPositionIdFromNonce(values256[2]),
positionOwner: addresses[0],
owedToken: addresses[1],
heldToken: addresses[2],
loanOwner: addresses[3],
principal: values256[0],
deposit: values256[1],
callTimeLimit: values32[0],
maxDuration: values32[1],
interestRate: values32[2],
interestPeriod: values32[3]
});
return openTx;
}
}
// File: contracts/margin/impl/PositionGetters.sol
/**
* @title PositionGetters
* @author dYdX
*
* A collection of public constant getter functions that allows reading of the state of any position
* stored in the dYdX protocol.
*/
contract PositionGetters is MarginStorage {
using SafeMath for uint256;
// ============ Public Constant Functions ============
/**
* Gets if a position is currently open.
*
* @param positionId Unique ID of the position
* @return True if the position is exists and is open
*/
function containsPosition(
bytes32 positionId
)
external
view
returns (bool)
{
return MarginCommon.containsPositionImpl(state, positionId);
}
/**
* Gets if a position is currently margin-called.
*
* @param positionId Unique ID of the position
* @return True if the position is margin-called
*/
function isPositionCalled(
bytes32 positionId
)
external
view
returns (bool)
{
return (state.positions[positionId].callTimestamp > 0);
}
/**
* Gets if a position was previously open and is now closed.
*
* @param positionId Unique ID of the position
* @return True if the position is now closed
*/
function isPositionClosed(
bytes32 positionId
)
external
view
returns (bool)
{
return state.closedPositions[positionId];
}
/**
* Gets the total amount of owedToken ever repaid to the lender for a position.
*
* @param positionId Unique ID of the position
* @return Total amount of owedToken ever repaid
*/
function getTotalOwedTokenRepaidToLender(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.totalOwedTokenRepaidToLender[positionId];
}
/**
* Gets the amount of heldToken currently locked up in Vault for a particular position.
*
* @param positionId Unique ID of the position
* @return The amount of heldToken
*/
function getPositionBalance(
bytes32 positionId
)
external
view
returns (uint256)
{
return MarginCommon.getPositionBalanceImpl(state, positionId);
}
/**
* Gets the time until the interest fee charged for the position will increase.
* Returns 1 if the interest fee increases every second.
* Returns 0 if the interest fee will never increase again.
*
* @param positionId Unique ID of the position
* @return The number of seconds until the interest fee will increase
*/
function getTimeUntilInterestIncrease(
bytes32 positionId
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
uint256 effectiveTimeElapsed = MarginCommon.calculateEffectiveTimeElapsed(
position,
block.timestamp
);
uint256 absoluteTimeElapsed = block.timestamp.sub(position.startTimestamp);
if (absoluteTimeElapsed > effectiveTimeElapsed) { // past maxDuration
return 0;
} else {
// nextStep is the final second at which the calculated interest fee is the same as it
// is currently, so add 1 to get the correct value
return effectiveTimeElapsed.add(1).sub(absoluteTimeElapsed);
}
}
/**
* Gets the amount of owedTokens currently needed to close the position completely, including
* interest fees.
*
* @param positionId Unique ID of the position
* @return The number of owedTokens
*/
function getPositionOwedAmount(
bytes32 positionId
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
return MarginCommon.calculateOwedAmount(
position,
position.principal,
block.timestamp
);
}
/**
* Gets the amount of owedTokens needed to close a given principal amount of the position at a
* given time, including interest fees.
*
* @param positionId Unique ID of the position
* @param principalToClose Amount of principal being closed
* @param timestamp Block timestamp in seconds of close
* @return The number of owedTokens owed
*/
function getPositionOwedAmountAtTime(
bytes32 positionId,
uint256 principalToClose,
uint32 timestamp
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
timestamp >= position.startTimestamp,
"PositionGetters#getPositionOwedAmountAtTime: Requested time before position started"
);
return MarginCommon.calculateOwedAmount(
position,
principalToClose,
timestamp
);
}
/**
* Gets the amount of owedTokens that can be borrowed from a lender to add a given principal
* amount to the position at a given time.
*
* @param positionId Unique ID of the position
* @param principalToAdd Amount being added to principal
* @param timestamp Block timestamp in seconds of addition
* @return The number of owedTokens that will be borrowed
*/
function getLenderAmountForIncreasePositionAtTime(
bytes32 positionId,
uint256 principalToAdd,
uint32 timestamp
)
external
view
returns (uint256)
{
MarginCommon.Position storage position =
MarginCommon.getPositionFromStorage(state, positionId);
require(
timestamp >= position.startTimestamp,
"PositionGetters#getLenderAmountForIncreasePositionAtTime: timestamp < position start"
);
return MarginCommon.calculateLenderAmountForIncreasePosition(
position,
principalToAdd,
timestamp
);
}
// ============ All Properties ============
/**
* Get a Position by id. This does not validate the position exists. If the position does not
* exist, all 0's will be returned.
*
* @param positionId Unique ID of the position
* @return Addresses corresponding to:
*
* [0] = owedToken
* [1] = heldToken
* [2] = lender
* [3] = owner
*
* Values corresponding to:
*
* [0] = principal
* [1] = requiredDeposit
*
* Values corresponding to:
*
* [0] = callTimeLimit
* [1] = startTimestamp
* [2] = callTimestamp
* [3] = maxDuration
* [4] = interestRate
* [5] = interestPeriod
*/
function getPosition(
bytes32 positionId
)
external
view
returns (
address[4],
uint256[2],
uint32[6]
)
{
MarginCommon.Position storage position = state.positions[positionId];
return (
[
position.owedToken,
position.heldToken,
position.lender,
position.owner
],
[
position.principal,
position.requiredDeposit
],
[
position.callTimeLimit,
position.startTimestamp,
position.callTimestamp,
position.maxDuration,
position.interestRate,
position.interestPeriod
]
);
}
// ============ Individual Properties ============
function getPositionLender(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].lender;
}
function getPositionOwner(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].owner;
}
function getPositionHeldToken(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].heldToken;
}
function getPositionOwedToken(
bytes32 positionId
)
external
view
returns (address)
{
return state.positions[positionId].owedToken;
}
function getPositionPrincipal(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].principal;
}
function getPositionInterestRate(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].interestRate;
}
function getPositionRequiredDeposit(
bytes32 positionId
)
external
view
returns (uint256)
{
return state.positions[positionId].requiredDeposit;
}
function getPositionStartTimestamp(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].startTimestamp;
}
function getPositionCallTimestamp(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].callTimestamp;
}
function getPositionCallTimeLimit(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].callTimeLimit;
}
function getPositionMaxDuration(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].maxDuration;
}
function getPositioninterestPeriod(
bytes32 positionId
)
external
view
returns (uint32)
{
return state.positions[positionId].interestPeriod;
}
}
// File: contracts/margin/impl/TransferImpl.sol
/**
* @title TransferImpl
* @author dYdX
*
* This library contains the implementation for the transferPosition and transferLoan functions of
* Margin
*/
library TransferImpl {
// ============ Public Implementation Functions ============
function transferLoanImpl(
MarginState.State storage state,
bytes32 positionId,
address newLender
)
public
{
require(
MarginCommon.containsPositionImpl(state, positionId),
"TransferImpl#transferLoanImpl: Position does not exist"
);
address originalLender = state.positions[positionId].lender;
require(
msg.sender == originalLender,
"TransferImpl#transferLoanImpl: Only lender can transfer ownership"
);
require(
newLender != originalLender,
"TransferImpl#transferLoanImpl: Cannot transfer ownership to self"
);
// Doesn't change the state of positionId; figures out the final owner of loan.
// That is, newLender may pass ownership to a different address.
address finalLender = TransferInternal.grantLoanOwnership(
positionId,
originalLender,
newLender);
require(
finalLender != originalLender,
"TransferImpl#transferLoanImpl: Cannot ultimately transfer ownership to self"
);
// Set state only after resolving the new owner (to reduce the number of storage calls)
state.positions[positionId].lender = finalLender;
}
function transferPositionImpl(
MarginState.State storage state,
bytes32 positionId,
address newOwner
)
public
{
require(
MarginCommon.containsPositionImpl(state, positionId),
"TransferImpl#transferPositionImpl: Position does not exist"
);
address originalOwner = state.positions[positionId].owner;
require(
msg.sender == originalOwner,
"TransferImpl#transferPositionImpl: Only position owner can transfer ownership"
);
require(
newOwner != originalOwner,
"TransferImpl#transferPositionImpl: Cannot transfer ownership to self"
);
// Doesn't change the state of positionId; figures out the final owner of position.
// That is, newOwner may pass ownership to a different address.
address finalOwner = TransferInternal.grantPositionOwnership(
positionId,
originalOwner,
newOwner);
require(
finalOwner != originalOwner,
"TransferImpl#transferPositionImpl: Cannot ultimately transfer ownership to self"
);
// Set state only after resolving the new owner (to reduce the number of storage calls)
state.positions[positionId].owner = finalOwner;
}
}
// File: contracts/margin/Margin.sol
/**
* @title Margin
* @author dYdX
*
* This contract is used to facilitate margin trading as per the dYdX protocol
*/
contract Margin is
ReentrancyGuard,
MarginStorage,
MarginEvents,
MarginAdmin,
LoanGetters,
PositionGetters
{
using SafeMath for uint256;
// ============ Constructor ============
constructor(
address vault,
address proxy
)
public
MarginAdmin()
{
state = MarginState.State({
VAULT: vault,
TOKEN_PROXY: proxy
});
}
// ============ Public State Changing Functions ============
/**
* Open a margin position. Called by the margin trader who must provide both a
* signed loan offering as well as a DEX Order with which to sell the owedToken.
*
* @param addresses Addresses corresponding to:
*
* [0] = position owner
* [1] = owedToken
* [2] = heldToken
* [3] = loan payer
* [4] = loan owner
* [5] = loan taker
* [6] = loan position owner
* [7] = loan fee recipient
* [8] = loan lender fee token
* [9] = loan taker fee token
* [10] = exchange wrapper address
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
* [7] = position amount of principal
* [8] = deposit amount
* [9] = nonce (used to calculate positionId)
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken.
* False if the margin deposit will be in owedToken
* and then sold along with the owedToken borrowed from the lender
* @param signature If loan payer is an account, then this must be the tightly-packed
* ECDSA V/R/S parameters from signing the loan hash. If loan payer
* is a smart contract, these are arbitrary bytes that the contract
* will recieve when choosing whether to approve the loan.
* @param order Order object to be passed to the exchange wrapper
* @return Unique ID for the new position
*/
function openPosition(
address[11] addresses,
uint256[10] values256,
uint32[4] values32,
bool depositInHeldToken,
bytes signature,
bytes order
)
external
onlyWhileOperational
nonReentrant
returns (bytes32)
{
return OpenPositionImpl.openPositionImpl(
state,
addresses,
values256,
values32,
depositInHeldToken,
signature,
order
);
}
/**
* Open a margin position without a counterparty. The caller will serve as both the
* lender and the position owner
*
* @param addresses Addresses corresponding to:
*
* [0] = position owner
* [1] = owedToken
* [2] = heldToken
* [3] = loan owner
*
* @param values256 Values corresponding to:
*
* [0] = principal
* [1] = deposit amount
* [2] = nonce (used to calculate positionId)
*
* @param values32 Values corresponding to:
*
* [0] = call time limit (in seconds)
* [1] = maxDuration (in seconds)
* [2] = interest rate (annual nominal percentage times 10**6)
* [3] = interest update period (in seconds)
*
* @return Unique ID for the new position
*/
function openWithoutCounterparty(
address[4] addresses,
uint256[3] values256,
uint32[4] values32
)
external
onlyWhileOperational
nonReentrant
returns (bytes32)
{
return OpenWithoutCounterpartyImpl.openWithoutCounterpartyImpl(
state,
addresses,
values256,
values32
);
}
/**
* Increase the size of a position. Funds will be borrowed from the loan payer and sold as per
* the position. The amount of owedToken borrowed from the lender will be >= the amount of
* principal added, as it will incorporate interest already earned by the position so far.
*
* @param positionId Unique ID of the position
* @param addresses Addresses corresponding to:
*
* [0] = loan payer
* [1] = loan taker
* [2] = loan position owner
* [3] = loan fee recipient
* [4] = loan lender fee token
* [5] = loan taker fee token
* [6] = exchange wrapper address
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
* [7] = amount of principal to add to the position (NOTE: the amount pulled from the lender
* will be >= this amount)
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
*
* @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken.
* False if the margin deposit will be pulled in owedToken
* and then sold along with the owedToken borrowed from the lender
* @param signature If loan payer is an account, then this must be the tightly-packed
* ECDSA V/R/S parameters from signing the loan hash. If loan payer
* is a smart contract, these are arbitrary bytes that the contract
* will recieve when choosing whether to approve the loan.
* @param order Order object to be passed to the exchange wrapper
* @return Amount of owedTokens pulled from the lender
*/
function increasePosition(
bytes32 positionId,
address[7] addresses,
uint256[8] values256,
uint32[2] values32,
bool depositInHeldToken,
bytes signature,
bytes order
)
external
onlyWhileOperational
nonReentrant
returns (uint256)
{
return IncreasePositionImpl.increasePositionImpl(
state,
positionId,
addresses,
values256,
values32,
depositInHeldToken,
signature,
order
);
}
/**
* Increase a position directly by putting up heldToken. The caller will serve as both the
* lender and the position owner
*
* @param positionId Unique ID of the position
* @param principalToAdd Principal amount to add to the position
* @return Amount of heldToken pulled from the msg.sender
*/
function increaseWithoutCounterparty(
bytes32 positionId,
uint256 principalToAdd
)
external
onlyWhileOperational
nonReentrant
returns (uint256)
{
return IncreasePositionImpl.increaseWithoutCounterpartyImpl(
state,
positionId,
principalToAdd
);
}
/**
* Close a position. May be called by the owner or with the approval of the owner. May provide
* an order and exchangeWrapper to facilitate the closing of the position. The payoutRecipient
* is sent the resulting payout.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @param exchangeWrapper Address of the exchange wrapper
* @param payoutInHeldToken True to pay out the payoutRecipient in heldToken,
* False to pay out the payoutRecipient in owedToken
* @param order Order object to be passed to the exchange wrapper
* @return Values corresponding to:
* 1) Principal of position closed
* 2) Amount of tokens (heldToken if payoutInHeldtoken is true,
* owedToken otherwise) received by the payoutRecipient
* 3) Amount of owedToken paid (incl. interest fee) to the lender
*/
function closePosition(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient,
address exchangeWrapper,
bool payoutInHeldToken,
bytes order
)
external
closePositionStateControl
nonReentrant
returns (uint256, uint256, uint256)
{
return ClosePositionImpl.closePositionImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
exchangeWrapper,
payoutInHeldToken,
order
);
}
/**
* Helper to close a position by paying owedToken directly rather than using an exchangeWrapper.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* @param payoutRecipient Address of the recipient of tokens paid out from closing
* @return Values corresponding to:
* 1) Principal amount of position closed
* 2) Amount of heldToken received by the payoutRecipient
* 3) Amount of owedToken paid (incl. interest fee) to the lender
*/
function closePositionDirectly(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
external
closePositionDirectlyStateControl
nonReentrant
returns (uint256, uint256, uint256)
{
return ClosePositionImpl.closePositionImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient,
address(0),
true,
new bytes(0)
);
}
/**
* Reduce the size of a position and withdraw a proportional amount of heldToken from the vault.
* Must be approved by both the position owner and lender.
*
* @param positionId Unique ID of the position
* @param requestedCloseAmount Principal amount of the position to close. The actual amount
* closed is also bounded by:
* 1) The principal of the position
* 2) The amount allowed by the owner if closer != owner
* 3) The amount allowed by the lender if closer != lender
* @return Values corresponding to:
* 1) Principal amount of position closed
* 2) Amount of heldToken received by the msg.sender
*/
function closeWithoutCounterparty(
bytes32 positionId,
uint256 requestedCloseAmount,
address payoutRecipient
)
external
closePositionStateControl
nonReentrant
returns (uint256, uint256)
{
return CloseWithoutCounterpartyImpl.closeWithoutCounterpartyImpl(
state,
positionId,
requestedCloseAmount,
payoutRecipient
);
}
/**
* Margin-call a position. Only callable with the approval of the position lender. After the
* call, the position owner will have time equal to the callTimeLimit of the position to close
* the position. If the owner does not close the position, the lender can recover the collateral
* in the position.
*
* @param positionId Unique ID of the position
* @param requiredDeposit Amount of deposit the position owner will have to put up to cancel
* the margin-call. Passing in 0 means the margin call cannot be
* canceled by depositing
*/
function marginCall(
bytes32 positionId,
uint256 requiredDeposit
)
external
nonReentrant
{
LoanImpl.marginCallImpl(
state,
positionId,
requiredDeposit
);
}
/**
* Cancel a margin-call. Only callable with the approval of the position lender.
*
* @param positionId Unique ID of the position
*/
function cancelMarginCall(
bytes32 positionId
)
external
onlyWhileOperational
nonReentrant
{
LoanImpl.cancelMarginCallImpl(state, positionId);
}
/**
* Used to recover the heldTokens held as collateral. Is callable after the maximum duration of
* the loan has expired or the loan has been margin-called for the duration of the callTimeLimit
* but remains unclosed. Only callable with the approval of the position lender.
*
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return Amount of heldToken recovered
*/
function forceRecoverCollateral(
bytes32 positionId,
address recipient
)
external
nonReentrant
returns (uint256)
{
return ForceRecoverCollateralImpl.forceRecoverCollateralImpl(
state,
positionId,
recipient
);
}
/**
* Deposit additional heldToken as collateral for a position. Cancels margin-call if:
* 0 < position.requiredDeposit < depositAmount. Only callable by the position owner.
*
* @param positionId Unique ID of the position
* @param depositAmount Additional amount in heldToken to deposit
*/
function depositCollateral(
bytes32 positionId,
uint256 depositAmount
)
external
onlyWhileOperational
nonReentrant
{
DepositCollateralImpl.depositCollateralImpl(
state,
positionId,
depositAmount
);
}
/**
* Cancel an amount of a loan offering. Only callable by the loan offering's payer.
*
* @param addresses Array of addresses:
*
* [0] = owedToken
* [1] = heldToken
* [2] = loan payer
* [3] = loan owner
* [4] = loan taker
* [5] = loan position owner
* [6] = loan fee recipient
* [7] = loan lender fee token
* [8] = loan taker fee token
*
* @param values256 Values corresponding to:
*
* [0] = loan maximum amount
* [1] = loan minimum amount
* [2] = loan minimum heldToken
* [3] = loan lender fee
* [4] = loan taker fee
* [5] = loan expiration timestamp (in seconds)
* [6] = loan salt
*
* @param values32 Values corresponding to:
*
* [0] = loan call time limit (in seconds)
* [1] = loan maxDuration (in seconds)
* [2] = loan interest rate (annual nominal percentage times 10**6)
* [3] = loan interest update period (in seconds)
*
* @param cancelAmount Amount to cancel
* @return Amount that was canceled
*/
function cancelLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
uint256 cancelAmount
)
external
cancelLoanOfferingStateControl
nonReentrant
returns (uint256)
{
return LoanImpl.cancelLoanOfferingImpl(
state,
addresses,
values256,
values32,
cancelAmount
);
}
/**
* Transfer ownership of a loan to a new address. This new address will be entitled to all
* payouts for this loan. Only callable by the lender for a position. If "who" is a contract, it
* must implement the LoanOwner interface.
*
* @param positionId Unique ID of the position
* @param who New owner of the loan
*/
function transferLoan(
bytes32 positionId,
address who
)
external
nonReentrant
{
TransferImpl.transferLoanImpl(
state,
positionId,
who);
}
/**
* Transfer ownership of a position to a new address. This new address will be entitled to all
* payouts. Only callable by the owner of a position. If "who" is a contract, it must implement
* the PositionOwner interface.
*
* @param positionId Unique ID of the position
* @param who New owner of the position
*/
function transferPosition(
bytes32 positionId,
address who
)
external
nonReentrant
{
TransferImpl.transferPositionImpl(
state,
positionId,
who);
}
// ============ Public Constant Functions ============
/**
* Gets the address of the Vault contract that holds and accounts for tokens.
*
* @return The address of the Vault contract
*/
function getVaultAddress()
external
view
returns (address)
{
return state.VAULT;
}
/**
* Gets the address of the TokenProxy contract that accounts must set allowance on in order to
* make loans or open/close positions.
*
* @return The address of the TokenProxy contract
*/
function getTokenProxyAddress()
external
view
returns (address)
{
return state.TOKEN_PROXY;
}
}
// File: contracts/margin/interfaces/OnlyMargin.sol
/**
* @title OnlyMargin
* @author dYdX
*
* Contract to store the address of the main Margin contract and trust only that address to call
* certain functions.
*/
contract OnlyMargin {
// ============ Constants ============
// Address of the known and trusted Margin contract on the blockchain
address public DYDX_MARGIN;
// ============ Constructor ============
constructor(
address margin
)
public
{
DYDX_MARGIN = margin;
}
// ============ Modifiers ============
modifier onlyMargin()
{
require(
msg.sender == DYDX_MARGIN,
"OnlyMargin#onlyMargin: Only Margin can call"
);
_;
}
}
// File: contracts/margin/external/lib/LoanOfferingParser.sol
/**
* @title LoanOfferingParser
* @author dYdX
*
* Contract for LoanOfferingVerifiers to parse arguments
*/
contract LoanOfferingParser {
// ============ Parsing Functions ============
function parseLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes signature
)
internal
pure
returns (MarginCommon.LoanOffering memory)
{
MarginCommon.LoanOffering memory loanOffering;
fillLoanOfferingAddresses(loanOffering, addresses);
fillLoanOfferingValues256(loanOffering, values256);
fillLoanOfferingValues32(loanOffering, values32);
loanOffering.signature = signature;
return loanOffering;
}
function fillLoanOfferingAddresses(
MarginCommon.LoanOffering memory loanOffering,
address[9] addresses
)
private
pure
{
loanOffering.owedToken = addresses[0];
loanOffering.heldToken = addresses[1];
loanOffering.payer = addresses[2];
loanOffering.owner = addresses[3];
loanOffering.taker = addresses[4];
loanOffering.positionOwner = addresses[5];
loanOffering.feeRecipient = addresses[6];
loanOffering.lenderFeeToken = addresses[7];
loanOffering.takerFeeToken = addresses[8];
}
function fillLoanOfferingValues256(
MarginCommon.LoanOffering memory loanOffering,
uint256[7] values256
)
private
pure
{
loanOffering.rates.maxAmount = values256[0];
loanOffering.rates.minAmount = values256[1];
loanOffering.rates.minHeldToken = values256[2];
loanOffering.rates.lenderFee = values256[3];
loanOffering.rates.takerFee = values256[4];
loanOffering.expirationTimestamp = values256[5];
loanOffering.salt = values256[6];
}
function fillLoanOfferingValues32(
MarginCommon.LoanOffering memory loanOffering,
uint32[4] values32
)
private
pure
{
loanOffering.callTimeLimit = values32[0];
loanOffering.maxDuration = values32[1];
loanOffering.rates.interestRate = values32[2];
loanOffering.rates.interestPeriod = values32[3];
}
}
// File: contracts/margin/external/lib/MarginHelper.sol
/**
* @title MarginHelper
* @author dYdX
*
* This library contains helper functions for interacting with Margin
*/
library MarginHelper {
function getPosition(
address DYDX_MARGIN,
bytes32 positionId
)
internal
view
returns (MarginCommon.Position memory)
{
(
address[4] memory addresses,
uint256[2] memory values256,
uint32[6] memory values32
) = Margin(DYDX_MARGIN).getPosition(positionId);
return MarginCommon.Position({
owedToken: addresses[0],
heldToken: addresses[1],
lender: addresses[2],
owner: addresses[3],
principal: values256[0],
requiredDeposit: values256[1],
callTimeLimit: values32[0],
startTimestamp: values32[1],
callTimestamp: values32[2],
maxDuration: values32[3],
interestRate: values32[4],
interestPeriod: values32[5]
});
}
}
// File: contracts/margin/external/BucketLender/BucketLender.sol
/**
* @title BucketLender
* @author dYdX
*
* On-chain shared lender that allows anyone to deposit tokens into this contract to be used to
* lend tokens for a particular margin position.
*
* - Each bucket has three variables:
* - Available Amount
* - The available amount of tokens that the bucket has to lend out
* - Outstanding Principal
* - The amount of principal that the bucket is responsible for in the margin position
* - Weight
* - Used to keep track of each account's weighted ownership within a bucket
* - Relative weight between buckets is meaningless
* - Only accounts' relative weight within a bucket matters
*
* - Token Deposits:
* - Go into a particular bucket, determined by time since the start of the position
* - If the position has not started: bucket = 0
* - If the position has started: bucket = ceiling(time_since_start / BUCKET_TIME)
* - This is always the highest bucket; no higher bucket yet exists
* - Increase the bucket's Available Amount
* - Increase the bucket's weight and the account's weight in that bucket
*
* - Token Withdrawals:
* - Can be from any bucket with available amount
* - Decrease the bucket's Available Amount
* - Decrease the bucket's weight and the account's weight in that bucket
*
* - Increasing the Position (Lending):
* - The lowest buckets with Available Amount are used first
* - Decreases Available Amount
* - Increases Outstanding Principal
*
* - Decreasing the Position (Being Paid-Back)
* - The highest buckets with Outstanding Principal are paid back first
* - Decreases Outstanding Principal
* - Increases Available Amount
*
*
* - Over time, this gives highest interest rates to earlier buckets, but disallows withdrawals from
* those buckets for a longer period of time.
* - Deposits in the same bucket earn the same interest rate.
* - Lenders can withdraw their funds at any time if they are not being lent (and are therefore not
* making the maximum interest).
* - The highest bucket with Outstanding Principal is always less-than-or-equal-to the lowest bucket
with Available Amount
*/
contract BucketLender is
Ownable,
OnlyMargin,
LoanOwner,
IncreaseLoanDelegator,
MarginCallDelegator,
CancelMarginCallDelegator,
ForceRecoverCollateralDelegator,
LoanOfferingParser,
LoanOfferingVerifier,
ReentrancyGuard
{
using SafeMath for uint256;
using TokenInteract for address;
// ============ Events ============
event Deposit(
address indexed beneficiary,
uint256 bucket,
uint256 amount,
uint256 weight
);
event Withdraw(
address indexed withdrawer,
uint256 bucket,
uint256 weight,
uint256 owedTokenWithdrawn,
uint256 heldTokenWithdrawn
);
event PrincipalIncreased(
uint256 principalTotal,
uint256 bucketNumber,
uint256 principalForBucket,
uint256 amount
);
event PrincipalDecreased(
uint256 principalTotal,
uint256 bucketNumber,
uint256 principalForBucket,
uint256 amount
);
event AvailableIncreased(
uint256 availableTotal,
uint256 bucketNumber,
uint256 availableForBucket,
uint256 amount
);
event AvailableDecreased(
uint256 availableTotal,
uint256 bucketNumber,
uint256 availableForBucket,
uint256 amount
);
// ============ State Variables ============
/**
* Available Amount is the amount of tokens that is available to be lent by each bucket.
* These tokens are also available to be withdrawn by the accounts that have weight in the
* bucket.
*/
// Available Amount for each bucket
mapping(uint256 => uint256) public availableForBucket;
// Total Available Amount
uint256 public availableTotal;
/**
* Outstanding Principal is the share of the margin position's principal that each bucket
* is responsible for. That is, each bucket with Outstanding Principal is owed
* (Outstanding Principal)*E^(RT) owedTokens in repayment.
*/
// Outstanding Principal for each bucket
mapping(uint256 => uint256) public principalForBucket;
// Total Outstanding Principal
uint256 public principalTotal;
/**
* Weight determines an account's proportional share of a bucket. Relative weights have no
* meaning if they are not for the same bucket. Likewise, the relative weight of two buckets has
* no meaning. However, the relative weight of two accounts within the same bucket is equal to
* the accounts' shares in the bucket and are therefore proportional to the payout that they
* should expect from withdrawing from that bucket.
*/
// Weight for each account in each bucket
mapping(uint256 => mapping(address => uint256)) public weightForBucketForAccount;
// Total Weight for each bucket
mapping(uint256 => uint256) public weightForBucket;
/**
* The critical bucket is:
* - Greater-than-or-equal-to The highest bucket with Outstanding Principal
* - Less-than-or-equal-to the lowest bucket with Available Amount
*
* It is equal to both of these values in most cases except in an edge cases where the two
* buckets are different. This value is cached to find such a bucket faster than looping through
* all possible buckets.
*/
uint256 public criticalBucket = 0;
/**
* Latest cached value for totalOwedTokenRepaidToLender.
* This number updates on the dYdX Margin base protocol whenever the position is
* partially-closed, but this contract is not notified at that time. Therefore, it is updated
* upon increasing the position or when depositing/withdrawing
*/
uint256 public cachedRepaidAmount = 0;
// True if the position was closed from force-recovering the collateral
bool public wasForceClosed = false;
// ============ Constants ============
// Unique ID of the position
bytes32 public POSITION_ID;
// Address of the token held in the position as collateral
address public HELD_TOKEN;
// Address of the token being lent
address public OWED_TOKEN;
// Time between new buckets
uint32 public BUCKET_TIME;
// Interest rate of the position
uint32 public INTEREST_RATE;
// Interest period of the position
uint32 public INTEREST_PERIOD;
// Maximum duration of the position
uint32 public MAX_DURATION;
// Margin-call time-limit of the position
uint32 public CALL_TIMELIMIT;
// (NUMERATOR/DENOMINATOR) denotes the minimum collateralization ratio of the position
uint32 public MIN_HELD_TOKEN_NUMERATOR;
uint32 public MIN_HELD_TOKEN_DENOMINATOR;
// Accounts that are permitted to margin-call positions (or cancel the margin call)
mapping(address => bool) public TRUSTED_MARGIN_CALLERS;
// Accounts that are permitted to withdraw on behalf of any address
mapping(address => bool) public TRUSTED_WITHDRAWERS;
// ============ Constructor ============
constructor(
address margin,
bytes32 positionId,
address heldToken,
address owedToken,
uint32[7] parameters,
address[] trustedMarginCallers,
address[] trustedWithdrawers
)
public
OnlyMargin(margin)
{
POSITION_ID = positionId;
HELD_TOKEN = heldToken;
OWED_TOKEN = owedToken;
require(
parameters[0] != 0,
"BucketLender#constructor: BUCKET_TIME cannot be zero"
);
BUCKET_TIME = parameters[0];
INTEREST_RATE = parameters[1];
INTEREST_PERIOD = parameters[2];
MAX_DURATION = parameters[3];
CALL_TIMELIMIT = parameters[4];
MIN_HELD_TOKEN_NUMERATOR = parameters[5];
MIN_HELD_TOKEN_DENOMINATOR = parameters[6];
// Initialize TRUSTED_MARGIN_CALLERS and TRUSTED_WITHDRAWERS
uint256 i = 0;
for (i = 0; i < trustedMarginCallers.length; i++) {
TRUSTED_MARGIN_CALLERS[trustedMarginCallers[i]] = true;
}
for (i = 0; i < trustedWithdrawers.length; i++) {
TRUSTED_WITHDRAWERS[trustedWithdrawers[i]] = true;
}
// Set maximum allowance on proxy
OWED_TOKEN.approve(
Margin(margin).getTokenProxyAddress(),
MathHelpers.maxUint256()
);
}
// ============ Modifiers ============
modifier onlyPosition(bytes32 positionId) {
require(
POSITION_ID == positionId,
"BucketLender#onlyPosition: Incorrect position"
);
_;
}
// ============ Margin-Only State-Changing Functions ============
/**
* Function a smart contract must implement to be able to consent to a loan. The loan offering
* will be generated off-chain. The "loan owner" address will own the loan-side of the resulting
* position.
*
* @param addresses Loan offering addresses
* @param values256 Loan offering uint256s
* @param values32 Loan offering uint32s
* @param positionId Unique ID of the position
* @param signature Arbitrary bytes
* @return This address to accept, a different address to ask that contract
*/
function verifyLoanOffering(
address[9] addresses,
uint256[7] values256,
uint32[4] values32,
bytes32 positionId,
bytes signature
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
Margin(DYDX_MARGIN).containsPosition(POSITION_ID),
"BucketLender#verifyLoanOffering: This contract should not open a new position"
);
MarginCommon.LoanOffering memory loanOffering = parseLoanOffering(
addresses,
values256,
values32,
signature
);
// CHECK ADDRESSES
assert(loanOffering.owedToken == OWED_TOKEN);
assert(loanOffering.heldToken == HELD_TOKEN);
assert(loanOffering.payer == address(this));
assert(loanOffering.owner == address(this));
require(
loanOffering.taker == address(0),
"BucketLender#verifyLoanOffering: loanOffering.taker is non-zero"
);
require(
loanOffering.feeRecipient == address(0),
"BucketLender#verifyLoanOffering: loanOffering.feeRecipient is non-zero"
);
require(
loanOffering.positionOwner == address(0),
"BucketLender#verifyLoanOffering: loanOffering.positionOwner is non-zero"
);
require(
loanOffering.lenderFeeToken == address(0),
"BucketLender#verifyLoanOffering: loanOffering.lenderFeeToken is non-zero"
);
require(
loanOffering.takerFeeToken == address(0),
"BucketLender#verifyLoanOffering: loanOffering.takerFeeToken is non-zero"
);
// CHECK VALUES256
require(
loanOffering.rates.maxAmount == MathHelpers.maxUint256(),
"BucketLender#verifyLoanOffering: loanOffering.maxAmount is incorrect"
);
require(
loanOffering.rates.minAmount == 0,
"BucketLender#verifyLoanOffering: loanOffering.minAmount is non-zero"
);
require(
loanOffering.rates.minHeldToken == 0,
"BucketLender#verifyLoanOffering: loanOffering.minHeldToken is non-zero"
);
require(
loanOffering.rates.lenderFee == 0,
"BucketLender#verifyLoanOffering: loanOffering.lenderFee is non-zero"
);
require(
loanOffering.rates.takerFee == 0,
"BucketLender#verifyLoanOffering: loanOffering.takerFee is non-zero"
);
require(
loanOffering.expirationTimestamp == MathHelpers.maxUint256(),
"BucketLender#verifyLoanOffering: expirationTimestamp is incorrect"
);
require(
loanOffering.salt == 0,
"BucketLender#verifyLoanOffering: loanOffering.salt is non-zero"
);
// CHECK VALUES32
require(
loanOffering.callTimeLimit == MathHelpers.maxUint32(),
"BucketLender#verifyLoanOffering: loanOffering.callTimelimit is incorrect"
);
require(
loanOffering.maxDuration == MathHelpers.maxUint32(),
"BucketLender#verifyLoanOffering: loanOffering.maxDuration is incorrect"
);
assert(loanOffering.rates.interestRate == INTEREST_RATE);
assert(loanOffering.rates.interestPeriod == INTEREST_PERIOD);
// no need to require anything about loanOffering.signature
return address(this);
}
/**
* Called by the Margin contract when anyone transfers ownership of a loan to this contract.
* This function initializes this contract and returns this address to indicate to Margin
* that it is willing to take ownership of the loan.
*
* @param from Address of the previous owner
* @param positionId Unique ID of the position
* @return This address on success, throw otherwise
*/
function receiveLoanOwnership(
address from,
bytes32 positionId
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID);
uint256 initialPrincipal = position.principal;
uint256 minHeldToken = MathHelpers.getPartialAmount(
uint256(MIN_HELD_TOKEN_NUMERATOR),
uint256(MIN_HELD_TOKEN_DENOMINATOR),
initialPrincipal
);
assert(initialPrincipal > 0);
assert(principalTotal == 0);
assert(from != address(this)); // position must be opened without lending from this position
require(
position.owedToken == OWED_TOKEN,
"BucketLender#receiveLoanOwnership: Position owedToken mismatch"
);
require(
position.heldToken == HELD_TOKEN,
"BucketLender#receiveLoanOwnership: Position heldToken mismatch"
);
require(
position.maxDuration == MAX_DURATION,
"BucketLender#receiveLoanOwnership: Position maxDuration mismatch"
);
require(
position.callTimeLimit == CALL_TIMELIMIT,
"BucketLender#receiveLoanOwnership: Position callTimeLimit mismatch"
);
require(
position.interestRate == INTEREST_RATE,
"BucketLender#receiveLoanOwnership: Position interestRate mismatch"
);
require(
position.interestPeriod == INTEREST_PERIOD,
"BucketLender#receiveLoanOwnership: Position interestPeriod mismatch"
);
require(
Margin(DYDX_MARGIN).getPositionBalance(POSITION_ID) >= minHeldToken,
"BucketLender#receiveLoanOwnership: Not enough heldToken as collateral"
);
// set relevant constants
principalForBucket[0] = initialPrincipal;
principalTotal = initialPrincipal;
weightForBucket[0] = weightForBucket[0].add(initialPrincipal);
weightForBucketForAccount[0][from] =
weightForBucketForAccount[0][from].add(initialPrincipal);
return address(this);
}
/**
* Called by Margin when additional value is added onto the position this contract
* is lending for. Balance is added to the address that loaned the additional tokens.
*
* @param payer Address that loaned the additional tokens
* @param positionId Unique ID of the position
* @param principalAdded Amount that was added to the position
* @param lentAmount Amount of owedToken lent
* @return This address to accept, a different address to ask that contract
*/
function increaseLoanOnBehalfOf(
address payer,
bytes32 positionId,
uint256 principalAdded,
uint256 lentAmount
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
Margin margin = Margin(DYDX_MARGIN);
require(
payer == address(this),
"BucketLender#increaseLoanOnBehalfOf: Other lenders cannot lend for this position"
);
require(
!margin.isPositionCalled(POSITION_ID),
"BucketLender#increaseLoanOnBehalfOf: No lending while the position is margin-called"
);
// This function is only called after the state has been updated in the base protocol;
// thus, the principal in the base protocol will equal the principal after the increase
uint256 principalAfterIncrease = margin.getPositionPrincipal(POSITION_ID);
uint256 principalBeforeIncrease = principalAfterIncrease.sub(principalAdded);
// principalTotal was the principal after the previous increase
accountForClose(principalTotal.sub(principalBeforeIncrease));
accountForIncrease(principalAdded, lentAmount);
assert(principalTotal == principalAfterIncrease);
return address(this);
}
/**
* Function a contract must implement in order to let other addresses call marginCall().
*
* @param caller Address of the caller of the marginCall function
* @param positionId Unique ID of the position
* @param depositAmount Amount of heldToken deposit that will be required to cancel the call
* @return This address to accept, a different address to ask that contract
*/
function marginCallOnBehalfOf(
address caller,
bytes32 positionId,
uint256 depositAmount
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
TRUSTED_MARGIN_CALLERS[caller],
"BucketLender#marginCallOnBehalfOf: Margin-caller must be trusted"
);
require(
depositAmount == 0, // prevents depositing from canceling the margin-call
"BucketLender#marginCallOnBehalfOf: Deposit amount must be zero"
);
return address(this);
}
/**
* Function a contract must implement in order to let other addresses call cancelMarginCall().
*
* @param canceler Address of the caller of the cancelMarginCall function
* @param positionId Unique ID of the position
* @return This address to accept, a different address to ask that contract
*/
function cancelMarginCallOnBehalfOf(
address canceler,
bytes32 positionId
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
require(
TRUSTED_MARGIN_CALLERS[canceler],
"BucketLender#cancelMarginCallOnBehalfOf: Margin-call-canceler must be trusted"
);
return address(this);
}
/**
* Function a contract must implement in order to let other addresses call
* forceRecoverCollateral().
*
* param recoverer Address of the caller of the forceRecoverCollateral() function
* @param positionId Unique ID of the position
* @param recipient Address to send the recovered tokens to
* @return This address to accept, a different address to ask that contract
*/
function forceRecoverCollateralOnBehalfOf(
address /* recoverer */,
bytes32 positionId,
address recipient
)
external
onlyMargin
nonReentrant
onlyPosition(positionId)
returns (address)
{
return forceRecoverCollateralInternal(recipient);
}
// ============ Public State-Changing Functions ============
/**
* Allow anyone to recalculate the Outstanding Principal and Available Amount for the buckets if
* part of the position has been closed since the last position increase.
*/
function rebalanceBuckets()
external
nonReentrant
{
rebalanceBucketsInternal();
}
/**
* Allows users to deposit owedToken into this contract. Allowance must be set on this contract
* for "token" in at least the amount "amount".
*
* @param beneficiary The account that will be entitled to this depoit
* @param amount The amount of owedToken to deposit
* @return The bucket number that was deposited into
*/
function deposit(
address beneficiary,
uint256 amount
)
external
nonReentrant
returns (uint256)
{
Margin margin = Margin(DYDX_MARGIN);
bytes32 positionId = POSITION_ID;
require(
beneficiary != address(0),
"BucketLender#deposit: Beneficiary cannot be the zero address"
);
require(
amount != 0,
"BucketLender#deposit: Cannot deposit zero tokens"
);
require(
!margin.isPositionClosed(positionId),
"BucketLender#deposit: Cannot deposit after the position is closed"
);
require(
!margin.isPositionCalled(positionId),
"BucketLender#deposit: Cannot deposit while the position is margin-called"
);
rebalanceBucketsInternal();
OWED_TOKEN.transferFrom(
msg.sender,
address(this),
amount
);
uint256 bucket = getCurrentBucket();
uint256 effectiveAmount = availableForBucket[bucket].add(getBucketOwedAmount(bucket));
uint256 weightToAdd = 0;
if (effectiveAmount == 0) {
weightToAdd = amount; // first deposit in bucket
} else {
weightToAdd = MathHelpers.getPartialAmount(
amount,
effectiveAmount,
weightForBucket[bucket]
);
}
require(
weightToAdd != 0,
"BucketLender#deposit: Cannot deposit for zero weight"
);
// update state
updateAvailable(bucket, amount, true);
weightForBucketForAccount[bucket][beneficiary] =
weightForBucketForAccount[bucket][beneficiary].add(weightToAdd);
weightForBucket[bucket] = weightForBucket[bucket].add(weightToAdd);
emit Deposit(
beneficiary,
bucket,
amount,
weightToAdd
);
return bucket;
}
/**
* Allows users to withdraw their lent funds. An account can withdraw its weighted share of the
* bucket.
*
* While the position is open, a bucket's share is equal to:
* Owed Token: (Available Amount) + (Outstanding Principal) * (1 + interest)
* Held Token: 0
*
* After the position is closed, a bucket's share is equal to:
* Owed Token: (Available Amount)
* Held Token: (Held Token Balance) * (Outstanding Principal) / (Total Outstanding Principal)
*
* @param buckets The bucket numbers to withdraw from
* @param maxWeights The maximum weight to withdraw from each bucket. The amount of tokens
* withdrawn will be at least this amount, but not necessarily more.
* Withdrawing the same weight from different buckets does not necessarily
* return the same amounts from those buckets. In order to withdraw as many
* tokens as possible, use the maximum uint256.
* @param onBehalfOf The address to withdraw on behalf of
* @return 1) The number of owedTokens withdrawn
* 2) The number of heldTokens withdrawn
*/
function withdraw(
uint256[] buckets,
uint256[] maxWeights,
address onBehalfOf
)
external
nonReentrant
returns (uint256, uint256)
{
require(
buckets.length == maxWeights.length,
"BucketLender#withdraw: The lengths of the input arrays must match"
);
if (onBehalfOf != msg.sender) {
require(
TRUSTED_WITHDRAWERS[msg.sender],
"BucketLender#withdraw: Only trusted withdrawers can withdraw on behalf of others"
);
}
rebalanceBucketsInternal();
// decide if some bucket is unable to be withdrawn from (is locked)
// the zero value represents no-lock
uint256 lockedBucket = 0;
if (
Margin(DYDX_MARGIN).containsPosition(POSITION_ID) &&
criticalBucket == getCurrentBucket()
) {
lockedBucket = criticalBucket;
}
uint256[2] memory results; // [0] = totalOwedToken, [1] = totalHeldToken
uint256 maxHeldToken = 0;
if (wasForceClosed) {
maxHeldToken = HELD_TOKEN.balanceOf(address(this));
}
for (uint256 i = 0; i < buckets.length; i++) {
uint256 bucket = buckets[i];
// prevent withdrawing from the current bucket if it is also the critical bucket
if ((bucket != 0) && (bucket == lockedBucket)) {
continue;
}
(uint256 owedTokenForBucket, uint256 heldTokenForBucket) = withdrawSingleBucket(
onBehalfOf,
bucket,
maxWeights[i],
maxHeldToken
);
results[0] = results[0].add(owedTokenForBucket);
results[1] = results[1].add(heldTokenForBucket);
}
// Transfer share of owedToken
OWED_TOKEN.transfer(msg.sender, results[0]);
HELD_TOKEN.transfer(msg.sender, results[1]);
return (results[0], results[1]);
}
/**
* Allows the owner to withdraw any excess tokens sent to the vault by unconventional means,
* including (but not limited-to) token airdrops. Any tokens moved to this contract by calling
* deposit() will be accounted for and will not be withdrawable by this function.
*
* @param token ERC20 token address
* @param to Address to transfer tokens to
* @return Amount of tokens withdrawn
*/
function withdrawExcessToken(
address token,
address to
)
external
onlyOwner
returns (uint256)
{
rebalanceBucketsInternal();
uint256 amount = token.balanceOf(address(this));
if (token == OWED_TOKEN) {
amount = amount.sub(availableTotal);
} else if (token == HELD_TOKEN) {
require(
!wasForceClosed,
"BucketLender#withdrawExcessToken: heldToken cannot be withdrawn if force-closed"
);
}
token.transfer(to, amount);
return amount;
}
// ============ Public Getter Functions ============
/**
* Get the current bucket number that funds will be deposited into. This is also the highest
* bucket so far.
*
* @return The highest bucket and the one that funds will be deposited into
*/
function getCurrentBucket()
public
view
returns (uint256)
{
// load variables from storage;
Margin margin = Margin(DYDX_MARGIN);
bytes32 positionId = POSITION_ID;
uint32 bucketTime = BUCKET_TIME;
assert(!margin.isPositionClosed(positionId));
// if position not created, allow deposits in the first bucket
if (!margin.containsPosition(positionId)) {
return 0;
}
// return the number of BUCKET_TIME periods elapsed since the position start, rounded-up
uint256 startTimestamp = margin.getPositionStartTimestamp(positionId);
return block.timestamp.sub(startTimestamp).div(bucketTime).add(1);
}
/**
* Gets the outstanding amount of owedToken owed to a bucket. This is the principal amount of
* the bucket multiplied by the interest accrued in the position. If the position is closed,
* then any outstanding principal will never be repaid in the form of owedToken.
*
* @param bucket The bucket number
* @return The amount of owedToken that this bucket expects to be paid-back if the posi
*/
function getBucketOwedAmount(
uint256 bucket
)
public
view
returns (uint256)
{
// if the position is completely closed, then the outstanding principal will never be repaid
if (Margin(DYDX_MARGIN).isPositionClosed(POSITION_ID)) {
return 0;
}
uint256 lentPrincipal = principalForBucket[bucket];
// the bucket has no outstanding principal
if (lentPrincipal == 0) {
return 0;
}
// get the total amount of owedToken that would be paid back at this time
uint256 owedAmount = Margin(DYDX_MARGIN).getPositionOwedAmountAtTime(
POSITION_ID,
principalTotal,
uint32(block.timestamp)
);
// return the bucket's share
return MathHelpers.getPartialAmount(
lentPrincipal,
principalTotal,
owedAmount
);
}
// ============ Internal Functions ============
function forceRecoverCollateralInternal(
address recipient
)
internal
returns (address)
{
require(
recipient == address(this),
"BucketLender#forceRecoverCollateralOnBehalfOf: Recipient must be this contract"
);
rebalanceBucketsInternal();
wasForceClosed = true;
return address(this);
}
// ============ Private Helper Functions ============
/**
* Recalculates the Outstanding Principal and Available Amount for the buckets. Only changes the
* state if part of the position has been closed since the last position increase.
*/
function rebalanceBucketsInternal()
private
{
// if force-closed, don't update the outstanding principal values; they are needed to repay
// lenders with heldToken
if (wasForceClosed) {
return;
}
uint256 marginPrincipal = Margin(DYDX_MARGIN).getPositionPrincipal(POSITION_ID);
accountForClose(principalTotal.sub(marginPrincipal));
assert(principalTotal == marginPrincipal);
}
/**
* Updates the state variables at any time. Only does anything after the position has been
* closed or partially-closed since the last time this function was called.
*
* - Increases the available amount in the highest buckets with outstanding principal
* - Decreases the principal amount in those buckets
*
* @param principalRemoved Amount of principal closed since the last update
*/
function accountForClose(
uint256 principalRemoved
)
private
{
if (principalRemoved == 0) {
return;
}
uint256 newRepaidAmount = Margin(DYDX_MARGIN).getTotalOwedTokenRepaidToLender(POSITION_ID);
assert(newRepaidAmount.sub(cachedRepaidAmount) >= principalRemoved);
uint256 principalToSub = principalRemoved;
uint256 availableToAdd = newRepaidAmount.sub(cachedRepaidAmount);
uint256 criticalBucketTemp = criticalBucket;
// loop over buckets in reverse order starting with the critical bucket
for (
uint256 bucket = criticalBucketTemp;
principalToSub > 0;
bucket--
) {
assert(bucket <= criticalBucketTemp); // no underflow on bucket
uint256 principalTemp = Math.min256(principalToSub, principalForBucket[bucket]);
if (principalTemp == 0) {
continue;
}
uint256 availableTemp = MathHelpers.getPartialAmount(
principalTemp,
principalToSub,
availableToAdd
);
updateAvailable(bucket, availableTemp, true);
updatePrincipal(bucket, principalTemp, false);
principalToSub = principalToSub.sub(principalTemp);
availableToAdd = availableToAdd.sub(availableTemp);
criticalBucketTemp = bucket;
}
assert(principalToSub == 0);
assert(availableToAdd == 0);
setCriticalBucket(criticalBucketTemp);
cachedRepaidAmount = newRepaidAmount;
}
/**
* Updates the state variables when a position is increased.
*
* - Decreases the available amount in the lowest buckets with available token
* - Increases the principal amount in those buckets
*
* @param principalAdded Amount of principal added to the position
* @param lentAmount Amount of owedToken lent
*/
function accountForIncrease(
uint256 principalAdded,
uint256 lentAmount
)
private
{
require(
lentAmount <= availableTotal,
"BucketLender#accountForIncrease: No lending not-accounted-for funds"
);
uint256 principalToAdd = principalAdded;
uint256 availableToSub = lentAmount;
uint256 criticalBucketTemp;
// loop over buckets in order starting from the critical bucket
uint256 lastBucket = getCurrentBucket();
for (
uint256 bucket = criticalBucket;
principalToAdd > 0;
bucket++
) {
assert(bucket <= lastBucket); // should never go past the last bucket
uint256 availableTemp = Math.min256(availableToSub, availableForBucket[bucket]);
if (availableTemp == 0) {
continue;
}
uint256 principalTemp = MathHelpers.getPartialAmount(
availableTemp,
availableToSub,
principalToAdd
);
updateAvailable(bucket, availableTemp, false);
updatePrincipal(bucket, principalTemp, true);
principalToAdd = principalToAdd.sub(principalTemp);
availableToSub = availableToSub.sub(availableTemp);
criticalBucketTemp = bucket;
}
assert(principalToAdd == 0);
assert(availableToSub == 0);
setCriticalBucket(criticalBucketTemp);
}
/**
* Withdraw
*
* @param onBehalfOf The account for which to withdraw for
* @param bucket The bucket number to withdraw from
* @param maxWeight The maximum weight to withdraw
* @param maxHeldToken The total amount of heldToken that has been force-recovered
* @return 1) The number of owedTokens withdrawn
* 2) The number of heldTokens withdrawn
*/
function withdrawSingleBucket(
address onBehalfOf,
uint256 bucket,
uint256 maxWeight,
uint256 maxHeldToken
)
private
returns (uint256, uint256)
{
// calculate the user's share
uint256 bucketWeight = weightForBucket[bucket];
if (bucketWeight == 0) {
return (0, 0);
}
uint256 userWeight = weightForBucketForAccount[bucket][onBehalfOf];
uint256 weightToWithdraw = Math.min256(maxWeight, userWeight);
if (weightToWithdraw == 0) {
return (0, 0);
}
// update state
weightForBucket[bucket] = weightForBucket[bucket].sub(weightToWithdraw);
weightForBucketForAccount[bucket][onBehalfOf] = userWeight.sub(weightToWithdraw);
// calculate for owedToken
uint256 owedTokenToWithdraw = withdrawOwedToken(
bucket,
weightToWithdraw,
bucketWeight
);
// calculate for heldToken
uint256 heldTokenToWithdraw = withdrawHeldToken(
bucket,
weightToWithdraw,
bucketWeight,
maxHeldToken
);
emit Withdraw(
onBehalfOf,
bucket,
weightToWithdraw,
owedTokenToWithdraw,
heldTokenToWithdraw
);
return (owedTokenToWithdraw, heldTokenToWithdraw);
}
/**
* Helper function to withdraw earned owedToken from this contract.
*
* @param bucket The bucket number to withdraw from
* @param userWeight The amount of weight the user is using to withdraw
* @param bucketWeight The total weight of the bucket
* @return The amount of owedToken being withdrawn
*/
function withdrawOwedToken(
uint256 bucket,
uint256 userWeight,
uint256 bucketWeight
)
private
returns (uint256)
{
// amount to return for the bucket
uint256 owedTokenToWithdraw = MathHelpers.getPartialAmount(
userWeight,
bucketWeight,
availableForBucket[bucket].add(getBucketOwedAmount(bucket))
);
// check that there is enough token to give back
require(
owedTokenToWithdraw <= availableForBucket[bucket],
"BucketLender#withdrawOwedToken: There must be enough available owedToken"
);
// update amounts
updateAvailable(bucket, owedTokenToWithdraw, false);
return owedTokenToWithdraw;
}
/**
* Helper function to withdraw heldToken from this contract.
*
* @param bucket The bucket number to withdraw from
* @param userWeight The amount of weight the user is using to withdraw
* @param bucketWeight The total weight of the bucket
* @param maxHeldToken The total amount of heldToken available to withdraw
* @return The amount of heldToken being withdrawn
*/
function withdrawHeldToken(
uint256 bucket,
uint256 userWeight,
uint256 bucketWeight,
uint256 maxHeldToken
)
private
returns (uint256)
{
if (maxHeldToken == 0) {
return 0;
}
// user's principal for the bucket
uint256 principalForBucketForAccount = MathHelpers.getPartialAmount(
userWeight,
bucketWeight,
principalForBucket[bucket]
);
uint256 heldTokenToWithdraw = MathHelpers.getPartialAmount(
principalForBucketForAccount,
principalTotal,
maxHeldToken
);
updatePrincipal(bucket, principalForBucketForAccount, false);
return heldTokenToWithdraw;
}
// ============ Setter Functions ============
/**
* Changes the critical bucket variable
*
* @param bucket The value to set criticalBucket to
*/
function setCriticalBucket(
uint256 bucket
)
private
{
// don't spend the gas to sstore unless we need to change the value
if (criticalBucket == bucket) {
return;
}
criticalBucket = bucket;
}
/**
* Changes the available owedToken amount. This changes both the variable to track the total
* amount as well as the variable to track a particular bucket.
*
* @param bucket The bucket number
* @param amount The amount to change the available amount by
* @param increase True if positive change, false if negative change
*/
function updateAvailable(
uint256 bucket,
uint256 amount,
bool increase
)
private
{
if (amount == 0) {
return;
}
uint256 newTotal;
uint256 newForBucket;
if (increase) {
newTotal = availableTotal.add(amount);
newForBucket = availableForBucket[bucket].add(amount);
emit AvailableIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
} else {
newTotal = availableTotal.sub(amount);
newForBucket = availableForBucket[bucket].sub(amount);
emit AvailableDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
}
availableTotal = newTotal;
availableForBucket[bucket] = newForBucket;
}
/**
* Changes the principal amount. This changes both the variable to track the total
* amount as well as the variable to track a particular bucket.
*
* @param bucket The bucket number
* @param amount The amount to change the principal amount by
* @param increase True if positive change, false if negative change
*/
function updatePrincipal(
uint256 bucket,
uint256 amount,
bool increase
)
private
{
if (amount == 0) {
return;
}
uint256 newTotal;
uint256 newForBucket;
if (increase) {
newTotal = principalTotal.add(amount);
newForBucket = principalForBucket[bucket].add(amount);
emit PrincipalIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
} else {
newTotal = principalTotal.sub(amount);
newForBucket = principalForBucket[bucket].sub(amount);
emit PrincipalDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line
}
principalTotal = newTotal;
principalForBucket[bucket] = newForBucket;
}
}
// File: contracts/margin/external/BucketLender/BucketLenderFactory.sol
/**
* @title BucketLenderFactory
* @author dYdX
*
* Contract that allows anyone to deploy a BucketLender contract by sending a transaction.
*/
contract BucketLenderFactory {
// ============ Events ============
event BucketLenderCreated(
address indexed creator,
address indexed owner,
bytes32 indexed positionId,
address at
);
// ============ State Variables ============
// Address of the Margin contract for the dYdX Margin Trading Protocol
address public DYDX_MARGIN;
// ============ Constructor ============
constructor(
address margin
)
public
{
DYDX_MARGIN = margin;
}
// ============ Public Functions ============
/**
* Deploy a new BucketLender contract to the blockchain
*
* @param positionId Unique ID of the position
* @param owner Address to which ownership of the BucketLender will be transferred
* @param heldToken Address of the token held in the position as collateral
* @param owedToken Address of the token being lent by the BucketLender
* @param parameters Values corresponding to:
*
* [0] = number of seconds per bucket
* [1] = interest rate
* [2] = interest period
* [3] = maximum loan duration
* [4] = margin-call timelimit
* [5] = numerator of minimum heldToken-per-owedToken
* [6] = denominator of minimum heldToken-per-owedToken
*
* @param marginCallers Accounts that are permitted to margin-call positions (or cancel the margin call)
* @return The address of the new BucketLender contract
*/
function createBucketLender(
bytes32 positionId,
address owner,
address heldToken,
address owedToken,
uint32[7] parameters,
address[] marginCallers,
address[] withdrawers
)
external
returns (address)
{
address newBucketLender = new BucketLender(
DYDX_MARGIN,
positionId,
heldToken,
owedToken,
parameters,
marginCallers,
withdrawers
);
BucketLender(newBucketLender).transferOwnership(owner);
emit BucketLenderCreated(
msg.sender,
owner,
positionId,
newBucketLender
);
return newBucketLender;
}
}
|
Gets the total amount of owed token lent for a loan. loanHash Unique hash of the loan offering return The total filled amount of the loan offering./
|
function getLoanFilledAmount(
bytes32 loanHash
)
external
view
returns (uint256)
{
return state.loanFills[loanHash];
}
| 1,594,077
|
./partial_match/1/0x0059A21dAc9730DE83A7d624921c66c05f102ca2/sources/PersonalCornerSale.sol
|
See {IERC165-supportsInterface}./
|
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Enumerable, AccessControl)
returns (bool)
{
return
interfaceId == _INTERFACE_ID_FEES ||
ERC721Enumerable.supportsInterface(interfaceId) ||
AccessControl.supportsInterface(interfaceId);
}
| 3,688,579
|
pragma solidity ^0.4.24;
// produced by the Solididy File Flattener (c) David Appleton 2018
// contact : dave@akomba.com
// released under Apache 2.0 licence
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);
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage role, address addr)
internal
{
role.bearer[addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage role, address addr)
internal
{
role.bearer[addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage role, address addr)
view
internal
{
require(has(role, addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage role, address addr)
view
internal
returns (bool)
{
return role.bearer[addr];
}
}
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];
}
}
contract MultiSigTransfer is Ownable {
string public name = "MultiSigTransfer";
string public symbol = "MST";
bool public complete = false;
bool public denied = false;
uint32 public quantity;
address public targetAddress;
address public requesterAddress;
/**
* @dev The multisig transfer contract ensures that no single administrator can
* KVTs without approval of another administrator
* @param _quantity The number of KVT to transfer
* @param _targetAddress The receiver of the KVTs
* @param _requesterAddress The administrator requesting the transfer
*/
constructor(
uint32 _quantity,
address _targetAddress,
address _requesterAddress
) public {
quantity = _quantity;
targetAddress = _targetAddress;
requesterAddress = _requesterAddress;
}
/**
* @dev Mark the transfer as approved / complete
*/
function approveTransfer() public onlyOwner {
require(denied == false, "cannot approve a denied transfer");
require(complete == false, "cannot approve a complete transfer");
complete = true;
}
/**
* @dev Mark the transfer as denied
*/
function denyTransfer() public onlyOwner {
require(denied == false, "cannot deny a transfer that is already denied");
denied = true;
}
/**
* @dev Determine if the transfer is pending
*/
function isPending() public view returns (bool) {
return !complete;
}
}
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
/**
* @dev reverts if addr does not have role
* @param _operator address
* @param _role the name of the role
* // reverts
*/
function checkRole(address _operator, string _role)
view
public
{
roles[_role].check(_operator);
}
/**
* @dev determine if addr has role
* @param _operator address
* @param _role the name of the role
* @return bool
*/
function hasRole(address _operator, string _role)
view
public
returns (bool)
{
return roles[_role].has(_operator);
}
/**
* @dev add a role to an address
* @param _operator address
* @param _role the name of the role
*/
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
/**
* @dev remove a role from an address
* @param _operator address
* @param _role the name of the role
*/
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param _role the name of the role
* // reverts
*/
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param _roles the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] _roles) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < _roles.length; i++) {
// if (hasRole(msg.sender, _roles[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
contract KinesisVelocityToken is BasicToken, Ownable, RBAC {
string public name = "KinesisVelocityToken";
string public symbol = "KVT";
uint8 public decimals = 0;
string public constant ADMIN_ROLE = "ADMIN";
address[] public transfers;
uint public constant INITIAL_SUPPLY = 300000;
uint public totalSupply = 0;
bool public isTransferable = false;
bool public toggleTransferablePending = false;
address public transferToggleRequester = address(0);
constructor() public {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
addRole(msg.sender, ADMIN_ROLE);
}
/**
* @dev Determine if the address is the owner of the contract
* @param _address The address to determine of ownership
*/
function isOwner(address _address) public view returns (bool) {
return owner == _address;
}
/**
* @dev Returns the list of MultiSig transfers
*/
function getTransfers() public view returns (address[]) {
return transfers;
}
/**
* @dev The KVT ERC20 token uses adminstrators to handle transfering to the crowdsale, vesting and pre-purchasers
*/
function isAdmin(address _address) public view returns (bool) {
return hasRole(_address, ADMIN_ROLE);
}
/**
* @dev Set an administrator as the owner, using Open Zepplin RBAC implementation
*/
function setAdmin(address _newAdmin) public onlyOwner {
return addRole(_newAdmin, ADMIN_ROLE);
}
/**
* @dev Remove an administrator as the owner, using Open Zepplin RBAC implementation
*/
function removeAdmin(address _oldAdmin) public onlyOwner {
return removeRole(_oldAdmin, ADMIN_ROLE);
}
/**
* @dev As an administrator, request the token is made transferable
* @param _toState The transfer state being requested
*/
function setTransferable(bool _toState) public onlyRole(ADMIN_ROLE) {
require(isTransferable != _toState, "to init a transfer toggle, the toState must change");
toggleTransferablePending = true;
transferToggleRequester = msg.sender;
}
/**
* @dev As an administrator who did not make the request, approve the transferable state change
*/
function approveTransferableToggle() public onlyRole(ADMIN_ROLE) {
require(toggleTransferablePending == true, "transfer toggle not in pending state");
require(transferToggleRequester != msg.sender, "the requester cannot approve the transfer toggle");
isTransferable = !isTransferable;
toggleTransferablePending = false;
transferToggleRequester = address(0);
}
/**
* @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, address _from, uint256 _value) private returns (bool) {
require(_value <= balances[_from], "the balance in the from address is smaller than the tx value");
// SafeMath.sub will throw if there is not enough balance.
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Public transfer token function. This wrapper ensures the token is transferable
* @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), "cannot transfer to the zero address");
/* We allow holders to return their Tokens to the contract owner at any point */
if (_to != owner && msg.sender != crowdsale) {
require(isTransferable == true, "kvt is not yet transferable");
}
/* Transfers from the owner address must use the administrative transfer */
require(msg.sender != owner, "the owner of the kvt contract cannot transfer");
return _transfer(_to, msg.sender, _value);
}
/**
* @dev Request an administrative transfer. This does not move tokens
* @param _to The address to transfer to.
* @param _quantity The amount to be transferred.
*/
function adminTransfer(address _to, uint32 _quantity) public onlyRole(ADMIN_ROLE) {
address newTransfer = new MultiSigTransfer(_quantity, _to, msg.sender);
transfers.push(newTransfer);
}
/**
* @dev Approve an administrative transfer. This moves the tokens if the requester
* is an admin, but not the same admin as the one who made the request
* @param _approvedTransfer The contract address of the multisignature transfer.
*/
function approveTransfer(address _approvedTransfer) public onlyRole(ADMIN_ROLE) returns (bool) {
MultiSigTransfer transferToApprove = MultiSigTransfer(_approvedTransfer);
uint32 transferQuantity = transferToApprove.quantity();
address deliveryAddress = transferToApprove.targetAddress();
address requesterAddress = transferToApprove.requesterAddress();
require(msg.sender != requesterAddress, "a requester cannot approve an admin transfer");
transferToApprove.approveTransfer();
return _transfer(deliveryAddress, owner, transferQuantity);
}
/**
* @dev Deny an administrative transfer. This ensures it cannot be approved.
* @param _approvedTransfer The contract address of the multisignature transfer.
*/
function denyTransfer(address _approvedTransfer) public onlyRole(ADMIN_ROLE) returns (bool) {
MultiSigTransfer transferToApprove = MultiSigTransfer(_approvedTransfer);
transferToApprove.denyTransfer();
}
address public crowdsale = address(0);
/**
* @dev Any admin can set the current crowdsale address, to allows transfers
* from the crowdsale to the purchaser
*/
function setCrowdsaleAddress(address _crowdsaleAddress) public onlyRole(ADMIN_ROLE) {
crowdsale = _crowdsaleAddress;
}
}
|
Deny an administrative transfer. This ensures it cannot be approved. _approvedTransfer The contract address of the multisignature transfer./
|
function denyTransfer(address _approvedTransfer) public onlyRole(ADMIN_ROLE) returns (bool) {
MultiSigTransfer transferToApprove = MultiSigTransfer(_approvedTransfer);
transferToApprove.denyTransfer();
}
address public crowdsale = address(0);
| 1,027,457
|
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "../VotePowerQueue.sol";
import "./UnstakeQueue.sol";
///
/// @title eSpace PoSPool
///
contract ESpacePoSPool is Ownable, Initializable {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
using VotePowerQueue for VotePowerQueue.InOutQueue;
using UnstakeQueue for UnstakeQueue.Queue;
uint256 private constant RATIO_BASE = 10000;
uint256 private constant ONE_DAY_BLOCK_COUNT = 3600 * 24;
uint256 private CFX_COUNT_OF_ONE_VOTE = 1000;
uint256 private CFX_VALUE_OF_ONE_VOTE = 1000 ether;
// ======================== Pool config =========================
// wheter this poolContract registed in PoS
bool public birdgeAddrSetted;
address private _bridgeAddress;
// ratio shared by user: 1-10000
uint256 public poolUserShareRatio = 9600;
// lock period: 7 days + half hour
uint256 public _poolLockPeriod = ONE_DAY_BLOCK_COUNT * 7 + 1800;
string public poolName; // = "eSpacePool";
uint256 private _poolAPY = 0;
// ======================== Contract states =========================
// global pool accumulative reward for each cfx
uint256 public accRewardPerCfx; // start from 0
PoolSummary private _poolSummary;
mapping(address => UserSummary) private userSummaries;
mapping(address => VotePowerQueue.InOutQueue) private userInqueues;
mapping(address => VotePowerQueue.InOutQueue) private userOutqueues;
PoolShot internal lastPoolShot;
mapping(address => UserShot) internal lastUserShots;
EnumerableSet.AddressSet private stakers;
// Unstake votes queue
UnstakeQueue.Queue private unstakeQueue;
// Currently withdrawable CFX
uint256 public withdrawableCfx;
// Votes need to cross from eSpace to Core
uint256 public crossingVotes;
// ======================== Struct definitions =========================
struct PoolSummary {
uint256 available;
uint256 interest; // PoS pool current interest
uint256 totalInterest; // total historical interest of whole pools
}
/// @title UserSummary
/// @custom:field votes User's total votes
/// @custom:field available User's avaliable votes
/// @custom:field locked
/// @custom:field unlocked
/// @custom:field claimedInterest
/// @custom:field currentInterest
struct UserSummary {
uint256 votes; // Total votes in PoS system, including locking, locked, unlocking, unlocked
uint256 available; // locking + locked
uint256 locked;
uint256 unlocked;
uint256 claimedInterest; // total historical claimed interest
uint256 currentInterest; // current claimable interest
}
struct PoolShot {
uint256 available;
uint256 balance;
uint256 blockNumber;
}
struct UserShot {
uint256 available;
uint256 accRewardPerCfx;
uint256 blockNumber;
}
// ======================== Modifiers =========================
modifier onlyRegisted() {
require(birdgeAddrSetted, "Pool is not setted");
_;
}
modifier onlyBridge() {
require(msg.sender == _bridgeAddress, "Only bridge is allowed");
_;
}
// ======================== Helpers =========================
function _selfBalance() internal view virtual returns (uint256) {
return address(this).balance;
}
function _blockNumber() internal view virtual returns (uint256) {
return block.number;
}
function _userShareRatio() public pure returns (uint256) {
return RATIO_BASE;
}
function _calUserShare(uint256 reward, address _stakerAddress) private pure returns (uint256) {
return reward.mul(_userShareRatio()).div(RATIO_BASE);
}
// used to update lastPoolShot after _poolSummary.available changed
function _updatePoolShot() private {
lastPoolShot.available = _poolSummary.available;
lastPoolShot.balance = _selfBalance();
lastPoolShot.blockNumber = _blockNumber();
}
// used to update lastUserShot after userSummary.available and accRewardPerCfx changed
function _updateUserShot(address _user) private {
lastUserShots[_user].available = userSummaries[_user].available;
lastUserShots[_user].accRewardPerCfx = accRewardPerCfx;
lastUserShots[_user].blockNumber = _blockNumber();
}
// used to update accRewardPerCfx after _poolSummary.available changed or user claimed interest
// depend on: lastPoolShot.available and lastPoolShot.balance
function _updateAccRewardPerCfx() private {
uint256 reward = _selfBalance() - lastPoolShot.balance;
if (reward == 0 || lastPoolShot.available == 0) return;
// update global accRewardPerCfx
uint256 cfxCount = lastPoolShot.available.mul(CFX_COUNT_OF_ONE_VOTE);
accRewardPerCfx = accRewardPerCfx.add(reward.div(cfxCount));
// update pool interest info
_poolSummary.totalInterest = _poolSummary.totalInterest.add(reward);
}
// depend on: accRewardPerCfx and lastUserShot
function _updateUserInterest(address _user) private {
UserShot memory uShot = lastUserShots[_user];
if (uShot.available == 0) return;
uint256 latestInterest = accRewardPerCfx.sub(uShot.accRewardPerCfx).mul(uShot.available.mul(CFX_COUNT_OF_ONE_VOTE));
uint256 _userInterest = _calUserShare(latestInterest, _user);
userSummaries[_user].currentInterest = userSummaries[_user].currentInterest.add(_userInterest);
_poolSummary.interest = _poolSummary.interest.add(latestInterest.sub(_userInterest));
}
// ======================== Events =========================
event IncreasePoSStake(address indexed user, uint256 votePower);
event DecreasePoSStake(address indexed user, uint256 votePower);
event WithdrawStake(address indexed user, uint256 votePower);
event ClaimInterest(address indexed user, uint256 amount);
event RatioChanged(uint256 ratio);
// ======================== Init methods =========================
// call this method when depoly the 1967 proxy contract
function initialize() public initializer {
CFX_COUNT_OF_ONE_VOTE = 1000;
CFX_VALUE_OF_ONE_VOTE = 1000 ether;
_poolLockPeriod = ONE_DAY_BLOCK_COUNT * 7 + 3600;
poolUserShareRatio = 9600;
}
// ======================== Contract methods =========================
///
/// @notice Increase PoS vote power
/// @param votePower The number of vote power to increase
///
function increaseStake(uint64 votePower) public virtual payable onlyRegisted {
require(votePower > 0, "Minimal votePower is 1");
require(msg.value == votePower * CFX_VALUE_OF_ONE_VOTE, "msg.value should be votePower * 1000 ether");
// transfer to bridge address
address payable receiver = payable(_bridgeAddress);
receiver.transfer(msg.value);
crossingVotes += votePower;
emit IncreasePoSStake(msg.sender, votePower);
_updateAccRewardPerCfx();
// update user interest
_updateUserInterest(msg.sender);
// put stake info in queue
userInqueues[msg.sender].enqueue(VotePowerQueue.QueueNode(votePower, _blockNumber() + _poolLockPeriod));
userSummaries[msg.sender].locked += userInqueues[msg.sender].collectEndedVotes();
userSummaries[msg.sender].votes += votePower;
userSummaries[msg.sender].available += votePower;
_updateUserShot(msg.sender);
//
_poolSummary.available += votePower;
_updatePoolShot();
stakers.add(msg.sender);
}
///
/// @notice Decrease PoS vote power
/// @param votePower The number of vote power to decrease
///
function decreaseStake(uint64 votePower) public virtual onlyRegisted {
userSummaries[msg.sender].locked += userInqueues[msg.sender].collectEndedVotes();
require(userSummaries[msg.sender].locked >= votePower, "Locked is not enough");
// record the decrease request
unstakeQueue.enqueue(UnstakeQueue.Node(votePower));
emit DecreasePoSStake(msg.sender, votePower);
_updateAccRewardPerCfx();
// update user interest
_updateUserInterest(msg.sender);
//
userOutqueues[msg.sender].enqueue(VotePowerQueue.QueueNode(votePower, _blockNumber() + _poolLockPeriod));
userSummaries[msg.sender].unlocked += userOutqueues[msg.sender].collectEndedVotes();
userSummaries[msg.sender].available -= votePower;
userSummaries[msg.sender].locked -= votePower;
_updateUserShot(msg.sender);
//
_poolSummary.available -= votePower;
_updatePoolShot();
}
///
/// @notice Withdraw PoS vote power
/// @param votePower The number of vote power to withdraw
///
function withdrawStake(uint64 votePower) public onlyRegisted {
userSummaries[msg.sender].unlocked += userOutqueues[msg.sender].collectEndedVotes();
require(userSummaries[msg.sender].unlocked >= votePower, "Unlocked is not enough");
uint256 _withdrawAmount = votePower * CFX_VALUE_OF_ONE_VOTE;
require(withdrawableCfx >= _withdrawAmount, "Withdrawable CFX is not enough");
// update amount of withdrawable CFX
withdrawableCfx -= _withdrawAmount;
//
userSummaries[msg.sender].unlocked -= votePower;
userSummaries[msg.sender].votes -= votePower;
address payable receiver = payable(msg.sender);
receiver.transfer(_withdrawAmount);
emit WithdrawStake(msg.sender, votePower);
_updatePoolShot();
if (userSummaries[msg.sender].votes == 0) {
stakers.remove(msg.sender);
}
}
///
/// @notice User's interest from participate PoS
/// @param _address The address of user to query
/// @return CFX interest in Drip
///
function userInterest(address _address) public view returns (uint256) {
uint256 _interest = userSummaries[_address].currentInterest;
uint256 _latestAccRewardPerCfx = accRewardPerCfx;
// add latest profit
uint256 _latestReward = _selfBalance() - lastPoolShot.balance;
UserShot memory uShot = lastUserShots[_address];
if (_latestReward > 0) {
uint256 _deltaAcc = _latestReward.div(lastPoolShot.available.mul(CFX_COUNT_OF_ONE_VOTE));
_latestAccRewardPerCfx = _latestAccRewardPerCfx.add(_deltaAcc);
}
if (uShot.available > 0) {
uint256 _latestInterest = _latestAccRewardPerCfx.sub(uShot.accRewardPerCfx).mul(uShot.available.mul(CFX_COUNT_OF_ONE_VOTE));
_interest = _interest.add(_calUserShare(_latestInterest, _address));
}
return _interest;
}
///
/// @notice Claim specific amount user interest
/// @param amount The amount of interest to claim
///
function claimInterest(uint amount) public onlyRegisted {
uint claimableInterest = userInterest(msg.sender);
require(claimableInterest >= amount, "Interest not enough");
_updateAccRewardPerCfx();
_updateUserInterest(msg.sender);
//
userSummaries[msg.sender].claimedInterest = userSummaries[msg.sender].claimedInterest.add(amount);
userSummaries[msg.sender].currentInterest = userSummaries[msg.sender].currentInterest.sub(amount);
// update userShot's accRewardPerCfx
_updateUserShot(msg.sender);
// send interest to user
address payable receiver = payable(msg.sender);
receiver.transfer(amount);
emit ClaimInterest(msg.sender, amount);
// update blockNumber and balance
_updatePoolShot();
}
///
/// @notice Claim one user's all interest
///
function claimAllInterest() public onlyRegisted {
uint claimableInterest = userInterest(msg.sender);
require(claimableInterest > 0, "No claimable interest");
claimInterest(claimableInterest);
}
///
/// @notice Get user's pool summary
/// @param _user The address of user to query
/// @return User's summary
///
function userSummary(address _user) public view returns (UserSummary memory) {
UserSummary memory summary = userSummaries[_user];
summary.locked += userInqueues[_user].sumEndedVotes();
summary.unlocked += userOutqueues[_user].sumEndedVotes();
return summary;
}
function poolSummary() public view returns (PoolSummary memory) {
PoolSummary memory summary = _poolSummary;
uint256 _latestReward = _selfBalance().sub(lastPoolShot.balance);
summary.totalInterest = summary.totalInterest.add(_latestReward);
return summary;
}
function poolAPY() public view returns (uint256) {
return _poolAPY;
}
function userInQueue(address account) public view returns (VotePowerQueue.QueueNode[] memory) {
return userInqueues[account].queueItems();
}
function userOutQueue(address account) public view returns (VotePowerQueue.QueueNode[] memory) {
return userOutqueues[account].queueItems();
}
function userInQueue(address account, uint64 offset, uint64 limit) public view returns (VotePowerQueue.QueueNode[] memory) {
return userInqueues[account].queueItems(offset, limit);
}
function userOutQueue(address account, uint64 offset, uint64 limit) public view returns (VotePowerQueue.QueueNode[] memory) {
return userOutqueues[account].queueItems(offset, limit);
}
function stakerNumber() public view returns (uint) {
return stakers.length();
}
function stakerAddress(uint256 i) public view returns (address) {
return stakers.at(i);
}
function unstakeLen() public view returns (uint256) {
return unstakeQueue.end - unstakeQueue.start;
}
function firstUnstakeVotes() public view returns (uint256) {
if (unstakeQueue.end == unstakeQueue.start) {
return 0;
}
return unstakeQueue.items[unstakeQueue.start].votes;
}
// ======================== admin methods =====================
///
/// @notice Enable admin to set the user share ratio
/// @dev The ratio base is 10000, only admin can do this
/// @param ratio The interest user share ratio (1-10000), default is 9000
///
function setPoolUserShareRatio(uint64 ratio) public onlyOwner {
require(ratio > 0 && ratio <= RATIO_BASE, "ratio should be 1-10000");
poolUserShareRatio = ratio;
emit RatioChanged(ratio);
}
///
/// @notice Enable admin to set the lock and unlock period
/// @dev Only admin can do this
/// @param period The lock period in block number, default is seven day's block count
///
function setLockPeriod(uint64 period) public onlyOwner {
_poolLockPeriod = period;
}
/// @param count Vote cfx count, unit is cfx
function setCfxCountOfOneVote(uint256 count) public onlyOwner {
CFX_COUNT_OF_ONE_VOTE = count;
CFX_VALUE_OF_ONE_VOTE = count * 1 ether;
}
function setBridge(address bridgeAddress) public onlyOwner {
_bridgeAddress = bridgeAddress;
birdgeAddrSetted = true;
}
function setPoolName(string memory name) public onlyOwner {
poolName = name;
}
function _retireUserStake(address _addr, uint64 endBlockNumber) public onlyOwner {
uint256 votePower = userSummaries[_addr].available;
if (votePower == 0) return;
_updateUserInterest(_addr);
userSummaries[_addr].available = 0;
userSummaries[_addr].locked = 0;
// clear user inqueue
userInqueues[_addr].clear();
userOutqueues[_addr].enqueue(VotePowerQueue.QueueNode(votePower, endBlockNumber));
_updateUserShot(_addr);
_poolSummary.available -= votePower;
}
// When pool node is force retired, use this method to make all user's available stake to unlocking
function _retireUserStakes(uint256 offset, uint256 limit, uint64 endBlockNumber) public onlyOwner {
uint256 len = stakers.length();
if (len == 0) return;
_updateAccRewardPerCfx();
uint256 end = offset + limit;
if (end > len) {
end = len;
}
for (uint256 i = offset; i < end; i++) {
_retireUserStake(stakers.at(i), endBlockNumber);
}
_updatePoolShot();
}
// ======================== bridge methods =====================
function setPoolAPY(uint256 apy) public onlyBridge {
_poolAPY = apy;
}
function handleUnlockedIncrease(uint256 votePower) public payable onlyBridge {
require(msg.value == votePower * CFX_VALUE_OF_ONE_VOTE, "msg.value should be votePower * 1000 ether");
withdrawableCfx += msg.value;
_updatePoolShot();
}
function handleCrossingVotes(uint256 votePower) public onlyBridge {
require(crossingVotes >= votePower, "crossingVotes should be greater than votePower");
crossingVotes -= votePower;
}
function handleUnstakeTask() public onlyBridge returns (uint256) {
UnstakeQueue.Node memory node = unstakeQueue.dequeue();
return node.votes;
}
// receive interest
function receiveInterest() public payable onlyBridge {}
fallback() external payable {}
}
|
Enable admin to set the user share ratio The ratio base is 10000, only admin can do this ratio The interest user share ratio (1-10000), default is 9000
|
function setPoolUserShareRatio(uint64 ratio) public onlyOwner {
require(ratio > 0 && ratio <= RATIO_BASE, "ratio should be 1-10000");
poolUserShareRatio = ratio;
emit RatioChanged(ratio);
}
| 12,963,318
|
pragma solidity ^0.4.23;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/IdentityProtocol.sol";
import "../contracts/identity/Identity.sol";
import "./helpers/ThrowProxy.sol";
contract TestIdentity {
Identity identity = new Identity(address(this),"QmeHy1gq8QHVchad7ndEsdAnaBWGu1CAVmYCb4aTJW2Pwa");
ThrowProxy throwProxy = new ThrowProxy(address(identity));
Identity throwableIdentity = Identity(address(throwProxy));
SomeContract someInstance = new SomeContract();
bytes msgData;
function () public {
msgData = msg.data;
}
// Testing setFinancialData() function
function testOwnerCanChangeProfile() public {
bool result = identity.setFinancialData("QmeHy1gq8QHVchad7ndEsdAnaBWGu1CAVmYCb4aTJW2879");
Assert.equal(result, true, "The profile must be changed");
}
// Testing setFinancialData() function
function testOnlyOwnerCanChangeProfile() public {
address(throwableIdentity).call(abi.encodeWithSignature("setFinancialData(bytes)","QmeHy1gq8QHVchad7ndEsdAnaBWGu1CAVmYCb4aTJW2Pwa"));
throwProxy.shouldThrow();
}
// Testing forward() function
function testIdentityCanForwardTransactionByOwner() public {
bool result = identity.forward(address(someInstance), 0, abi.encodeWithSignature("someFunction()"));
Assert.equal(result, true, "The transaction must be executed");
}
// Testing forward() function
function testOnlyOwnerCanUseIdentityAsProxy() public {
address(throwableIdentity).call(abi.encodeWithSignature("forward(address,uint256,bytes)",address(someInstance), 0, abi.encodeWithSignature("someFunction()")));
throwProxy.shouldThrow();
}
}
contract SomeContract {
function someFunction()
public
pure
returns(bool)
{
return true;
}
}
|
Testing setFinancialData() function
|
function testOwnerCanChangeProfile() public {
bool result = identity.setFinancialData("QmeHy1gq8QHVchad7ndEsdAnaBWGu1CAVmYCb4aTJW2879");
Assert.equal(result, true, "The profile must be changed");
}
| 7,321,751
|
// Project: BUZcoin.io (original)
// v11, 2018-04-17
// This code is the property of CryptoB2B.io
// Copying in whole or in part is prohibited.
// Authors: Ivan Fedorov and Dmitry Borodin
// Do you want the same TokenSale platform? www.cryptob2b.io
// *.sol in 1 file - https://cryptob2b.io/solidity/buzcoin/
pragma solidity ^0.4.21;
contract IFinancialStrategy{
enum State { Active, Refunding, Closed }
State public state = State.Active;
event Deposited(address indexed beneficiary, uint256 weiAmount);
event Receive(address indexed beneficiary, uint256 weiAmount);
function deposit(address _beneficiary) external payable;
function setup(address _beneficiary, uint256 _arg1, uint256 _arg2, uint8 _state) external;
function calc(uint256 _allValue) external;
function getBeneficiaryCash(address _beneficiary) external;
function getPartnerCash(uint8 _user, bool _isAdmin, address _msgsender, bool _calc, uint256 _weiTotalRaised) external;
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
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) {
uint256 c = a / b;
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;
}
function minus(uint256 a, uint256 b) internal pure returns (uint256) {
if (b>=a) return 0;
return a - b;
}
}
contract MigrationAgent
{
function migrateFrom(address _from, uint256 _value) public;
}
contract IToken{
function setUnpausedWallet(address _wallet, bool mode) public;
function mint(address _to, uint256 _amount) public returns (bool);
function totalSupply() public view returns (uint256);
function setPause(bool mode) public;
function setMigrationAgent(address _migrationAgent) public;
function migrateAll(address[] _holders) public;
function burn(address _beneficiary, uint256 _value) public;
function freezedTokenOf(address _beneficiary) public view returns (uint256 amount);
function defrostDate(address _beneficiary) public view returns (uint256 Date);
function freezeTokens(address _beneficiary, uint256 _amount, uint256 _when) public;
}
contract ERC223ReceivingContract {
function tokenFallback(address _from, uint _value, bytes memory _data) public;
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract 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;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
/**
* @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 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;
}
}
contract ICreator{
function createToken() external returns (IToken);
function createFinancialStrategy() external returns(IFinancialStrategy);
}
contract BuzFinancialStrategy is IFinancialStrategy, Ownable{
using SafeMath for uint256;
// Partner 0 Partner 1 Partner 2
uint256[3] public percent = [20, 2, 3 ];
uint256[3] public cap = [200 ether, 1800 ether, 9999999 ether]; // QUINTILLIONS
uint256[3] public debt1 = [0,0,0];
uint256[3] public debt2 = [0,0,0];
uint256[3] public total = [0,0,0]; // QUINTILLIONS
uint256[3] public took = [0,0,0];
uint256[3] public ready = [0,0,0];
address[3] public wallets= [
0x356608b672fdB01C5077d1A2cb6a7b38fDdcd8A5,
0xf1F3D1Dc1E5cEA08f127cad3B7Dbd29b299c88C8,
0x55ecFbD0111ab365b6De98A01E9305EfD4a78FAA
];
uint256 public benTook=0;
uint256 public benReady=0;
uint256 public newCash=0;
uint256 public cashHistory=0;
uint256 public prcSum=0;
address public benWallet=0;
function BuzFinancialStrategy() public {
initialize();
}
function balance() external view returns(uint256){
return address(this).balance;
}
function initialize() internal {
for (uint8 i=0; i<percent.length; i++ ) prcSum+=percent[i];
}
function deposit(address _beneficiary) external onlyOwner payable {
require(state == State.Active);
newCash = newCash.add(msg.value);
cashHistory += msg.value;
emit Deposited(_beneficiary,msg.value);
}
// 0 - destruct
// 1 - close
// 2 - restart
// 3 - refund
// 4 - test
// 5 - update Exchange
function setup(address _beneficiary, uint256 _arg1, uint256 _arg2, uint8 _state) external onlyOwner {
if (_state == 0) {
// call from Crowdsale.distructVault(true) for exit
// arg1 - nothing
// arg2 - nothing
selfdestruct(_beneficiary);
}
else if (_state == 1 || _state == 3) {
// Call from Crowdsale.finalization()
// [1] - successfull round (goalReach)
// [3] - failed round (not enough money)
// arg1 = weiTotalRaised();
// arg2 = nothing;
require(state == State.Active);
//internalCalc(_arg1);
state = State.Closed;
benWallet=_beneficiary;
}
else if (_state == 2) {
// Call from Crowdsale.initialization()
// arg1 = weiTotalRaised();
// arg2 = nothing;
require(state == State.Closed);
state = State.Active;
benWallet=_beneficiary;
}
else if (_state == 4) {
// call from Crowdsale.distructVault(false) for test
// arg1 = nothing;
// arg2 = nothing;
benWallet=_beneficiary;
}
else if (_state == 5) {
// arg1 = old ETH/USD (exchange)
// arg2 = new ETH/USD (_ETHUSD)
for (uint8 user=0; user<cap.length; user++) cap[user]=cap[user].mul(_arg1).div(_arg2);
benWallet=_beneficiary;
}
}
function calc(uint256 _allValue) external onlyOwner {
internalCalc(_allValue);
}
function internalCalc(uint256 _allValue) internal {
uint256 free=newCash+benReady;
uint256 common1=0;
uint256 common2=0;
uint256 spent=0;
uint256 plan=0;
uint8 user=0;
if (free==0) return;
for (user=0; user<percent.length; user++) {
plan=_allValue*percent[user]/100;
if (total[user]>=plan || total[user]>=cap[user]) {
debt1[user]=0;
debt2[user]=0;
continue;
}
debt1[user]=plan.minus(total[user]);
if (debt1[user]+total[user] > cap[user]) debt1[user]=cap[user].minus(total[user]);
common1+=debt1[user];
plan=free.mul(percent[user]).div(prcSum);
debt2[user]=plan;
if (debt2[user]+total[user] > cap[user]) debt2[user]=cap[user].minus(total[user]);
common2+=debt2[user];
}
if (common1>0 && common1<=free) {
for (user=0; user<percent.length; user++) {
if (debt1[user]==0) continue;
plan=free.mul(debt1[user]).div(common1);
if (plan>debt1[user]) plan=debt1[user];
ready[user]+=plan;
total[user]+=plan;
spent+=plan;
}
}
if (common2>0 && common1>free) {
for (user=0; user<percent.length; user++) {
if (debt2[user]==0) continue;
plan=free.mul(debt2[user]).div(common2);
if (plan>debt1[user]) plan=debt1[user]; // debt1, not 2
ready[user]+=plan;
total[user]+=plan;
spent+=plan;
}
}
if (spent>newCash+benReady) benReady=0;
else benReady=newCash.add(benReady).minus(spent);
newCash=0;
}
// Call from Crowdsale:
function getBeneficiaryCash(address _beneficiary) external onlyOwner {
uint256 move=benReady;
benWallet=_beneficiary;
if (move == 0) return;
emit Receive(_beneficiary, move);
benReady = 0;
benTook += move;
_beneficiary.transfer(move);
}
// Call from Crowdsale:
function getPartnerCash(uint8 _user, bool _isAdmin, address _msgsender, bool _calc, uint256 _weiTotalRaised) external onlyOwner {
require(_user<percent.length && _user<wallets.length);
if (!_isAdmin) {
for (uint8 i=0; i<wallets.length; i++) {
if (wallets[i]==_msgsender) break;
}
if (i>=wallets.length) {
return;
}
}
if (_calc) internalCalc(_weiTotalRaised);
uint256 move=ready[_user];
if (move==0) return;
emit Receive(wallets[_user], move);
ready[_user]=0;
took[_user]+=move;
wallets[_user].transfer(move);
}
}
contract ICrowdsale {
// 0 1 2 3 4 5 6
enum Roles {beneficiary, accountant, manager, observer, bounty, company, team}
address[8] public wallets;
}
contract Crowdsale is ICrowdsale{
// (A1)
// The main contract for the sale and management of rounds.
// 0000000000000000000000000000000000000000000000000000000000000000
uint256 constant USER_UNPAUSE_TOKEN_TIMEOUT = 90 days;
uint256 constant FORCED_REFUND_TIMEOUT1 = 300 days;
uint256 constant FORCED_REFUND_TIMEOUT2 = 400 days;
uint256 constant ROUND_PROLONGATE = 90 days;
uint256 constant BURN_TOKENS_TIME = 60 days;
using SafeMath for uint256;
enum TokenSaleType {round1, round2}
TokenSaleType public TokenSale = TokenSaleType.round1;
ICreator public creator;
bool isBegin=false;
IToken public token;
//Allocation public allocation;
IFinancialStrategy public financialStrategy;
bool public isFinalized;
bool public isInitialized;
bool public isPausedCrowdsale;
bool public chargeBonuses;
bool public canFirstMint=true;
struct Bonus {
uint256 value;
uint256 procent;
uint256 freezeTime;
}
struct Profit {
uint256 percent;
uint256 duration;
}
struct Freezed {
uint256 value;
uint256 dateTo;
}
Bonus[] public bonuses;
Profit[] public profits;
uint256 public startTime= 1524009600;
uint256 public endTime = 1526601599;
uint256 public renewal;
// How many tokens (excluding the bonus) are transferred to the investor in exchange for 1 ETH
// **THOUSANDS** 10^18 for human, *10**18 for Solidity, 1e18 for MyEtherWallet (MEW).
// Example: if 1ETH = 40.5 Token ==> use 40500 finney
uint256 public rate = 5000 ether; // $0.1 (ETH/USD=$500)
// ETH/USD rate in US$
// **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: ETH/USD=$1000 ==> use 1000*10**18 (Solidity) or 1000 ether or 1000e18 (MEW)
uint256 public exchange = 500 ether;
// If the round does not attain this value before the closing date, the round is recognized as a
// failure and investors take the money back (the founders will not interfere in any way).
// **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: softcap=15ETH ==> use 15*10**18 (Solidity) or 15e18 (MEW)
uint256 public softCap = 0;
// The maximum possible amount of income
// **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: hardcap=123.45ETH ==> use 123450*10**15 (Solidity) or 12345e15 (MEW)
uint256 public hardCap = 62000 ether; // $31M (ETH/USD=$500)
// If the last payment is slightly higher than the hardcap, then the usual contracts do
// not accept it, because it goes beyond the hardcap. However it is more reasonable to accept the
// last payment, very slightly raising the hardcap. The value indicates by how many ETH the
// last payment can exceed the hardcap to allow it to be paid. Immediately after this payment, the
// round closes. The funders should write here a small number, not more than 1% of the CAP.
// Can be equal to zero, to cancel.
// **QUINTILLIONS** 10^18 / *10**18 / 1e18
uint256 public overLimit = 20 ether;
// The minimum possible payment from an investor in ETH. Payments below this value will be rejected.
// **QUINTILLIONS** 10^18 / *10**18 / 1e18. Example: minPay=0.1ETH ==> use 100*10**15 (Solidity) or 100e15 (MEW)
uint256 public minPay = 20 finney;
uint256 public maxAllProfit = 38; // max time bonus=30%, max value bonus=8%, maxAll=38%
uint256 public ethWeiRaised;
uint256 public nonEthWeiRaised;
uint256 public weiRound1;
uint256 public tokenReserved;
uint256 public totalSaledToken;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Finalized();
event Initialized();
function Crowdsale(ICreator _creator) public
{
creator=_creator;
// Initially, all next 7+ roles/wallets are given to the Manager. The Manager is an employee of the company
// with knowledge of IT, who publishes the contract and sets it up. However, money and tokens require
// a Beneficiary and other roles (Accountant, Team, etc.). The Manager will not have the right
// to receive them. To enable this, the Manager must either enter specific wallets here, or perform
// this via method changeWallet. In the finalization methods it is written which wallet and
// what percentage of tokens are received.
wallets = [
// Beneficiary
// Receives all the money (when finalizing Round1 & Round2)
0x55d36E21b7ee114dA69a9d79D37a894d80d8Ed09,
// Accountant
// Receives all the tokens for non-ETH investors (when finalizing Round1 & Round2)
0xaebC3c0a722A30981F8d19BDA33eFA51a89E4C6C,
// Manager
// All rights except the rights to receive tokens or money. Has the right to change any other
// wallets (Beneficiary, Accountant, ...), but only if the round has not started. Once the
// round is initialized, the Manager has lost all rights to change the wallets.
// If the TokenSale is conducted by one person, then nothing needs to be changed. Permit all 7 roles
// point to a single wallet.
msg.sender,
// Observer
// Has only the right to call paymentsInOtherCurrency (please read the document)
0x8a91aC199440Da0B45B2E278f3fE616b1bCcC494,
// Bounty - 2% tokens
0x1f85AE08D0e1313C95D6D63e9A95c4eEeaC9D9a3,
// Company - 10% tokens
0x8A6d301742133C89f08153BC9F52B585F824A18b,
// Team - 13% tokens, no freeze
0xE9B02195F38938f1462c59D7c1c2F15350ad1543
];
}
function onlyAdmin(bool forObserver) internal view {
require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender ||
forObserver==true && wallets[uint8(Roles.observer)] == msg.sender);
}
// Setting the current rate ETH/USD
function changeExchange(uint256 _ETHUSD) public {
require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.observer)] == msg.sender);
require(_ETHUSD >= 1 ether);
softCap=softCap.mul(exchange).div(_ETHUSD); // QUINTILLIONS
hardCap=hardCap.mul(exchange).div(_ETHUSD); // QUINTILLIONS
minPay=minPay.mul(exchange).div(_ETHUSD); // QUINTILLIONS
rate=rate.mul(_ETHUSD).div(exchange); // QUINTILLIONS
for (uint16 i = 0; i < bonuses.length; i++) {
bonuses[i].value=bonuses[i].value.mul(exchange).div(_ETHUSD); // QUINTILLIONS
}
financialStrategy.setup(wallets[uint8(Roles.beneficiary)], exchange, _ETHUSD, 5);
exchange=_ETHUSD;
}
// Setting of basic parameters, analog of class constructor
// @ Do I have to use the function see your scenario
// @ When it is possible to call before Round 1/2
// @ When it is launched automatically -
// @ Who can call the function admins
function begin() public
{
onlyAdmin(true);
if (isBegin) return;
isBegin=true;
token = creator.createToken();
financialStrategy = creator.createFinancialStrategy();
token.setUnpausedWallet(wallets[uint8(Roles.accountant)], true);
token.setUnpausedWallet(wallets[uint8(Roles.manager)], true);
token.setUnpausedWallet(wallets[uint8(Roles.bounty)], true);
token.setUnpausedWallet(wallets[uint8(Roles.company)], true);
token.setUnpausedWallet(wallets[uint8(Roles.observer)], true);
bonuses.push(Bonus(20 ether, 2,0));
bonuses.push(Bonus(100 ether, 5,0));
bonuses.push(Bonus(400 ether, 8,0));
profits.push(Profit(30,900 days));
}
// Issue of tokens for the zero round, it is usually called: private pre-sale (Round 0)
// @ Do I have to use the function may be
// @ When it is possible to call before Round 1/2
// @ When it is launched automatically -
// @ Who can call the function admins
function firstMintRound0(uint256 _amount /* QUINTILLIONS! */) public {
onlyAdmin(false);
require(canFirstMint);
begin();
token.mint(wallets[uint8(Roles.manager)],_amount);
}
// info
function totalSupply() external view returns (uint256){
return token.totalSupply();
}
// Returns the name of the current round in plain text. Constant.
function getTokenSaleType() external view returns(string){
return (TokenSale == TokenSaleType.round1)?'round1':'round2';
}
// Transfers the funds of the investor to the contract of return of funds. Internal.
function forwardFunds() internal {
financialStrategy.deposit.value(msg.value)(msg.sender);
}
// Check for the possibility of buying tokens. Inside. Constant.
function validPurchase() internal view returns (bool) {
// The round started and did not end
bool withinPeriod = (now > startTime && now < endTime.add(renewal));
// Rate is greater than or equal to the minimum
bool nonZeroPurchase = msg.value >= minPay;
// hardCap is not reached, and in the event of a transaction, it will not be exceeded by more than OverLimit
bool withinCap = msg.value <= hardCap.sub(weiRaised()).add(overLimit);
// round is initialized and no "Pause of trading" is set
return withinPeriod && nonZeroPurchase && withinCap && isInitialized && !isPausedCrowdsale;
}
// Check for the ability to finalize the round. Constant.
function hasEnded() public view returns (bool) {
bool timeReached = now > endTime.add(renewal);
bool capReached = weiRaised() >= hardCap;
return (timeReached || capReached) && isInitialized;
}
// Finalize. Only available to the Manager and the Beneficiary. If the round failed, then
// anyone can call the finalization to unlock the return of funds to investors
// You must call a function to finalize each round (after the Round1 & after the Round2)
// @ Do I have to use the function yes
// @ When it is possible to call after end of Round1 & Round2
// @ When it is launched automatically no
// @ Who can call the function admins or anybody (if round is failed)
function finalize() public {
require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender || !goalReached());
require(!isFinalized);
require(hasEnded() || ((wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender) && goalReached()));
isFinalized = true;
finalization();
emit Finalized();
}
// The logic of finalization. Internal
// @ Do I have to use the function no
// @ When it is possible to call -
// @ When it is launched automatically after end of round
// @ Who can call the function -
function finalization() internal {
// If the goal of the achievement
if (goalReached()) {
financialStrategy.setup(wallets[uint8(Roles.beneficiary)], weiRaised(), 0, 1);//Для контракта Buz деньги не возвращает.
// if there is anything to give
if (tokenReserved > 0) {
token.mint(wallets[uint8(Roles.accountant)],tokenReserved);
// Reset the counter
tokenReserved = 0;
}
// If the finalization is Round 1
if (TokenSale == TokenSaleType.round1) {
// Reset settings
isInitialized = false;
isFinalized = false;
// Switch to the second round (to Round2)
TokenSale = TokenSaleType.round2;
// Reset the collection counter
weiRound1 = weiRaised();
ethWeiRaised = 0;
nonEthWeiRaised = 0;
}
else // If the second round is finalized
{
// Permission to collect tokens to those who can pick them up
chargeBonuses = true;
totalSaledToken = token.totalSupply();
//partners = true;
}
}
else // If they failed round
{
financialStrategy.setup(wallets[uint8(Roles.beneficiary)], weiRaised(), 0, 3);
}
}
// The Manager freezes the tokens for the Team.
// You must call a function to finalize Round 2 (only after the Round2)
// @ Do I have to use the function yes
// @ When it is possible to call Round2
// @ When it is launched automatically -
// @ Who can call the function admins
function finalize2() public {
onlyAdmin(false);
require(chargeBonuses);
chargeBonuses = false;
//allocation = creator.createAllocation(token, now + 1 years /* stage N1 */, now + 2 years /* stage N2 */);
//token.setUnpausedWallet(allocation, true);
// Team = %, Founders = %, Fund = % TOTAL = %
//allocation.addShare(wallets[uint8(Roles.team)], 6, 50); // only 50% - first year, stage N1 (and +50 for stage N2)
//allocation.addShare(wallets[uint8(Roles.founders)], 10, 50); // only 50% - first year, stage N1 (and +50 for stage N2)
// 2% - bounty wallet
token.mint(wallets[uint8(Roles.bounty)], totalSaledToken.mul(2).div(75));
// 10% - company
token.mint(wallets[uint8(Roles.company)], totalSaledToken.mul(10).div(75));
// 13% - team
token.mint(wallets[uint8(Roles.team)], totalSaledToken.mul(13).div(75));
}
function changeCrowdsale(address _newCrowdsale) external {
//onlyAdmin(false);
require(wallets[uint8(Roles.manager)] == msg.sender);
Ownable(token).transferOwnership(_newCrowdsale);
}
// Initializing the round. Available to the manager. After calling the function,
// the Manager loses all rights: Manager can not change the settings (setup), change
// wallets, prevent the beginning of the round, etc. You must call a function after setup
// for the initial round (before the Round1 and before the Round2)
// @ Do I have to use the function yes
// @ When it is possible to call before each round
// @ When it is launched automatically -
// @ Who can call the function admins
function initialize() public {
onlyAdmin(false);
// If not yet initialized
require(!isInitialized);
begin();
// And the specified start time has not yet come
// If initialization return an error, check the start date!
require(now <= startTime);
initialization();
emit Initialized();
renewal = 0;
isInitialized = true;
canFirstMint = false;
}
function initialization() internal {
if (financialStrategy.state() != IFinancialStrategy.State.Active){
financialStrategy.setup(wallets[uint8(Roles.beneficiary)], weiRaised(), 0, 2);
}
}
//
// @ Do I have to use the function
// @ When it is possible to call
// @ When it is launched automatically
// @ Who can call the function
function getPartnerCash(uint8 _user, bool _calc) external {
bool isAdmin=false;
for (uint8 i=0; i<wallets.length; i++) {
if (wallets[i]==msg.sender) {
isAdmin=true;
break;
}
}
financialStrategy.getPartnerCash(_user, isAdmin, msg.sender, _calc, weiTotalRaised());
}
function getBeneficiaryCash() external {
onlyAdmin(false);
// financialStrategy.calc(weiTotalRaised());
financialStrategy.getBeneficiaryCash(wallets[uint8(Roles.beneficiary)]);
}
function calcFin() external {
onlyAdmin(true);
financialStrategy.calc(weiTotalRaised());
}
function calcAndGet() public {
onlyAdmin(true);
financialStrategy.calc(weiTotalRaised());
financialStrategy.getBeneficiaryCash(wallets[uint8(Roles.beneficiary)]);
for (uint8 i=0; i<3; i++) { // <-- TODO check financialStrategy.wallets.length
financialStrategy.getPartnerCash(i, true, msg.sender, false, weiTotalRaised());
}
}
// We check whether we collected the necessary minimum funds. Constant.
function goalReached() public view returns (bool) {
return weiRaised() >= softCap;
}
// Customize. The arguments are described in the constructor above.
// @ Do I have to use the function yes
// @ When it is possible to call before each rond
// @ When it is launched automatically -
// @ Who can call the function admins
function setup(uint256 _startTime, uint256 _endTime, uint256 _softCap, uint256 _hardCap,
uint256 _rate, uint256 _exchange,
uint256 _maxAllProfit, uint256 _overLimit, uint256 _minPay,
uint256[] _durationTB , uint256[] _percentTB, uint256[] _valueVB, uint256[] _percentVB, uint256[] _freezeTimeVB) public
{
onlyAdmin(false);
require(!isInitialized);
begin();
// Date and time are correct
require(now <= _startTime);
require(_startTime < _endTime);
startTime = _startTime;
endTime = _endTime;
// The parameters are correct
require(_softCap <= _hardCap);
softCap = _softCap;
hardCap = _hardCap;
require(_rate > 0);
rate = _rate;
overLimit = _overLimit;
minPay = _minPay;
exchange = _exchange;
maxAllProfit = _maxAllProfit;
require(_valueVB.length == _percentVB.length && _valueVB.length == _freezeTimeVB.length);
bonuses.length = _valueVB.length;
for(uint256 i = 0; i < _valueVB.length; i++){
bonuses[i] = Bonus(_valueVB[i],_percentVB[i],_freezeTimeVB[i]);
}
require(_percentTB.length == _durationTB.length);
profits.length = _percentTB.length;
for( i = 0; i < _percentTB.length; i++){
profits[i] = Profit(_percentTB[i],_durationTB[i]);
}
}
// Collected funds for the current round. Constant.
function weiRaised() public constant returns(uint256){
return ethWeiRaised.add(nonEthWeiRaised);
}
// Returns the amount of fees for both phases. Constant.
function weiTotalRaised() public constant returns(uint256){
return weiRound1.add(weiRaised());
}
// Returns the percentage of the bonus on the current date. Constant.
function getProfitPercent() public constant returns (uint256){
return getProfitPercentForData(now);
}
// Returns the percentage of the bonus on the given date. Constant.
function getProfitPercentForData(uint256 _timeNow) public constant returns (uint256){
uint256 allDuration;
for(uint8 i = 0; i < profits.length; i++){
allDuration = allDuration.add(profits[i].duration);
if(_timeNow < startTime.add(allDuration)){
return profits[i].percent;
}
}
return 0;
}
function getBonuses(uint256 _value) public constant returns (uint256,uint256,uint256){
if(bonuses.length == 0 || bonuses[0].value > _value){
return (0,0,0);
}
uint16 i = 1;
for(i; i < bonuses.length; i++){
if(bonuses[i].value > _value){
break;
}
}
return (bonuses[i-1].value,bonuses[i-1].procent,bonuses[i-1].freezeTime);
}
// The ability to quickly check Round1 (only for Round1, only 1 time). Completes the Round1 by
// transferring the specified number of tokens to the Accountant's wallet. Available to the Manager.
// Use only if this is provided by the script and white paper. In the normal scenario, it
// does not call and the funds are raised normally. We recommend that you delete this
// function entirely, so as not to confuse the auditors. Initialize & Finalize not needed.
// ** QUINTILIONS ** 10^18 / 1**18 / 1e18
// @ Do I have to use the function no, see your scenario
// @ When it is possible to call after Round0 and before Round2
// @ When it is launched automatically -
// @ Who can call the function admins
// function fastTokenSale(uint256 _totalSupply) external {
// onlyAdmin(false);
// require(TokenSale == TokenSaleType.round1 && !isInitialized);
// token.mint(wallets[uint8(Roles.accountant)], _totalSupply);
// TokenSale = TokenSaleType.round2;
// }
// Remove the "Pause of exchange". Available to the manager at any time. If the
// manager refuses to remove the pause, then 30-120 days after the successful
// completion of the TokenSale, anyone can remove a pause and allow the exchange to continue.
// The manager does not interfere and will not be able to delay the term.
// He can only cancel the pause before the appointed time.
// @ Do I have to use the function YES YES YES
// @ When it is possible to call after end of ICO
// @ When it is launched automatically -
// @ Who can call the function admins or anybody
function tokenUnpause() external {
require(wallets[uint8(Roles.manager)] == msg.sender
|| (now > endTime.add(renewal).add(USER_UNPAUSE_TOKEN_TIMEOUT) && TokenSale == TokenSaleType.round2 && isFinalized && goalReached()));
token.setPause(false);
}
// Enable the "Pause of exchange". Available to the manager until the TokenSale is completed.
// The manager cannot turn on the pause, for example, 3 years after the end of the TokenSale.
// @ Do I have to use the function no
// @ When it is possible to call while Round2 not ended
// @ When it is launched automatically before any rounds
// @ Who can call the function admins
function tokenPause() public {
onlyAdmin(false);
require(!isFinalized);
token.setPause(true);
}
// Pause of sale. Available to the manager.
// @ Do I have to use the function no
// @ When it is possible to call during active rounds
// @ When it is launched automatically -
// @ Who can call the function admins
function setCrowdsalePause(bool mode) public {
onlyAdmin(false);
isPausedCrowdsale = mode;
}
// For example - After 5 years of the project's existence, all of us suddenly decided collectively
// (company + investors) that it would be more profitable for everyone to switch to another smart
// contract responsible for tokens. The company then prepares a new token, investors
// disassemble, study, discuss, etc. After a general agreement, the manager allows any investor:
// - to burn the tokens of the previous contract
// - generate new tokens for a new contract
// It is understood that after a general solution through this function all investors
// will collectively (and voluntarily) move to a new token.
// @ Do I have to use the function no
// @ When it is possible to call only after ICO!
// @ When it is launched automatically -
// @ Who can call the function admins
function moveTokens(address _migrationAgent) public {
onlyAdmin(false);
token.setMigrationAgent(_migrationAgent);
}
// @ Do I have to use the function no
// @ When it is possible to call only after ICO!
// @ When it is launched automatically -
// @ Who can call the function admins
function migrateAll(address[] _holders) public {
onlyAdmin(false);
token.migrateAll(_holders);
}
// Change the address for the specified role.
// Available to any wallet owner except the observer.
// Available to the manager until the round is initialized.
// The Observer's wallet or his own manager can change at any time.
// @ Do I have to use the function no
// @ When it is possible to call depend...
// @ When it is launched automatically -
// @ Who can call the function staff (all 7+ roles)
function changeWallet(Roles _role, address _wallet) external
{
require(
(msg.sender == wallets[uint8(_role)] /*&& _role != Roles.observer*/)
||
(msg.sender == wallets[uint8(Roles.manager)] && (!isInitialized || _role == Roles.observer))
);
wallets[uint8(_role)] = _wallet;
}
// The beneficiary at any time can take rights in all roles and prescribe his wallet in all the
// rollers. Thus, he will become the recipient of tokens for the role of Accountant,
// Team, etc. Works at any time.
// @ Do I have to use the function no
// @ When it is possible to call any time
// @ When it is launched automatically -
// @ Who can call the function only Beneficiary
// function resetAllWallets() external{
// address _beneficiary = wallets[uint8(Roles.beneficiary)];
// require(msg.sender == _beneficiary);
// for(uint8 i = 0; i < wallets.length; i++){
// wallets[i] = _beneficiary;
// }
// token.setUnpausedWallet(_beneficiary, true);
// }
// Burn the investor tokens, if provided by the ICO scenario. Limited time available - BURN_TOKENS_TIME
// For people who ignore the KYC/AML procedure during 30 days after payment: money back and burning tokens.
// ***CHECK***SCENARIO***
// @ Do I have to use the function no
// @ When it is possible to call any time
// @ When it is launched automatically -
// @ Who can call the function admin
function massBurnTokens(address[] _beneficiary, uint256[] _value) external {
onlyAdmin(false);
require(endTime.add(renewal).add(BURN_TOKENS_TIME) > now);
require(_beneficiary.length == _value.length);
for(uint16 i; i<_beneficiary.length; i++) {
token.burn(_beneficiary[i],_value[i]);
}
}
// Extend the round time, if provided by the script. Extend the round only for
// a limited number of days - ROUND_PROLONGATE
// ***CHECK***SCENARIO***
// @ Do I have to use the function no
// @ When it is possible to call during active round
// @ When it is launched automatically -
// @ Who can call the function admins
function prolongate(uint256 _duration) external {
onlyAdmin(false);
require(now > startTime && now < endTime.add(renewal) && isInitialized);
renewal = renewal.add(_duration);
require(renewal <= ROUND_PROLONGATE);
}
// If a little more than a year has elapsed (Round2 start date + 400 days), a smart contract
// will allow you to send all the money to the Beneficiary, if any money is present. This is
// possible if you mistakenly launch the Round2 for 30 years (not 30 days), investors will transfer
// money there and you will not be able to pick them up within a reasonable time. It is also
// possible that in our checked script someone will make unforeseen mistakes, spoiling the
// finalization. Without finalization, money cannot be returned. This is a rescue option to
// get around this problem, but available only after a year (400 days).
// Another reason - the TokenSale was a failure, but not all ETH investors took their money during the year after.
// Some investors may have lost a wallet key, for example.
// The method works equally with the Round1 and Round2. When the Round1 starts, the time for unlocking
// the distructVault begins. If the TokenSale is then started, then the term starts anew from the first day of the TokenSale.
// Next, act independently, in accordance with obligations to investors.
// Within 400 days (FORCED_REFUND_TIMEOUT1) of the start of the Round, if it fails only investors can take money. After
// the deadline this can also include the company as well as investors, depending on who is the first to use the method.
// @ Do I have to use the function no
// @ When it is possible to call -
// @ When it is launched automatically -
// @ Who can call the function beneficiary & manager
function distructVault(bool mode) public {
if(mode){
if (wallets[uint8(Roles.beneficiary)] == msg.sender && (now > startTime.add(FORCED_REFUND_TIMEOUT1))) {
financialStrategy.setup(wallets[uint8(Roles.beneficiary)], weiRaised(), 0, 0);
}
if (wallets[uint8(Roles.manager)] == msg.sender && (now > startTime.add(FORCED_REFUND_TIMEOUT2))) {
financialStrategy.setup(wallets[uint8(Roles.manager)], weiRaised(), 0, 0);
}
} else {
onlyAdmin(false);
financialStrategy.setup(wallets[uint8(Roles.beneficiary)], 0, 0, 4);
}
}
// We accept payments other than Ethereum (ETH) and other currencies, for example, Bitcoin (BTC).
// Perhaps other types of cryptocurrency - see the original terms in the white paper and on the TokenSale website.
// We release tokens on Ethereum. During the Round1 and Round2 with a smart contract, you directly transfer
// the tokens there and immediately, with the same transaction, receive tokens in your wallet.
// When paying in any other currency, for example in BTC, we accept your money via one common wallet.
// Our manager fixes the amount received for the bitcoin wallet and calls the method of the smart
// contract paymentsInOtherCurrency to inform him how much foreign currency has been received - on a daily basis.
// The smart contract pins the number of accepted ETH directly and the number of BTC. Smart contract
// monitors softcap and hardcap, so as not to go beyond this framework.
// In theory, it is possible that when approaching hardcap, we will receive a transfer (one or several
// transfers) to the wallet of BTC, that together with previously received money will exceed the hardcap in total.
// In this case, we will refund all the amounts above, in order not to exceed the hardcap.
// Collection of money in BTC will be carried out via one common wallet. The wallet's address will be published
// everywhere (in a white paper, on the TokenSale website, on Telegram, on Bitcointalk, in this code, etc.)
// Anyone interested can check that the administrator of the smart contract writes down exactly the amount
// in ETH (in equivalent for BTC) there. In theory, the ability to bypass a smart contract to accept money in
// BTC and not register them in ETH creates a possibility for manipulation by the company. Thanks to
// paymentsInOtherCurrency however, this threat is leveled.
// Any user can check the amounts in BTC and the variable of the smart contract that accounts for this
// (paymentsInOtherCurrency method). Any user can easily check the incoming transactions in a smart contract
// on a daily basis. Any hypothetical tricks on the part of the company can be exposed and panic during the TokenSale,
// simply pointing out the incompatibility of paymentsInOtherCurrency (ie, the amount of ETH + BTC collection)
// and the actual transactions in BTC. The company strictly adheres to the described principles of openness.
// The company administrator is required to synchronize paymentsInOtherCurrency every working day (but you
// cannot synchronize if there are no new BTC payments). In the case of unforeseen problems, such as
// brakes on the Ethereum network, this operation may be difficult. You should only worry if the
// administrator does not synchronize the amount for more than 96 hours in a row, and the BTC wallet
// receives significant amounts.
// This scenario ensures that for the sum of all fees in all currencies this value does not exceed hardcap.
// ** QUINTILLIONS ** 10^18 / 1**18 / 1e18
// @ Do I have to use the function no
// @ When it is possible to call during active rounds
// @ When it is launched automatically every day from cryptob2b token software
// @ Who can call the function admins + observer
function paymentsInOtherCurrency(uint256 _token, uint256 _value) public {
// For audit:
// BTC 13vL9G4Gt2BX58qQQfauf9JbFFjC5pEnQy
// XRP rHG2nJCKYEe326zhTtXWVEeDob81VKkK3q
// DASH XcMZbRJzPghTcZPyScF21mL3eKhYAGo4Ab
// LTC LcKTi2ZduMvHo7WbXye2RhLy9xMZjdXWZS
require(wallets[uint8(Roles.observer)] == msg.sender || wallets[uint8(Roles.manager)] == msg.sender);
//onlyAdmin(true);
bool withinPeriod = (now >= startTime && now <= endTime.add(renewal));
bool withinCap = _value.add(ethWeiRaised) <= hardCap.add(overLimit);
require(withinPeriod && withinCap && isInitialized);
nonEthWeiRaised = _value;
tokenReserved = _token;
}
function lokedMint(address _beneficiary, uint256 _value, uint256 _freezeTime) internal {
if(_freezeTime > 0){
uint256 totalBloked = token.freezedTokenOf(_beneficiary).add(_value);
uint256 pastDateUnfreeze = token.defrostDate(_beneficiary);
uint256 newDateUnfreeze = _freezeTime.add(now);
newDateUnfreeze = (pastDateUnfreeze > newDateUnfreeze ) ? pastDateUnfreeze : newDateUnfreeze;
token.freezeTokens(_beneficiary,totalBloked,newDateUnfreeze);
}
token.mint(_beneficiary,_value);
}
// The function for obtaining smart contract funds in ETH. If all the checks are true, the token is
// transferred to the buyer, taking into account the current bonus.
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 ProfitProcent = getProfitPercent();
uint256 value;
uint256 percent;
uint256 freezeTime;
(value,
percent,
freezeTime) = getBonuses(weiAmount);
Bonus memory curBonus = Bonus(value,percent,freezeTime);
uint256 bonus = curBonus.procent;
// --------------------------------------------------------------------------------------------
// *** Scenario 1 - select max from all bonuses + check maxAllProfit
//uint256 totalProfit = (ProfitProcent < bonus) ? bonus : ProfitProcent;
// *** Scenario 2 - sum both bonuses + check maxAllProfit
uint256 totalProfit = bonus.add(ProfitProcent);
// --------------------------------------------------------------------------------------------
totalProfit = (totalProfit > maxAllProfit) ? maxAllProfit : totalProfit;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate).mul(totalProfit.add(100)).div(100 ether);
// update state
ethWeiRaised = ethWeiRaised.add(weiAmount);
lokedMint(beneficiary, tokens, curBonus.freezeTime);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// buyTokens alias
function () public payable {
buyTokens(msg.sender);
}
}
contract MigratableToken is BasicToken,Ownable {
uint256 public totalMigrated;
address public migrationAgent;
event Migrate(address indexed _from, address indexed _to, uint256 _value);
function setMigrationAgent(address _migrationAgent) public onlyOwner {
require(migrationAgent == 0x0);
migrationAgent = _migrationAgent;
}
function migrateInternal(address _holder) internal{
require(migrationAgent != 0x0);
uint256 value = balances[_holder];
balances[_holder] = 0;
totalSupply_ = totalSupply_.sub(value);
totalMigrated = totalMigrated.add(value);
MigrationAgent(migrationAgent).migrateFrom(_holder, value);
emit Migrate(_holder,migrationAgent,value);
}
function migrateAll(address[] _holders) public onlyOwner {
for(uint i = 0; i < _holders.length; i++){
migrateInternal(_holders[i]);
}
}
// Reissue your tokens.
function migrate() public
{
require(balances[msg.sender] > 0);
migrateInternal(msg.sender);
}
}
contract BurnableToken is BasicToken, Ownable {
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(address _beneficiary, uint256 _value) public onlyOwner {
require(_value <= balances[_beneficiary]);
// 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[_beneficiary] = balances[_beneficiary].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_beneficiary, _value);
emit Transfer(_beneficiary, address(0), _value);
}
}
contract Pausable is Ownable {
mapping (address => bool) public unpausedWallet;
event Pause();
event Unpause();
bool public paused = true;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused(address _to) {
require(!paused||unpausedWallet[msg.sender]||unpausedWallet[_to]);
_;
}
function onlyAdmin() internal view {
require(owner == msg.sender || msg.sender == ICrowdsale(owner).wallets(uint8(ICrowdsale.Roles.manager)));
}
// Add a wallet ignoring the "Exchange pause". Available to the owner of the contract.
function setUnpausedWallet(address _wallet, bool mode) public {
onlyAdmin();
unpausedWallet[_wallet] = mode;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function setPause(bool mode) onlyOwner public {
if (!paused && mode) {
paused = true;
emit Pause();
}
if (paused && !mode) {
paused = false;
emit Unpause();
}
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused(_to) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused(_to) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
contract FreezingToken is PausableToken {
struct freeze {
uint256 amount;
uint256 when;
}
mapping (address => freeze) freezedTokens;
function freezedTokenOf(address _beneficiary) public view returns (uint256 amount){
freeze storage _freeze = freezedTokens[_beneficiary];
if(_freeze.when < now) return 0;
return _freeze.amount;
}
function defrostDate(address _beneficiary) public view returns (uint256 Date) {
freeze storage _freeze = freezedTokens[_beneficiary];
if(_freeze.when < now) return 0;
return _freeze.when;
}
function freezeTokens(address _beneficiary, uint256 _amount, uint256 _when) public {
onlyAdmin();
freeze storage _freeze = freezedTokens[_beneficiary];
_freeze.amount = _amount;
_freeze.when = _when;
}
function masFreezedTokens(address[] _beneficiary, uint256[] _amount, uint256[] _when) public {
onlyAdmin();
require(_beneficiary.length == _amount.length && _beneficiary.length == _when.length);
for(uint16 i = 0; i < _beneficiary.length; i++){
freeze storage _freeze = freezedTokens[_beneficiary[i]];
_freeze.amount = _amount[i];
_freeze.when = _when[i];
}
}
function transferAndFreeze(address _to, uint256 _value, uint256 _when) external {
require(unpausedWallet[msg.sender]);
if(_when > 0){
freeze storage _freeze = freezedTokens[_to];
_freeze.amount = _freeze.amount.add(_value);
_freeze.when = (_freeze.when > _when)? _freeze.when: _when;
}
transfer(_to,_value);
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(balanceOf(msg.sender) >= freezedTokenOf(msg.sender).add(_value));
return super.transfer(_to,_value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(balanceOf(_from) >= freezedTokenOf(_from).add(_value));
return super.transferFrom( _from,_to,_value);
}
}
contract Token is IToken, FreezingToken, MintableToken, MigratableToken, BurnableToken{
string public constant name = "BUZcoin";
string public constant symbol = "BUZ";
uint8 public constant decimals = 18;
}
contract Creator is ICreator{
IToken public token = new Token();
IFinancialStrategy public financialStrategy = new BuzFinancialStrategy();
function createToken() external returns (IToken) {
Token(token).transferOwnership(msg.sender);
return token;
}
function createFinancialStrategy() external returns(IFinancialStrategy) {
BuzFinancialStrategy(financialStrategy).transferOwnership(msg.sender);
return financialStrategy;
}
}
|
0 - destruct 1 - close 2 - restart 3 - refund 4 - test 5 - update Exchange call from Crowdsale.distructVault(true) for exit arg1 - nothing arg2 - nothing Call from Crowdsale.finalization() [1] - successfull round (goalReach) [3] - failed round (not enough money) arg1 = weiTotalRaised(); arg2 = nothing;internalCalc(_arg1); Call from Crowdsale.initialization() arg1 = weiTotalRaised(); arg2 = nothing; call from Crowdsale.distructVault(false) for test arg1 = nothing; arg2 = nothing; arg1 = old ETH/USD (exchange) arg2 = new ETH/USD (_ETHUSD)
|
function setup(address _beneficiary, uint256 _arg1, uint256 _arg2, uint8 _state) external onlyOwner {
if (_state == 0) {
selfdestruct(_beneficiary);
}
else if (_state == 1 || _state == 3) {
require(state == State.Active);
state = State.Closed;
benWallet=_beneficiary;
}
else if (_state == 2) {
require(state == State.Closed);
state = State.Active;
benWallet=_beneficiary;
}
else if (_state == 4) {
benWallet=_beneficiary;
}
else if (_state == 5) {
for (uint8 user=0; user<cap.length; user++) cap[user]=cap[user].mul(_arg1).div(_arg2);
benWallet=_beneficiary;
}
}
| 203,532
|
pragma solidity 0.7.1;
pragma experimental ABIEncoderV2;
contract CoreUniLotterySettings
{
// Percentage calculations.
// As Solidity doesn't have floats, we have to use integers for
// percentage arithmetics.
// We set 1 percent to be equal to 1,000,000 - thus, we
// simulate 6 decimal points when computing percentages.
uint32 public constant PERCENT = 10 ** 6;
uint32 constant BASIS_POINT = PERCENT / 100;
uint32 constant _100PERCENT = 100 * PERCENT;
/** The UniLottery Owner's address.
*
* In the current version, The Owner has rights to:
* - Take up to 10% profit from every lottery.
* - Pool liquidity into the pool and unpool it.
* - Start new Auto-Mode & Manual-Mode lotteries.
* - Set randomness provider gas price & other settings.
*/
// Public Testnets: 0xb13CB9BECcB034392F4c9Db44E23C3Fb5fd5dc63
// MainNet: 0x1Ae51bec001a4fA4E3b06A5AF2e0df33A79c01e2
address payable public constant OWNER_ADDRESS =
address( uint160( 0x1Ae51bec001a4fA4E3b06A5AF2e0df33A79c01e2 ) );
// Maximum lottery fee the owner can imburse on transfers.
uint32 constant MAX_OWNER_LOTTERY_FEE = 1 * PERCENT;
// Minimum amout of profit percentage that must be distributed
// to lottery winners.
uint32 constant MIN_WINNER_PROFIT_SHARE = 40 * PERCENT;
// Min & max profits the owner can take from lottery net profit.
uint32 constant MIN_OWNER_PROFITS = 3 * PERCENT;
uint32 constant MAX_OWNER_PROFITS = 10 * PERCENT;
// Min & max amount of lottery profits that the pool must get.
uint32 constant MIN_POOL_PROFITS = 10 * PERCENT;
uint32 constant MAX_POOL_PROFITS = 60 * PERCENT;
// Maximum lifetime of a lottery - 1 month (4 weeks).
uint32 constant MAX_LOTTERY_LIFETIME = 4 weeks;
// Callback gas requirements for a lottery's ending callback,
// and for the Pool's Scheduled Callback.
// Must be determined empirically.
uint32 constant LOTTERY_RAND_CALLBACK_GAS = 200000;
uint32 constant AUTO_MODE_SCHEDULED_CALLBACK_GAS = 3800431;
}
interface IUniswapRouter
{
// Get Factory and WETH addresses.
function factory() external pure returns (address);
function WETH() external pure returns (address);
// Create/add to a liquidity pair using ETH.
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline )
external
payable
returns (
uint amountToken,
uint amountETH,
uint liquidity
);
// Remove liquidity pair.
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline )
external
returns (
uint amountETH
);
// Get trade output amount, given an input.
function getAmountsOut(
uint amountIn,
address[] memory path )
external view
returns (
uint[] memory amounts
);
// Get trade input amount, given an output.
function getAmountsIn(
uint amountOut,
address[] memory path )
external view
returns (
uint[] memory amounts
);
}
interface IUniswapFactory
{
function getPair(
address tokenA,
address tokenB )
external view
returns ( address pair );
}
contract UniLotteryConfigGenerator
{
function getConfig()
external pure
returns( Lottery.LotteryConfig memory cfg )
{
cfg.initialFunds = 10 ether;
}
}
contract UniLotteryLotteryFactory
{
// Uniswap Router address on this network - passed to Lotteries on
// construction.
//ddress payable immutable uniRouterAddress;
// Delegate Contract for the Lottery, containing all logic code
// needed for deploying LotteryStubs.
// Deployed only once, on construction.
address payable immutable public delegateContract;
// The Pool Address.
address payable poolAddress;
// The Lottery Storage Factory address, that the Lottery contracts use.
UniLotteryStorageFactory lotteryStorageFactory;
// Pool-Only modifier.
modifier poolOnly
{
require( msg.sender == poolAddress/*,
"Function can only be called by the Main Pool!" */);
_;
}
// Constructor.
// Set the Uniswap Address, and deploy&lock the Delegate Code contract.
//
constructor( /*address payable _uniRouter*/ )
{
//uniRouterAddress = _uniRouter;
delegateContract = address( uint160( address( new Lottery() ) ) );
}
// Initialization function.
// Set the poolAddress as msg.sender, and lock it.
// Also, set the Lottery Storage Factory contract instance address.
function initialize( address _storageFactoryAddress )
external
{
require( poolAddress == address( 0 )/*,
"Initialization has already finished!" */);
// Set the Pool's Address.
// Lock it. No more calls to this function will be executed.
poolAddress = msg.sender;
// Set the Storage Factory, and initialize it!
lotteryStorageFactory =
UniLotteryStorageFactory( _storageFactoryAddress );
lotteryStorageFactory.initialize();
}
/**
* Deploy a new Lottery Stub from the specified config.
* @param config - Lottery Config to be used (passed by the pool).
* @return newLottery - the newly deployed lottery stub.
*/
function createNewLottery(
Lottery.LotteryConfig memory config,
address randomnessProvider )
public
poolOnly
returns( address payable newLottery )
{
// Create new Lottery Storage, using storage factory.
// Populate the stub, by calling the "construct" function.
LotteryStub stub = new LotteryStub();
stub.stub_construct( delegateContract );
Lottery( address( stub ) ).construct(
config, poolAddress, randomnessProvider,
lotteryStorageFactory.createNewStorage() );
return address( stub );
}
}
contract LotteryStub
{
// ============ ERC20 token contract's storage ============ //
// ------- Slot ------- //
// Balances of token holders.
mapping (address => uint256) private _balances;
// ------- Slot ------- //
// Allowances of spenders for a specific token owner.
mapping (address => mapping (address => uint256)) private _allowances;
// ------- Slot ------- //
// Total supply of the token.
uint256 private _totalSupply;
// ============== Lottery contract's storage ============== //
// ------- Initial Slots ------- //
// The config which is passed to constructor.
Lottery.LotteryConfig internal cfg;
// ------- Slot ------- //
// The Lottery Storage contract, which stores all holder data,
// such as scores, referral tree data, etc.
LotteryStorage /*public*/ lotStorage;
// ------- Slot ------- //
// Pool address. Set on constructor from msg.sender.
address payable /*public*/ poolAddress;
// ------- Slot ------- //
// Randomness Provider address.
address /*public*/ randomnessProvider;
// ------- Slot ------- //
// Exchange address. In Uniswap mode, it's the Uniswap liquidity
// pair's address, where trades execute.
address /*public*/ exchangeAddress;
// Start date.
uint32 /*public*/ startDate;
// Completion (Mining Phase End) date.
uint32 /*public*/ completionDate;
// The date when Randomness Provider was called, requesting a
// random seed for the lottery finish.
// Also, when this variable becomes Non-Zero, it indicates that we're
// on Ending Stage Part One: waiting for the random seed.
uint32 finish_timeRandomSeedRequested;
// ------- Slot ------- //
// WETH address. Set by calling Router's getter, on constructor.
address WETHaddress;
// Is the WETH first or second token in our Uniswap Pair?
bool uniswap_ethFirst;
// If we are, or were before, on finishing stage, this is the
// probability of lottery going to Ending Stage on this transaction.
uint32 finishProbablity;
// Re-Entrancy Lock (Mutex).
// We protect for reentrancy in the Fund Transfer functions.
bool reEntrancyMutexLocked;
// On which stage we are currently.
uint8 /*public*/ lotteryStage;
// Indicator for whether the lottery fund gains have passed a
// minimum fund gain requirement.
// After that time point (when this bool is set), the token sells
// which could drop the fund value below the requirement, would
// be denied.
bool fundGainRequirementReached;
// The current step of the Mining Stage.
uint16 miningStep;
// If we're currently on Special Transfer Mode - that is, we allow
// direct transfers between parties even in NON-ACTIVE state.
bool specialTransferModeEnabled;
// ------- Slot ------- //
// Per-Transaction Pseudo-Random hash value (transferHashValue).
// This value is computed on every token transfer, by keccak'ing
// the last (current) transferHashValue, msg.sender, block.timestamp, and
// transaction count.
//
// This is used on Finishing Stage, as a pseudo-random number,
// which is used to check if we should end the lottery (move to
// Ending Stage).
uint256 transferHashValue;
// ------- Slot ------- //
// On lottery end, get & store the lottery total ETH return
// (including initial funds), and profit amount.
uint128 /*public*/ ending_totalReturn;
uint128 /*public*/ ending_profitAmount;
// ------- Slot ------- //
// The mapping that contains TRUE for addresses that already claimed
// their lottery winner prizes.
// Used only in COMPLETION, on claimWinnerPrize(), to check if
// msg.sender has already claimed his prize.
mapping( address => bool ) /*public*/ prizeClaimersAddresses;
// =================== OUR CONTRACT'S OWN STORAGE =================== //
// The address of the delegate contract, containing actual logic.
address payable public __delegateContract;
// =================== Functions =================== //
// Constructor.
// Just set the delegate's address.
function stub_construct( address payable _delegateAddr )
external
{
require( __delegateContract == address(0) );
__delegateContract = _delegateAddr;
}
// Fallback payable function, which delegates any call to our
// contract, into the delegate contract.
fallback()
external payable
{
// DelegateCall the delegate code contract.
( bool success, bytes memory data ) =
__delegateContract.delegatecall( msg.data );
// Use inline assembly to be able to return value from the fallback.
// (by default, returning a value from fallback is not possible,
// but it's still possible to manually copy data to the
// return buffer.
assembly
{
// delegatecall returns 0 (false) on error.
// Add 32 bytes to "data" pointer, because first slot (32 bytes)
// contains the length, and we use return value's length
// from returndatasize() opcode.
switch success
case 0 { revert( add( data, 32 ), returndatasize() ) }
default { return( add( data, 32 ), returndatasize() ) }
}
}
// Receive ether function.
receive() external payable
{ }
}
contract LotteryStorageStub
{
// =============== LotteryStorage contract's storage ================ //
// --------- Slot --------- //
// The Lottery address that this storage belongs to.
// Is set by the "initialize()", called by corresponding Lottery.
address lottery;
// The Random Seed, that was passed to us from Randomness Provider,
// or generated alternatively.
uint64 randomSeed;
// The actual number of winners that there will be. Set after
// completing the Winner Selection Algorithm.
uint16 numberOfWinners;
// Bool indicating if Winner Selection Algorithm has been executed.
bool algorithmCompleted;
// --------- Slot --------- //
// Winner Algorithm config. Specified in Initialization().
LotteryStorage.WinnerAlgorithmConfig algConfig;
// --------- Slot --------- //
// The Min-Max holder score storage.
LotteryStorage.MinMaxHolderScores minMaxScores;
// --------- Slot --------- //
// Array of holders.
address[] /*public*/ holders;
// --------- Slot --------- //
// Holder array indexes mapping, for O(1) array element access.
mapping( address => uint ) holderIndexes;
// --------- Slot --------- //
// Mapping of holder data.
mapping( address => LotteryStorage.HolderData ) /*public*/ holderData;
// --------- Slot --------- //
// Mapping of referral IDs to addresses of holders who generated
// those IDs.
mapping( uint256 => address ) referrers;
// --------- Slot --------- //
// The array of final-sorted winners (set after Winner Selection
// Algorithm completes), that contains the winners' indexes
// in the "holders" array, to save space.
//
// Notice that by using uint16, we can fit 16 items into one slot!
// So, if there are 160 winners, we only take up 10 slots, so
// only 20,000 * 10 = 200,000 gas gets consumed!
//
LotteryStorage.WinnerIndexStruct[] sortedWinnerIndexes;
// =================== OUR CONTRACT'S OWN STORAGE =================== //
// The address of the delegate contract, containing actual logic.
address public __delegateContract;
// =================== Functions =================== //
// Constructor.
// Just set the delegate's address.
function stub_construct( address _delegateAddr )
external
{
require( __delegateContract == address(0) );
__delegateContract = _delegateAddr;
}
// Fallback function, which delegates any call to our
// contract, into the delegate contract.
fallback()
external
{
// DelegateCall the delegate code contract.
( bool success, bytes memory data ) =
__delegateContract.delegatecall( msg.data );
// Use inline assembly to be able to return value from the fallback.
// (by default, returning a value from fallback is not possible,
// but it's still possible to manually copy data to the
// return buffer.
assembly
{
// delegatecall returns 0 (false) on error.
// Add 32 bytes to "data" pointer, because first slot (32 bytes)
// contains the length, and we use return value's length
// from returndatasize() opcode.
switch success
case 0 { revert( add( data, 32 ), returndatasize() ) }
default { return( add( data, 32 ), returndatasize() ) }
}
}
}
interface IUniLotteryPool
{
function lotteryFinish( uint totalReturn, uint profitAmount )
external payable;
}
interface IRandomnessProvider
{
function requestRandomSeedForLotteryFinish() external;
}
contract LotteryStorage is CoreUniLotterySettings
{
// ==================== Structs & Constants ==================== //
// Struct of holder data & scores.
struct HolderData
{
// --------- Slot --------- //
// If this holder provided a valid referral ID, this is the
// address of a referrer - the user who generated the said
// referral ID.
address referrer;
// Bonus score points, which can be given in certain events,
// such as when player registers a valid referral ID.
int16 bonusScore;
// Number of all child referrees, including multi-level ones.
// Updated by traversing child->parent way, incrementing
// every node's counter by one.
// Used in Winner Selection Algorithm, to determine how much
// to divide the accumulated referree scores by.
uint16 referreeCount;
// --------- Slot --------- //
// If this holder has generated his own referral ID, this is
// that ID. If he hasn't generated an ID, this is zero.
uint256 referralID;
// --------- Slot --------- //
// The intermediate individual score factor variables.
// Ether contributed: ( buys - sells ). Can be negative.
int40 etherContributed;
// Time x ether factor: (relativeTxTime * etherAmount).
int40 timeFactors;
// Token balance score factor of this holder - we use int,
// for easier computation of player scores in our algorithms.
int40 tokenBalance;
// Accumulated referree score factors - ether contributed by
// all referrees, time factors, and token balances of all
// referrees.
int40 referree_etherContributed;
int40 referree_timeFactors;
int40 referree_tokenBalance;
}
// Final Score (end lottery score * randomValue) structure.
struct FinalScore
{
address addr; // 20 bytes \
uint16 holderIndex; // 2 bytes | = 30 bytes => 1 slot.
uint64 score; // 8 bytes /
}
// Winner Indexes structure - used to efficiently store Winner
// indexes in holder's array, after completing the Winner Selection
// Algorithm.
// To save Space, we store these in a struct, with uint16 array
// with 16 items - so this struct takes up excactly 1 slot.
struct WinnerIndexStruct
{
uint16[ 16 ] indexes;
}
// A structure which is used by Winner Selection algorithm,
// which is a subset of the LotteryConfig structure, containing
// only items necessary for executing the Winner Selection algorigm.
// More detailed member description can be found in LotteryConfig
// structure description.
// Takes up only one slot!
struct WinnerAlgorithmConfig
{
// --------- Slot --------- //
// Individual player max score parts.
int16 maxPlayerScore_etherContributed;
int16 maxPlayerScore_tokenHoldingAmount;
int16 maxPlayerScore_timeFactor;
int16 maxPlayerScore_refferalBonus;
// Number of lottery winners.
uint16 winnerCount;
// Score-To-Random ration data (as a rational ratio number).
// For example if 1:5, then scorePart = 1, and randPart = 5.
uint16 randRatio_scorePart;
uint16 randRatio_randPart;
// The Ending Algorithm type.
uint8 endingAlgoType;
}
// Structure containing the minimum and maximum values of
// holder intermediate scores.
// These values get updated on transfers during ACTIVE stage,
// when holders buy/sell tokens.
//
// Used in winner selection algorithm, to normalize the scores in
// a single loop, to avoid looping additional time to find min/max.
//
// Structure takes up only a single slot!
//
struct MinMaxHolderScores
{
// --------- Slot --------- //
int40 holderScore_etherContributed_min;
int40 holderScore_etherContributed_max;
int40 holderScore_timeFactors_min;
int40 holderScore_timeFactors_max;
int40 holderScore_tokenBalance_min;
int40 holderScore_tokenBalance_max;
}
// Referral score variant of the structure above.
// Also, only a single slot!
//
struct MinMaxReferralScores
{
// --------- Slot --------- //
// Min&Max values for referrer scores.
int40 referralScore_etherContributed_min;
int40 referralScore_etherContributed_max;
int40 referralScore_timeFactors_min;
int40 referralScore_timeFactors_max;
int40 referralScore_tokenBalance_min;
int40 referralScore_tokenBalance_max;
}
// ROOT_REFERRER constant.
// Used to prevent cyclic dependencies on referral tree.
address constant ROOT_REFERRER = address( 1 );
// Max referral tree depth - maximum number of referrees that
// a referrer can get.
uint constant MAX_REFERRAL_DEPTH = 10;
// Precision of division operations.
int constant PRECISION = 10000;
// Random number modulo to use when obtaining random numbers from
// the random seed + nonce, using keccak256.
// This is the maximum available Score Random Factor, plus one.
// By default, 10^9 (one billion).
//
uint constant RANDOM_MODULO = (10 ** 9);
// Maximum number of holders that the MinedWinnerSelection algorithm
// can process. Related to block gas limit.
uint constant MINEDSELECTION_MAX_NUMBER_OF_HOLDERS = 300;
// Maximum number of holders that the WinnerSelfValidation algorithm
// can process. Related to block gas limit.
uint constant SELFVALIDATION_MAX_NUMBER_OF_HOLDERS = 1200;
// ==================== State Variables ==================== //
// --------- Slot --------- //
// The Lottery address that this storage belongs to.
// Is set by the "initialize()", called by corresponding Lottery.
address lottery;
// The Random Seed, that was passed to us from Randomness Provider,
// or generated alternatively.
uint64 randomSeed;
// The actual number of winners that there will be. Set after
// completing the Winner Selection Algorithm.
uint16 numberOfWinners;
// Bool indicating if Winner Selection Algorithm has been executed.
bool algorithmCompleted;
// --------- Slot --------- //
// Winner Algorithm config. Specified in Initialization().
WinnerAlgorithmConfig algConfig;
// --------- Slot --------- //
// The Min-Max holder score storage.
MinMaxHolderScores public minMaxScores;
MinMaxReferralScores public minMaxReferralScores;
// --------- Slot --------- //
// Array of holders.
address[] public holders;
// --------- Slot --------- //
// Holder array indexes mapping, for O(1) array element access.
mapping( address => uint ) holderIndexes;
// --------- Slot --------- //
// Mapping of holder data.
mapping( address => HolderData ) public holderData;
// --------- Slot --------- //
// Mapping of referral IDs to addresses of holders who generated
// those IDs.
mapping( uint256 => address ) referrers;
// --------- Slot --------- //
// The array of final-sorted winners (set after Winner Selection
// Algorithm completes), that contains the winners' indexes
// in the "holders" array, to save space.
//
// Notice that by using uint16, we can fit 16 items into one slot!
// So, if there are 160 winners, we only take up 10 slots, so
// only 20,000 * 10 = 200,000 gas gets consumed!
//
WinnerIndexStruct[] sortedWinnerIndexes;
// ============== Internal (Private) Functions ============== //
// Lottery-Only modifier.
modifier lotteryOnly
{
require( msg.sender == address( lottery )/*,
"Function can only be called by Lottery that this"
"Storage Contract belongs to!" */);
_;
}
// ============== [ BEGIN ] LOTTERY QUICKSORT FUNCTIONS ============== //
/**
* QuickSort and QuickSelect algorithm functionality code.
*
* These algorithms are used to find the lottery winners in
* an array of final random-factored scores.
* As the highest-scorers win, we need to sort an array to
* identify them.
*
* For this task, we use QuickSelect to partition array into
* winner part (elements with score larger than X, where X is
* n-th largest element, where n is number of winners),
* and others (non-winners), who are ignored to save computation
* power.
* Then we sort the winner part only, using QuickSort, and
* distribute prizes to winners accordingly.
*/
// Swap function used in QuickSort algorithms.
//
function QSort_swap( FinalScore[] memory list,
uint a, uint b )
internal pure
{
FinalScore memory tmp = list[ a ];
list[ a ] = list[ b ];
list[ b ] = tmp;
}
// Standard Hoare's partition scheme function, used for both
// QuickSort and QuickSelect.
//
function QSort_partition(
FinalScore[] memory list,
int lo, int hi )
internal pure
returns( int newPivotIndex )
{
uint64 pivot = list[ uint( hi + lo ) / 2 ].score;
int i = lo - 1;
int j = hi + 1;
while( true )
{
do {
i++;
} while( list[ uint( i ) ].score > pivot ) ;
do {
j--;
} while( list[ uint( j ) ].score < pivot ) ;
if( i >= j )
return j;
QSort_swap( list, uint( i ), uint( j ) );
}
}
// QuickSelect's Lomuto partition scheme.
//
function QSort_LomutoPartition(
FinalScore[] memory list,
uint left, uint right, uint pivotIndex )
internal pure
returns( uint newPivotIndex )
{
uint pivotValue = list[ pivotIndex ].score;
QSort_swap( list, pivotIndex, right ); // Move pivot to end
uint storeIndex = left;
for( uint i = left; i < right; i++ )
{
if( list[ i ].score > pivotValue ) {
QSort_swap( list, storeIndex, i );
storeIndex++;
}
}
// Move pivot to its final place, and return the pivot's index.
QSort_swap( list, right, storeIndex );
return storeIndex;
}
// QuickSelect algorithm (iterative).
//
function QSort_QuickSelect(
FinalScore[] memory list,
int left, int right, int k )
internal pure
returns( int indexOfK )
{
while( true ) {
if( left == right )
return left;
int pivotIndex = int( QSort_LomutoPartition( list,
uint(left), uint(right), uint(right) ) );
if( k == pivotIndex )
return k;
else if( k < pivotIndex )
right = pivotIndex - 1;
else
left = pivotIndex + 1;
}
}
// Standard QuickSort function.
//
function QSort_QuickSort(
FinalScore[] memory list,
int lo, int hi )
internal pure
{
if( lo < hi ) {
int p = QSort_partition( list, lo, hi );
QSort_QuickSort( list, lo, p );
QSort_QuickSort( list, p + 1, hi );
}
}
// ============== [ END ] LOTTERY QUICKSORT FUNCTIONS ============== //
// ------------ Ending Stage - Winner Selection Algorithm ------------ //
/**
* Compute the individual player score factors for a holder.
* Function split from the below one (ending_Stage_2), to avoid
* "Stack too Deep" errors.
*/
function computeHolderIndividualScores(
WinnerAlgorithmConfig memory cfg,
MinMaxHolderScores memory minMax,
HolderData memory hdata )
internal pure
returns( int individualScore )
{
// Normalize the scores, by subtracting minimum and dividing
// by maximum, to get the score values specified in cfg.
// Use precision of 100, then round.
//
// Notice that we're using int arithmetics, so division
// truncates. That's why we use PRECISION, to simulate
// rounding.
//
// This formula is better explained in example.
// In this example, we use variable abbreviations defined
// below, on formula's right side comments.
//
// Say, values are these in our example:
// e = 4, eMin = 1, eMax = 8, MS = 5, P = 10.
//
// So, let's calculate the score using the formula:
// ( ( ( (4 - 1) * 10 * 5 ) / (8 - 1) ) + (10 / 2) ) / 10 =
// ( ( ( 3 * 10 * 5 ) / 7 ) + 5 ) / 10 =
// ( ( 150 / 7 ) + 5 ) / 10 =
// ( ( 150 / 7 ) + 5 ) / 10 =
// ( 20 + 5 ) / 10 =
// 25 / 10 =
// [ 2.5 ] = 2
//
// So, with truncation, we see that for e = 4, the score
// is 2 out of 5 maximum.
// That's because the minimum ether contributed was 1, and
// maximum was 8.
// So, 4 stays below the middle, and gets a nicely rounded
// score of 2.
// Compute etherContributed.
int score_etherContributed = ( (
( int( hdata.etherContributed - // e
minMax.holderScore_etherContributed_min ) // eMin
* PRECISION * cfg.maxPlayerScore_etherContributed )// P * MS
/ int( minMax.holderScore_etherContributed_max - // eMax
minMax.holderScore_etherContributed_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Compute timeFactors.
int score_timeFactors = ( (
( int( hdata.timeFactors - // e
minMax.holderScore_timeFactors_min ) // eMin
* PRECISION * cfg.maxPlayerScore_timeFactor ) // P * MS
/ int( minMax.holderScore_timeFactors_max - // eMax
minMax.holderScore_timeFactors_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Compute tokenBalance.
int score_tokenBalance = ( (
( int( hdata.tokenBalance - // e
minMax.holderScore_tokenBalance_min ) // eMin
* PRECISION * cfg.maxPlayerScore_tokenHoldingAmount )
/ int( minMax.holderScore_tokenBalance_max - // eMax
minMax.holderScore_tokenBalance_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Return the accumulated individual score (excluding referrees).
return score_etherContributed + score_timeFactors +
score_tokenBalance;
}
/**
* Compute the unified Referree-Score of a player, who's got
* the accumulated factor-scores of all his referrees in his
* holderData structure.
*
* @param individualToReferralRatio - an int value, computed
* before starting the winner score computation loop, in
* the ending_Stage_2 initial part, to save computation
* time later.
* This is the ratio of the maximum available referral score,
* to the maximum available individual score, as defined in
* the config (for example, if max.ref.score is 20, and
* max.ind.score is 40, then the ratio is 20/40 = 0.5).
*
* We use this ratio to transform the computed accumulated
* referree individual scores to the standard referrer's
* score, by multiplying by that ratio.
*/
function computeReferreeScoresForHolder(
int individualToReferralRatio,
WinnerAlgorithmConfig memory cfg,
MinMaxReferralScores memory minMax,
HolderData memory hdata )
internal pure
returns( int unifiedReferreeScore )
{
// If number of referrees of this HODLer is Zero, then
// his referree score is also zero.
if( hdata.referreeCount == 0 )
return 0;
// Now, compute the Referree's Accumulated Scores.
//
// Here we use the same formula as when computing individual
// scores (in the function above), but we use referree parts
// instead.
// Compute etherContributed.
int referreeScore_etherContributed = ( (
( int( hdata.referree_etherContributed -
minMax.referralScore_etherContributed_min )
* PRECISION * cfg.maxPlayerScore_etherContributed )
/ int( minMax.referralScore_etherContributed_max -
minMax.referralScore_etherContributed_min )
) );
// Compute timeFactors.
int referreeScore_timeFactors = ( (
( int( hdata.referree_timeFactors -
minMax.referralScore_timeFactors_min )
* PRECISION * cfg.maxPlayerScore_timeFactor )
/ int( minMax.referralScore_timeFactors_max -
minMax.referralScore_timeFactors_min )
) );
// Compute tokenBalance.
int referreeScore_tokenBalance = ( (
( int( hdata.referree_tokenBalance -
minMax.referralScore_tokenBalance_min )
* PRECISION * cfg.maxPlayerScore_tokenHoldingAmount )
/ int( minMax.referralScore_tokenBalance_max -
minMax.referralScore_tokenBalance_min )
) );
// Accumulate 'em all !
// Then, multiply it by the ratio of all individual max scores
// (maxPlayerScore_etherContributed, timeFactor, tokenBalance),
// to the maxPlayerScore_refferalBonus.
// Use the same precision.
unifiedReferreeScore = int( ( (
( ( referreeScore_etherContributed +
referreeScore_timeFactors +
referreeScore_tokenBalance ) + (PRECISION / 2)
) / PRECISION
) * individualToReferralRatio
) / PRECISION );
}
/**
* Update Min & Max values for individual holder scores.
*/
function priv_updateMinMaxScores_individual(
MinMaxHolderScores memory minMax,
int40 _etherContributed,
int40 _timeFactors,
int40 _tokenBalance )
internal
pure
{
// etherContributed:
if( _etherContributed >
minMax.holderScore_etherContributed_max )
minMax.holderScore_etherContributed_max =
_etherContributed;
if( _etherContributed <
minMax.holderScore_etherContributed_min )
minMax.holderScore_etherContributed_min =
_etherContributed;
// timeFactors:
if( _timeFactors >
minMax.holderScore_timeFactors_max )
minMax.holderScore_timeFactors_max =
_timeFactors;
if( _timeFactors <
minMax.holderScore_timeFactors_min )
minMax.holderScore_timeFactors_min =
_timeFactors;
// tokenBalance:
if( _tokenBalance >
minMax.holderScore_tokenBalance_max )
minMax.holderScore_tokenBalance_max =
_tokenBalance;
if( _tokenBalance <
minMax.holderScore_tokenBalance_min )
minMax.holderScore_tokenBalance_min =
_tokenBalance;
}
/**
* Update Min & Max values for referral scores.
*/
function priv_updateMinMaxScores_referral(
MinMaxReferralScores memory minMax,
int40 _etherContributed,
int40 _timeFactors,
int40 _tokenBalance )
internal
pure
{
// etherContributed:
if( _etherContributed >
minMax.referralScore_etherContributed_max )
minMax.referralScore_etherContributed_max =
_etherContributed;
if( _etherContributed <
minMax.referralScore_etherContributed_min )
minMax.referralScore_etherContributed_min =
_etherContributed;
// timeFactors:
if( _timeFactors >
minMax.referralScore_timeFactors_max )
minMax.referralScore_timeFactors_max =
_timeFactors;
if( _timeFactors <
minMax.referralScore_timeFactors_min )
minMax.referralScore_timeFactors_min =
_timeFactors;
// tokenBalance:
if( _tokenBalance >
minMax.referralScore_tokenBalance_max )
minMax.referralScore_tokenBalance_max =
_tokenBalance;
if( _tokenBalance <
minMax.referralScore_tokenBalance_min )
minMax.referralScore_tokenBalance_min =
_tokenBalance;
}
// =================== PUBLIC FUNCTIONS =================== //
/**
* Update current holder's score with given change values, and
* Propagate the holder's current transfer's score changes
* through the referral chain, updating every parent referrer's
* accumulated referree scores, until the ROOT_REFERRER or zero
* address referrer is encountered.
*/
function updateAndPropagateScoreChanges(
address holder,
int __etherContributed_change,
int __timeFactors_change,
int __tokenBalance_change )
public
lotteryOnly
{
// Convert the data into shrinked format - leave only
// 4 decimals of Ether precision, and drop the decimal part
// of ULT tokens absolutely.
// Don't change TimeFactors, as it is already adjusted in
// Lottery contract's code.
int40 timeFactors_change = int40( __timeFactors_change );
int40 etherContributed_change = int40(
__etherContributed_change / int(1 ether / 10000) );
int40 tokenBalance_change = int40(
__tokenBalance_change / int(1 ether) );
// Update current holder's score.
holderData[ holder ].etherContributed += etherContributed_change;
holderData[ holder ].timeFactors += timeFactors_change;
holderData[ holder ].tokenBalance += tokenBalance_change;
// Check if scores are exceeding current min/max scores,
// and if so, update the min/max scores.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores;
priv_updateMinMaxScores_individual(
minMaxCpy,
holderData[ holder ].etherContributed,
holderData[ holder ].timeFactors,
holderData[ holder ].tokenBalance
);
// Propagate the score through the referral chain.
// Dive at maximum to the depth of 10, to avoid "Outta Gas"
// errors.
uint depth = 0;
address referrerAddr = holderData[ holder ].referrer;
while( referrerAddr != ROOT_REFERRER &&
referrerAddr != address( 0 ) &&
depth < MAX_REFERRAL_DEPTH )
{
// Update this referrer's accumulated referree scores.
holderData[ referrerAddr ].referree_etherContributed +=
etherContributed_change;
holderData[ referrerAddr ].referree_timeFactors +=
timeFactors_change;
holderData[ referrerAddr ].referree_tokenBalance +=
tokenBalance_change;
// Update MinMax according to this referrer's score.
priv_updateMinMaxScores_referral(
minMaxRefCpy,
holderData[ referrerAddr ].referree_etherContributed,
holderData[ referrerAddr ].referree_timeFactors,
holderData[ referrerAddr ].referree_tokenBalance
);
// Move to the higher-level referrer.
referrerAddr = holderData[ referrerAddr ].referrer;
depth++;
}
// Check if MinMax have changed. If so, update it.
if( keccak256( abi.encode( minMaxCpy ) ) !=
keccak256( abi.encode( minMaxScores ) ) )
minMaxScores = minMaxCpy;
// Check referral part.
if( keccak256( abi.encode( minMaxRefCpy ) ) !=
keccak256( abi.encode( minMaxReferralScores ) ) )
minMaxReferralScores = minMaxRefCpy;
}
/**
* Pure function to fix an in-memory copy of MinMaxScores,
* by changing equal min-max pairs to differ by one.
* This is needed to avoid division-by-zero in some calculations.
*/
function priv_fixMinMaxIfEqual(
MinMaxHolderScores memory minMaxCpy,
MinMaxReferralScores memory minMaxRefCpy )
internal
pure
{
// Individual part
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
// Referral part
if( minMaxRefCpy.referralScore_etherContributed_min ==
minMaxRefCpy.referralScore_etherContributed_max )
minMaxRefCpy.referralScore_etherContributed_max =
minMaxRefCpy.referralScore_etherContributed_min + 1;
if( minMaxRefCpy.referralScore_timeFactors_min ==
minMaxRefCpy.referralScore_timeFactors_max )
minMaxRefCpy.referralScore_timeFactors_max =
minMaxRefCpy.referralScore_timeFactors_min + 1;
if( minMaxRefCpy.referralScore_tokenBalance_min ==
minMaxRefCpy.referralScore_tokenBalance_max )
minMaxRefCpy.referralScore_tokenBalance_max =
minMaxRefCpy.referralScore_tokenBalance_min + 1;
}
/**
* Function executes the Lottery Winner Selection Algorithm,
* and writes the final, sorted array, containing winner rankings.
*
* This function is called from the Lottery's Mining Stage Step 2,
*
* This is the final function that lottery performs actively -
* and arguably the most important - because it determines
* lottery winners through Winner Selection Algorithm.
*
* The random seed must be already set, before calling this function.
*/
function executeWinnerSelectionAlgorithm()
public
lotteryOnly
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is MinedWinnerSelection!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.MinedWinnerSelection)/*,
"Algorithm cannot be performed on current Algo-Type!" */);
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we block.timestamp have to do, is loop through holder array, and
// compute randomized final scores for every holder, into
// the Final Score array.
// Declare the Final Score array - computed for all holders.
uint ARRLEN =
( holders.length > MINEDSELECTION_MAX_NUMBER_OF_HOLDERS ?
MINEDSELECTION_MAX_NUMBER_OF_HOLDERS : holders.length );
FinalScore[] memory finalScores = new FinalScore[] ( ARRLEN );
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5/*, "scorePart" */== 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores;
priv_fixMinMaxIfEqual( minMaxCpy, minMaxRefCpy );
// Loop through all the holders.
for( uint i = 0; i < ARRLEN; i++ )
{
// Fetch the needed holder data to in-memory hdata variable,
// to save gas on score part computing functions.
HolderData memory hdata;
// Slot 1:
hdata.etherContributed =
holderData[ holders[ i ] ].etherContributed;
hdata.timeFactors =
holderData[ holders[ i ] ].timeFactors;
hdata.tokenBalance =
holderData[ holders[ i ] ].tokenBalance;
hdata.referreeCount =
holderData[ holders[ i ] ].referreeCount;
// Slot 2:
hdata.referree_etherContributed =
holderData[ holders[ i ] ].referree_etherContributed;
hdata.referree_timeFactors =
holderData[ holders[ i ] ].referree_timeFactors;
hdata.referree_tokenBalance =
holderData[ holders[ i ] ].referree_tokenBalance;
hdata.bonusScore =
holderData[ holders[ i ] ].bonusScore;
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
hdata.bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, hdata )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxRefCpy, hdata );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Multiply the score by the Random Modulo Adjustment
// Factor, to get fairer ratio of random-to-determined data.
totalPlayerScore = ( totalPlayerScore * SCORE_RAND_FACT ) /
( PRECISION );
// Score is computed!
// Now, randomize it, and add to Final Scores Array.
// We use keccak to generate a random number from random seed,
// using holder's address as a nonce.
uint modulizedRandomNumber = uint(
keccak256( abi.encodePacked( randomSeed, holders[ i ] ) )
) % RANDOM_MODULO;
// Add the random number, to introduce the random factor.
// Ratio of (current) totalPlayerScore to modulizedRandomNumber
// is the same as ratio of randRatio_scorePart to
// randRatio_randPart.
uint endScore = uint( totalPlayerScore ) + modulizedRandomNumber;
// Finally, set this holder's final score data.
finalScores[ i ].addr = holders[ i ];
finalScores[ i ].holderIndex = uint16( i );
finalScores[ i ].score = uint64( endScore );
}
// All final scores are block.timestamp computed.
// Sort the array, to find out the highest scores!
// Firstly, partition an array to only work on top K scores,
// where K is the number of winners.
// There can be a rare case where specified number of winners is
// more than lottery token holders. We got that covered.
require( finalScores.length > 0 );
uint K = cfg.winnerCount - 1;
if( K > finalScores.length-1 )
K = finalScores.length-1; // Must be THE LAST ELEMENT's INDEX.
// Use QuickSelect to do this.
QSort_QuickSelect( finalScores, 0,
int( finalScores.length - 1 ), int( K ) );
// Now, QuickSort only the first K items, because the rest
// item scores are not high enough to become winners.
QSort_QuickSort( finalScores, 0, int( K ) );
// Now, the winner array is sorted, with the highest scores
// sitting at the first positions!
// Let's set up the winner indexes array, where we'll store
// the winners' indexes in the holders array.
// So, if this array is [8, 2, 3], that means that
// Winner #1 is holders[8], winner #2 is holders[2], and
// winner #3 is holders[3].
// Set the Number Of Winners variable.
numberOfWinners = uint16( K + 1 );
// Now, we can loop through the first numberOfWinners elements, to set
// the holder indexes!
// Loop through 16 elements at a time, to fill the structs.
for( uint offset = 0; offset < numberOfWinners; offset += 16 )
{
WinnerIndexStruct memory windStruct;
uint loopStop = ( offset + 16 > numberOfWinners ?
numberOfWinners : offset + 16 );
for( uint i = offset; i < loopStop; i++ )
{
windStruct.indexes[ i - offset ] =finalScores[ i ].holderIndex;
}
// Push this block.timestamp-filled struct to the storage array!
sortedWinnerIndexes.push( windStruct );
}
// That's it! We're done!
algorithmCompleted = true;
}
/**
* Add a holder to holders array.
* @param holder - address of a holder to add.
*/
function addHolder( address holder )
public
lotteryOnly
{
// Add it to list, and set index in the mapping.
holders.push( holder );
holderIndexes[ holder ] = holders.length - 1;
}
/**
* Removes the holder 'sender' from the Holders Array.
* However, this holder's HolderData structure persists!
*
* Notice that no index validity checks are performed, so, if
* 'sender' is not present in "holderIndexes" mapping, this
* function will remove the 0th holder instead!
* This is not a problem for us, because Lottery calls this
* function only when it's absolutely certain that 'sender' is
* present in the holders array.
*
* @param sender - address of a holder to remove.
* Named 'sender', because when token sender sends away all
* his tokens, he must then be removed from holders array.
*/
function removeHolder( address sender )
public
lotteryOnly
{
// Get index of the sender address in the holders array.
uint index = holderIndexes[ sender ];
// Remove the sender from array, by copying last element's
// value into the index'th element, where sender was before.
holders[ index ] = holders[ holders.length - 1 ];
// Remove the last element of array, which we've just copied.
holders.pop();
// Update indexes: remove the sender's index from the mapping,
// and change the previoulsy-last element's index to the
// one where we copied it - where sender was before.
delete holderIndexes[ sender ];
holderIndexes[ holders[ index ] ] = index;
}
/**
* Get holder array length.
*/
function getHolderCount()
public view
returns( uint )
{
return holders.length;
}
/**
* Generate a referral ID for a token holder.
* Referral ID is used to refer other wallets into playing our
* lottery.
* - Referrer gets bonus points for every wallet that bought
* lottery tokens and specified his referral ID.
* - Referrees (wallets who got referred by registering a valid
* referral ID, corresponding to some referrer), get some
* bonus points for specifying (registering) a referral ID.
*
* Referral ID is a uint256 number, which is generated by
* keccak256'ing the holder's address, holder's current
* token ballance, and current time.
*/
function generateReferralID( address holder )
public
lotteryOnly
returns( uint256 referralID )
{
// Check if holder has some tokens, and doesn't
// have his own referral ID yet.
require( holderData[ holder ].tokenBalance != 0/*,
"holder doesn't have any lottery tokens!" */);
require( holderData[ holder ].referralID == 0/*,
"Holder already has a referral ID!" */);
// Generate a referral ID with keccak.
uint256 refID = uint256( keccak256( abi.encodePacked(
holder, holderData[ holder ].tokenBalance, block.timestamp ) ) );
// Specify the ID as current ID of this holder.
holderData[ holder ].referralID = refID;
// If this holder wasn't referred by anyone (his referrer is
// not set), and he's block.timestamp generated his own ID, he won't
// be able to register as a referree of someone else
// from block.timestamp on.
// This is done to prevent circular dependency in referrals.
// Do it by setting a referrer to ROOT_REFERRER address,
// which is an invalid address (address(1)).
if( holderData[ holder ].referrer == address( 0 ) )
holderData[ holder ].referrer = ROOT_REFERRER;
// Create a new referrer with this ID.
referrers[ refID ] = holder;
return refID;
}
/**
* Register a referral for a token holder, using a valid
* referral ID got from a referrer.
* This function is called by a referree, who obtained a
* valid referral ID from some referrer, who previously
* generated it using generateReferralID().
*
* You can only register a referral once!
* When you do so, you get bonus referral points!
*/
function registerReferral(
address holder,
int16 referralRegisteringBonus,
uint256 referralID )
public
lotteryOnly
returns( address _referrerAddress )
{
// Check if this holder has some tokens, and if he hasn't
// registered a referral yet.
require( holderData[ holder ].tokenBalance != 0/*,
"holder doesn't have any lottery tokens!" */);
require( holderData[ holder ].referrer == address( 0 )/*,
"holder already has registered a referral!" */);
// Create a local memory copy of minMaxReferralScores.
MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores;
// Get the referrer's address from his ID, and specify
// it as a referrer of holder.
holderData[ holder ].referrer = referrers[ referralID ];
// Bonus points are added to this holder's score for
// registering a referral!
holderData[ holder ].bonusScore = referralRegisteringBonus;
// Increment number of referrees for every parent referrer,
// by traversing a referral tree child->parent way.
address referrerAddr = holderData[ holder ].referrer;
// Set the return value.
_referrerAddress = referrerAddr;
// Traverse a tree.
while( referrerAddr != ROOT_REFERRER &&
referrerAddr != address( 0 ) )
{
// Increment referree count for this referrrer.
holderData[ referrerAddr ].referreeCount++;
// Update the Referrer Scores of the referrer, adding this
// referree's scores to it's current values.
holderData[ referrerAddr ].referree_etherContributed +=
holderData[ holder ].etherContributed;
holderData[ referrerAddr ].referree_timeFactors +=
holderData[ holder ].timeFactors;
holderData[ referrerAddr ].referree_tokenBalance +=
holderData[ holder ].tokenBalance;
// Update MinMax according to this referrer's score.
priv_updateMinMaxScores_referral(
minMaxRefCpy,
holderData[ referrerAddr ].referree_etherContributed,
holderData[ referrerAddr ].referree_timeFactors,
holderData[ referrerAddr ].referree_tokenBalance
);
// Move to the higher-level referrer.
referrerAddr = holderData[ referrerAddr ].referrer;
}
// Update MinMax Referral Scores if needed.
if( keccak256( abi.encode( minMaxRefCpy ) ) !=
keccak256( abi.encode( minMaxReferralScores ) ) )
minMaxReferralScores = minMaxRefCpy;
return _referrerAddress;
}
/**
* Sets our random seed to some value.
* Should be called from Lottery, after obtaining random seed from
* the Randomness Provider.
*/
function setRandomSeed( uint _seed )
external
lotteryOnly
{
randomSeed = uint64( _seed );
}
/**
* Initialization function.
* Here, we bind our contract to the Lottery contract that
* this Storage belongs to.
* The parent lottery must call this function - hence, we set
* "lottery" to msg.sender.
*
* When this function is called, our contract must be not yet
* initialized - "lottery" address must be Zero!
*
* Here, we also set our Winner Algorithm config, which is a
* subset of LotteryConfig, fitting into 1 storage slot.
*/
function initialize(
WinnerAlgorithmConfig memory _wcfg )
public
{
require( address( lottery ) == address( 0 )/*,
"Storage is already initialized!" */);
// Set the Lottery address (msg.sender can't be zero),
// and thus, set our contract to initialized!
lottery = msg.sender;
// Set the Winner-Algo-Config.
algConfig = _wcfg;
// NOT-NEEDED: Set initial min-max scores: min is INT_MAX.
/*minMaxScores.holderScore_etherContributed_min = int80( 2 ** 78 );
minMaxScores.holderScore_timeFactors_min = int80( 2 ** 78 );
minMaxScores.holderScore_tokenBalance_min = int80( 2 ** 78 );
*/
}
// ==================== Views ==================== //
// Returns the current random seed.
// If the seed hasn't been set yet (or set to 0), returns 0.
//
function getRandomSeed()
external view
returns( uint )
{
return randomSeed;
}
// Check if Winner Selection Algorithm has beed executed.
//
function minedSelection_algorithmAlreadyExecuted()
external view
returns( bool )
{
return algorithmCompleted;
}
/**
* After lottery has completed, this function returns if "addr"
* is one of lottery winners, and the position in winner rankings.
* Function is used to obtain the ranking position before
* calling claimWinnerPrize() on Lottery.
*
* This function should be called off-chain, and then using the
* retrieved data, one can call claimWinnerPrize().
*/
function minedSelection_getWinnerStatus(
address addr )
public view
returns( bool isWinner,
uint32 rankingPosition )
{
// Loop through the whole winner indexes array, trying to
// find if "addr" is one of the winner addresses.
for( uint16 i = 0; i < numberOfWinners; i++ )
{
// Check if holder on this winner ranking's index position
// is addr, if so, good!
uint pos = sortedWinnerIndexes[ i / 16 ].indexes[ i % 16 ];
if( holders[ pos ] == addr )
{
return ( true, i );
}
}
// The "addr" is not a winner.
return ( false, 0 );
}
/**
* Checks if address is on specified winner ranking position.
* Used in Lottery, to check if msg.sender is really the
* winner #rankingPosition, as he claims to be.
*/
function minedSelection_isAddressOnWinnerPosition(
address addr,
uint32 rankingPosition )
external view
returns( bool )
{
if( rankingPosition >= numberOfWinners )
return false;
// Just check if address at "holders" array
// index "sortedWinnerIndexes[ position ]" is really the "addr".
uint pos = sortedWinnerIndexes[ rankingPosition / 16 ]
.indexes[ rankingPosition % 16 ];
return ( holders[ pos ] == addr );
}
/**
* Returns an array of all winner addresses, sorted by their
* ranking position (winner #1 first, #2 second, etc.).
*/
function minedSelection_getAllWinners()
external view
returns( address[] memory )
{
address[] memory winners = new address[] ( numberOfWinners );
for( uint i = 0; i < numberOfWinners; i++ )
{
uint pos = sortedWinnerIndexes[ i / 16 ].indexes[ i % 16 ];
winners[ i ] = holders[ pos ];
}
return winners;
}
/**
* Compute the Lottery Active Stage Score of a token holder.
*
* This function computes the Active Stage (pre-randomization)
* player score, and should generally be used to compute player
* intermediate scores - while lottery is still active or on
* finishing stage, before random random seed is obtained.
*/
function getPlayerActiveStageScore( address holderAddr )
external view
returns( uint playerScore )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Check if holderAddr is a holder at all!
if( holders[ holderIndexes[ holderAddr ] ] != holderAddr )
return 0;
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores;
priv_fixMinMaxIfEqual( minMaxCpy, minMaxRefCpy );
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
holderData[ holderAddr ].bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, holderData[ holderAddr ] )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxRefCpy, holderData[ holderAddr ] );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Return the score!
return uint( totalPlayerScore );
}
/**
* Internal sub-procedure of the function below, used to obtain
* a final, randomized score of a Single Holder.
*/
function priv_getSingleHolderScore(
address hold3r,
int individualToReferralRatio,
int maxAvailablePlayerScore,
int SCORE_RAND_FACT,
WinnerAlgorithmConfig memory cfg,
MinMaxHolderScores memory minMaxCpy,
MinMaxReferralScores memory minMaxRefCpy )
internal view
returns( uint endScore )
{
// Fetch the needed holder data to in-memory hdata variable,
// to save gas on score part computing functions.
HolderData memory hdata;
// Slot 1:
hdata.etherContributed =
holderData[ hold3r ].etherContributed;
hdata.timeFactors =
holderData[ hold3r ].timeFactors;
hdata.tokenBalance =
holderData[ hold3r ].tokenBalance;
hdata.referreeCount =
holderData[ hold3r ].referreeCount;
// Slot 2:
hdata.referree_etherContributed =
holderData[ hold3r ].referree_etherContributed;
hdata.referree_timeFactors =
holderData[ hold3r ].referree_timeFactors;
hdata.referree_tokenBalance =
holderData[ hold3r ].referree_tokenBalance;
hdata.bonusScore =
holderData[ hold3r ].bonusScore;
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
hdata.bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, hdata )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxRefCpy, hdata );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Multiply the score by the Random Modulo Adjustment
// Factor, to get fairer ratio of random-to-determined data.
totalPlayerScore = ( totalPlayerScore * SCORE_RAND_FACT ) /
( PRECISION );
// Score is computed!
// Now, randomize it, and add to Final Scores Array.
// We use keccak to generate a random number from random seed,
// using holder's address as a nonce.
uint modulizedRandomNumber = uint(
keccak256( abi.encodePacked( randomSeed, hold3r ) )
) % RANDOM_MODULO;
// Add the random number, to introduce the random factor.
// Ratio of (current) totalPlayerScore to modulizedRandomNumber
// is the same as ratio of randRatio_scorePart to
// randRatio_randPart.
return uint( totalPlayerScore ) + modulizedRandomNumber;
}
/**
* Winner Self-Validation algo-type main function.
* Here, we compute scores for all lottery holders iteratively
* in O(n) time, and thus get the winner ranking position of
* the holder in question.
*
* This function performs essentialy the same steps as the
* Mined-variant (executeWinnerSelectionAlgorithm), but doesn't
* write anything to blockchain.
*
* @param holderAddr - address of a holder whose rank we want to find.
*/
function winnerSelfValidation_getWinnerStatus(
address holderAddr )
internal view
returns( bool isWinner, uint rankingPosition )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is WinnerSelfValidation!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.WinnerSelfValidation)/*,
"Algorithm cannot be performed on current Algo-Type!" */);
// Check if holderAddr is a holder at all!
require( holders[ holderIndexes[ holderAddr ] ] == holderAddr/*,
"holderAddr is not a lottery token holder!" */);
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we block.timestamp have to do, is loop through holder array, and
// compute randomized final scores for every holder.
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5/*, "scorePart" */== 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores;
priv_fixMinMaxIfEqual( minMaxCpy, minMaxRefCpy );
// How many holders had higher scores than "holderAddr".
// Used to obtain the final winner rank of "holderAddr".
uint numOfHoldersHigherThan = 0;
// The final (randomized) score of "holderAddr".
uint holderAddrsFinalScore = priv_getSingleHolderScore(
holderAddr,
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy, minMaxRefCpy );
// Index of holderAddr.
uint holderAddrIndex = holderIndexes[ holderAddr ];
// Loop through all the allowed holders.
for( uint i = 0;
i < ( holders.length < SELFVALIDATION_MAX_NUMBER_OF_HOLDERS ?
holders.length : SELFVALIDATION_MAX_NUMBER_OF_HOLDERS );
i++ )
{
// Skip the holderAddr's index.
if( i == holderAddrIndex )
continue;
// Compute the score using helper function.
uint endScore = priv_getSingleHolderScore(
holders[ i ],
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy, minMaxRefCpy );
// Check if score is higher than HolderAddr's, and if so, check.
if( endScore > holderAddrsFinalScore )
numOfHoldersHigherThan++;
}
// All scores are checked!
// Now, we can obtain holderAddr's winner rank based on how
// many scores were above holderAddr's score!
isWinner = ( numOfHoldersHigherThan < cfg.winnerCount );
rankingPosition = numOfHoldersHigherThan;
}
/**
* Rolled-Randomness algo-type main function.
* Here, we only compute the score of the holder in question,
* and compare it to maximum-available final score, divided
* by no-of-winners.
*
* @param holderAddr - address of a holder whose rank we want to find.
*/
function rolledRandomness_getWinnerStatus(
address holderAddr )
internal view
returns( bool isWinner, uint rankingPosition )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is RolledRandomness!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.RolledRandomness)/*,
"Algorithm cannot be performed on current Algo-Type!" */);
// Check if holderAddr is a holder at all!
require( holders[ holderIndexes[ holderAddr ] ] == holderAddr/*,
"holderAddr is not a lottery token holder!" */);
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we block.timestamp have to do, is loop through holder array, and
// compute randomized final scores for every holder.
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5, "scorePart" == 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
MinMaxReferralScores memory minMaxRefCpy = minMaxReferralScores;
priv_fixMinMaxIfEqual( minMaxCpy, minMaxRefCpy );
// The final (randomized) score of "holderAddr".
uint holderAddrsFinalScore = priv_getSingleHolderScore(
holderAddr,
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy, minMaxRefCpy );
// Now, compute the Max-Final-Random Score, divide it
// by the Holder Count, and get the ranking by placing this
// holder's score in it's corresponding part.
//
// In this approach, we assume linear randomness distribution.
// In practice, distribution might be a bit different, but this
// approach is the most efficient.
//
// Max-Final-Score (randomized) is the highest available score
// that can be achieved, and is made by adding together the
// maximum availabe Player Score Part and maximum available
// Random Part (equals RANDOM_MODULO).
// These parts have a ratio equal to config-specified
// randRatio_scorePart to randRatio_randPart.
//
// So, if player's active stage's score is low (1), but rand-part
// in ratio is huge, then the score is mostly random, so
// maxFinalScore is close to the RANDOM_MODULO - maximum random
// value that can be rolled.
//
// If, however, we use 1:1 playerScore-to-Random Ratio, then
// playerScore and RandomScore make up equal parts of end score,
// so the maxFinalScore is actually two times larger than
// RANDOM_MODULO, so player needs to score more
// player-points to get larger prizes.
//
// In default configuration, playerScore-to-random ratio is 1:3,
// so there's a good randomness factor, so even the low-scoring
// players can reasonably hope to get larger prizes, but
// the higher is player's active stage score, the more
// chances of scoring a high final score a player gets, with
// the higher-end of player scores basically guaranteeing
// themselves a specific prize amount, if winnerCount is
// big enough to overlap.
int maxRandomPart = int( RANDOM_MODULO - 1 );
int maxPlayerScorePart = ( SCORE_RAND_FACT * maxAvailablePlayerScore )
/ PRECISION;
uint maxFinalScore = uint( maxRandomPart + maxPlayerScorePart );
// Compute the amount that single-holder's virtual part
// might take up in the max-final score.
uint singleHolderPart = maxFinalScore / holders.length;
// Now, compute how many single-holder-parts are there in
// this holder's score.
uint holderAddrScorePartCount = holderAddrsFinalScore /
singleHolderPart;
// The ranking is that number, minus holders length.
// If very high score is scored, default to position 0 (highest).
rankingPosition = (
holderAddrScorePartCount < holders.length ?
holders.length - holderAddrScorePartCount : 0
);
isWinner = ( rankingPosition < cfg.winnerCount );
}
/**
* Genericized, algorithm type-dependent getWinnerStatus function.
*/
function getWinnerStatus(
address addr )
external view
returns( bool isWinner, uint32 rankingPosition )
{
bool _isW;
uint _rp;
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.RolledRandomness) )
{
(_isW, _rp) = rolledRandomness_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.WinnerSelfValidation) )
{
(_isW, _rp) = winnerSelfValidation_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.MinedWinnerSelection) )
{
(_isW, _rp) = minedSelection_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
}
}
interface IMainUniLotteryPool
{
function isLotteryOngoing( address lotAddr )
external view returns( bool );
function scheduledCallback( uint256 requestID )
external;
function onLotteryCallbackPriceExceedingGivenFunds(
address lottery, uint currentRequestPrice,
uint poolGivenPastRequestPrice )
external returns( bool );
}
interface ILottery
{
function finish_randomnessProviderCallback(
uint256 randomSeed, uint256 requestID ) external;
}
contract UniLotteryStorageFactory
{
// The Pool Address.
address payable poolAddress;
// The Delegate Logic contract, containing all code for
// all LotteryStorage contracts to be deployed.
address immutable public delegateContract;
// Pool-Only modifier.
modifier poolOnly
{
require( msg.sender == poolAddress/*,
"Function can only be called by the Main Pool!" */);
_;
}
// Constructor.
// Deploy the Delegate Contract here.
//
constructor()
{
delegateContract = address( new LotteryStorage() );
}
// Initialization function.
// Set the poolAddress as msg.sender, and lock it.
function initialize()
external
{
require( poolAddress == address( 0 )/*,
"Initialization has already finished!" */);
// Set the Pool's Address.
poolAddress = msg.sender;
}
/**
* Deploy a new Lottery Storage Stub, to be used by it's corresponding
* Lottery Stub, which will be created later, passing this Storage
* we create here.
* @return newStorage - the Lottery Storage Stub contract just deployed.
*/
function createNewStorage()
public
poolOnly
returns( address newStorage )
{
LotteryStorageStub stub = new LotteryStorageStub();
stub.stub_construct( delegateContract );
return address( stub );
}
}
abstract contract Context {
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;
}
}
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);
}
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;
}
}
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 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 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 virtual {
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 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 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"));
}
}
abstract contract solcChecker {
/* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) virtual external;
}
interface ProvableI {
function cbAddress() external returns (address _cbAddress);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function getPrice(string calldata _datasource) external returns (uint _dsprice);
function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash);
function getPrice(string calldata _datasource, uint _gasLimit) external returns (uint _dsprice);
function queryN(uint _timestamp, string calldata _datasource, bytes calldata _argN) external payable returns (bytes32 _id);
function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id);
function query2(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id);
}
interface OracleAddrResolverI {
function getAddress() external returns (address _address);
}
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory _buf, uint _capacity) internal pure {
uint capacity = _capacity;
if (capacity % 32 != 0) {
capacity += 32 - (capacity % 32);
}
_buf.capacity = capacity; // Allocate space for the buffer data
assembly {
let ptr := mload(0x40)
mstore(_buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory _buf, uint _capacity) private pure {
bytes memory oldbuf = _buf.buf;
init(_buf, _capacity);
append(_buf, oldbuf);
}
function max(uint _a, uint _b) private pure returns (uint _max) {
if (_a > _b) {
return _a;
}
return _b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return _buffer The original buffer.
*
*/
function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) {
if (_data.length + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _data.length) * 2);
}
uint dest;
uint src;
uint len = _data.length;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length)
mstore(bufptr, add(buflen, mload(_data))) // Update buffer length
src := add(_data, 32)
}
for(; len >= 32; len -= 32) { // Copy word-length chunks while possible
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return _buf;
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
*
*/
function append(buffer memory _buf, uint8 _data) internal pure {
if (_buf.buf.length + 1 > _buf.capacity) {
resize(_buf, _buf.capacity * 2);
}
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length)
mstore8(dest, _data)
mstore(bufptr, add(buflen, 1)) // Update buffer length
}
}
/**
*
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param _buf The buffer to append to.
* @param _data The data to append.
* @return _buffer The original buffer.
*
*/
function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) {
if (_len + _buf.buf.length > _buf.capacity) {
resize(_buf, max(_buf.capacity, _len) * 2);
}
uint mask = 256 ** _len - 1;
assembly {
let bufptr := mload(_buf) // Memory address of the buffer data
let buflen := mload(bufptr) // Length of existing buffer data
let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len
mstore(dest, or(and(mload(dest), not(mask)), _data))
mstore(bufptr, add(buflen, _len)) // Update buffer length
}
return _buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure {
if (_value <= 23) {
_buf.append(uint8((_major << 5) | _value));
} else if (_value <= 0xFF) {
_buf.append(uint8((_major << 5) | 24));
_buf.appendInt(_value, 1);
} else if (_value <= 0xFFFF) {
_buf.append(uint8((_major << 5) | 25));
_buf.appendInt(_value, 2);
} else if (_value <= 0xFFFFFFFF) {
_buf.append(uint8((_major << 5) | 26));
_buf.appendInt(_value, 4);
} else if (_value <= 0xFFFFFFFFFFFFFFFF) {
_buf.append(uint8((_major << 5) | 27));
_buf.appendInt(_value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure {
_buf.append(uint8((_major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure {
encodeType(_buf, MAJOR_TYPE_INT, _value);
}
function encodeInt(Buffer.buffer memory _buf, int _value) internal pure {
if (_value >= 0) {
encodeType(_buf, MAJOR_TYPE_INT, uint(_value));
} else {
encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value));
}
}
function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure {
encodeType(_buf, MAJOR_TYPE_BYTES, _value.length);
_buf.append(_value);
}
function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure {
encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length);
_buf.append(bytes(_value));
}
function startArray(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory _buf) internal pure {
encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE);
}
}
contract usingProvable {
using CBOR for Buffer.buffer;
ProvableI provable;
OracleAddrResolverI OAR;
uint constant day = 60 * 60 * 24;
uint constant week = 60 * 60 * 24 * 7;
uint constant month = 60 * 60 * 24 * 30;
byte constant proofType_NONE = 0x00;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
byte constant proofType_Android = 0x40;
byte constant proofType_TLSNotary = 0x10;
string provable_network_name;
uint8 constant networkID_auto = 0;
uint8 constant networkID_morden = 2;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_consensys = 161;
mapping(bytes32 => bytes32) provable_randomDS_args;
mapping(bytes32 => bool) provable_randomDS_sessionKeysHashVerified;
modifier provableAPI {
if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) {
provable_setNetwork(networkID_auto);
}
if (address(provable) != OAR.getAddress()) {
provable = ProvableI(OAR.getAddress());
}
_;
}
modifier provable_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) {
// RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1)));
bool proofVerified = provable_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), provable_getNetworkName());
require(proofVerified);
_;
}
function provable_setNetwork(uint8 _networkID) internal returns (bool _networkSet) {
_networkID; // NOTE: Silence the warning and remain backwards compatible
return provable_setNetwork();
}
function provable_setNetworkName(string memory _network_name) internal {
provable_network_name = _network_name;
}
function provable_getNetworkName() internal view returns (string memory _networkName) {
return provable_network_name;
}
function provable_setNetwork() internal returns (bool _networkSet) {
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet
OAR = OracleAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
provable_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet
OAR = OracleAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
provable_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet
OAR = OracleAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
provable_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet
OAR = OracleAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
provable_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet
OAR = OracleAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41);
provable_setNetworkName("eth_goerli");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge
OAR = OracleAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide
OAR = OracleAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity
OAR = OracleAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
/**
* @dev The following `__callback` functions are just placeholders ideally
* meant to be defined in child contract when proofs are used.
* The function bodies simply silence compiler warnings.
*/
function __callback(bytes32 _myid, string memory _result) virtual public {
__callback(_myid, _result, new bytes(0));
}
function __callback(bytes32 _myid, string memory _result, bytes memory _proof) virtual public {
_myid; _result; _proof;
provable_randomDS_args[bytes32(0)] = bytes32(0);
}
function provable_getPrice(string memory _datasource) provableAPI internal returns (uint _queryPrice) {
return provable.getPrice(_datasource);
}
function provable_getPrice(string memory _datasource, uint _gasLimit) provableAPI internal returns (uint _queryPrice) {
return provable.getPrice(_datasource, _gasLimit);
}
function provable_query(string memory _datasource, string memory _arg) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return provable.query{value: price}(0, _datasource, _arg);
}
function provable_query(uint _timestamp, string memory _datasource, string memory _arg) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return provable.query{value: price}(_timestamp, _datasource, _arg);
}
function provable_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource,_gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return provable.query_withGasLimit{value: price}(_timestamp, _datasource, _arg, _gasLimit);
}
function provable_query(string memory _datasource, string memory _arg, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return provable.query_withGasLimit{value: price}(0, _datasource, _arg, _gasLimit);
}
function provable_query(string memory _datasource, string memory _arg1, string memory _arg2) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return provable.query2{value: price}(0, _datasource, _arg1, _arg2);
}
function provable_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
return provable.query2{value: price}(_timestamp, _datasource, _arg1, _arg2);
}
function provable_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return provable.query2_withGasLimit{value: price}(_timestamp, _datasource, _arg1, _arg2, _gasLimit);
}
function provable_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
return provable.query2_withGasLimit{value: price}(0, _datasource, _arg1, _arg2, _gasLimit);
}
function provable_query(string memory _datasource, string[] memory _argN) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return provable.queryN{value: price}(0, _datasource, args);
}
function provable_query(uint _timestamp, string memory _datasource, string[] memory _argN) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return provable.queryN{value: price}(_timestamp, _datasource, args);
}
function provable_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return provable.queryN_withGasLimit{value: price}(_timestamp, _datasource, args, _gasLimit);
}
function provable_query(string memory _datasource, string[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = stra2cbor(_argN);
return provable.queryN_withGasLimit{value: price}(0, _datasource, args, _gasLimit);
}
function provable_query(string memory _datasource, string[1] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[1] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](1);
dynargs[0] = _args[0];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[2] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[2] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[3] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[3] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[4] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[4] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[5] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[5] memory _args) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, string[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
string[] memory dynargs = new string[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[] memory _argN) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return provable.queryN{value: price}(0, _datasource, args);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource);
if (price > 1 ether + tx.gasprice * 200000) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return provable.queryN{value: price}(_timestamp, _datasource, args);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return provable.queryN_withGasLimit{value: price}(_timestamp, _datasource, args, _gasLimit);
}
function provable_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
uint price = provable.getPrice(_datasource, _gasLimit);
if (price > 1 ether + tx.gasprice * _gasLimit) {
return 0; // Unexpectedly high price
}
bytes memory args = ba2cbor(_argN);
return provable.queryN_withGasLimit{value: price}(0, _datasource, args, _gasLimit);
}
function provable_query(string memory _datasource, bytes[1] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = _args[0];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[2] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[3] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[4] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[5] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_timestamp, _datasource, dynargs);
}
function provable_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_timestamp, _datasource, dynargs, _gasLimit);
}
function provable_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) provableAPI internal returns (bytes32 _id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = _args[0];
dynargs[1] = _args[1];
dynargs[2] = _args[2];
dynargs[3] = _args[3];
dynargs[4] = _args[4];
return provable_query(_datasource, dynargs, _gasLimit);
}
function provable_setProof(byte _proofP) provableAPI internal {
return provable.setProofType(_proofP);
}
function provable_cbAddress() provableAPI internal returns (address _callbackAddress) {
return provable.cbAddress();
}
function getCodeSize(address _addr) view internal returns (uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function provable_setCustomGasPrice(uint _gasPrice) provableAPI internal {
return provable.setCustomGasPrice(_gasPrice);
}
function provable_randomDS_getSessionPubKeyHash() provableAPI internal returns (bytes32 _sessionKeyHash) {
return provable.randomDS_getSessionPubKeyHash();
}
function parseAddr(string memory _a) internal pure returns (address _parsedAddress) {
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i = 2; i < 2 + 2 * 20; i += 2) {
iaddr *= 256;
b1 = uint160(uint8(tmp[i]));
b2 = uint160(uint8(tmp[i + 1]));
if ((b1 >= 97) && (b1 <= 102)) {
b1 -= 87;
} else if ((b1 >= 65) && (b1 <= 70)) {
b1 -= 55;
} else if ((b1 >= 48) && (b1 <= 57)) {
b1 -= 48;
}
if ((b2 >= 97) && (b2 <= 102)) {
b2 -= 87;
} else if ((b2 >= 65) && (b2 <= 70)) {
b2 -= 55;
} else if ((b2 >= 48) && (b2 <= 57)) {
b2 -= 48;
}
iaddr += (b1 * 16 + b2);
}
return address(iaddr);
}
function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) {
minLength = b.length;
}
for (uint i = 0; i < minLength; i ++) {
if (a[i] < b[i]) {
return -1;
} else if (a[i] > b[i]) {
return 1;
}
}
if (a.length < b.length) {
return -1;
} else if (a.length > b.length) {
return 1;
} else {
return 0;
}
}
function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if (h.length < 1 || n.length < 1 || (n.length > h.length)) {
return -1;
} else if (h.length > (2 ** 128 - 1)) {
return -1;
} else {
uint subindex = 0;
for (uint i = 0; i < h.length; i++) {
if (h[i] == n[0]) {
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) {
subindex++;
}
if (subindex == n.length) {
return int(i);
}
}
}
return -1;
}
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, "", "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
babcde[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
babcde[k++] = _bb[i];
}
for (i = 0; i < _bc.length; i++) {
babcde[k++] = _bc[i];
}
for (i = 0; i < _bd.length; i++) {
babcde[k++] = _bd[i];
}
for (i = 0; i < _be.length; i++) {
babcde[k++] = _be[i];
}
return string(babcde);
}
function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) {
return safeParseInt(_a, 0);
}
function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
require(!decimals, 'More than one decimal encountered in string!');
decimals = true;
} else {
revert("Non-numeral character encountered in string!");
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function parseInt(string memory _a) internal pure returns (uint _parsedInt) {
return parseInt(_a, 0);
}
function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) {
break;
} else {
_b--;
}
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
decimals = true;
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < _arr.length; i++) {
buf.encodeString(_arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < _arr.length; i++) {
buf.encodeBytes(_arr[i]);
}
buf.endSequence();
return buf.buf;
}
function provable_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) {
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10; // Convert from seconds to ledger timer ticks
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(uint8(_nbytes));
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = provable_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
/*
The following variables can be relaxed.
Check the relaxed random contract at https://github.com/oraclize/ethereum-examples
for an idea on how to override and replace commit hash variables.
*/
mstore(add(unonce, 0x20), xor(blockhash(sub(number(), 1)), xor(coinbase(), timestamp())))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = provable_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
provable_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));
return queryId;
}
function provable_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal {
provable_randomDS_args[_queryId] = _commitment;
}
function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) {
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20);
sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs);
if (address(uint160(uint256(keccak256(_pubkey)))) == signer) {
return true;
} else {
(sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs);
return (address(uint160(uint256(keccak256(_pubkey)))) == signer);
}
}
function provable_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) {
bool sigok;
// Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2);
copyBytes(_proof, _sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1 + 65 + 32);
tosign2[0] = byte(uint8(1)); //role
copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (!sigok) {
return false;
}
// Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1 + 65);
tosign3[0] = 0xFE;
copyBytes(_proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2);
copyBytes(_proof, 3 + 65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
function provable_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) {
// Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) {
return 1;
}
bool proofVerified = provable_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), provable_getNetworkName());
if (!proofVerified) {
return 2;
}
return 0;
}
function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) {
bool match_ = true;
require(_prefix.length == _nRandomBytes);
for (uint256 i = 0; i< _nRandomBytes; i++) {
if (_content[i] != _prefix[i]) {
match_ = false;
}
}
return match_;
}
function provable_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) {
// Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId)
uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32;
bytes memory keyhash = new bytes(32);
copyBytes(_proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) {
return false;
}
bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2);
copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0);
// Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) {
return false;
}
// Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8 + 1 + 32);
copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65;
copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (provable_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match
delete provable_randomDS_args[_queryId];
} else return false;
// Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32 + 8 + 1 + 32);
copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) {
return false;
}
// Verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (!provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) {
provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = provable_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset);
}
return provable_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
*/
function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) {
uint minLength = _length + _toOffset;
require(_to.length >= minLength); // Buffer too small. Should be a better way?
uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint j = 32 + _toOffset;
while (i < (32 + _fromOffset + _length)) {
assembly {
let tmp := mload(add(_from, i))
mstore(add(_to, j), tmp)
}
i += 32;
j += 32;
}
return _to;
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
Duplicate Solidity's ecrecover, but catching the CALL return value
*/
function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) {
/*
We do our own memory management here. Solidity uses memory offset
0x40 to store the current end of memory. We write past it (as
writes are memory extensions), but don't update the offset so
Solidity will reuse it. The memory used here is only needed for
this context.
FIXME: inline assembly can't access return values
*/
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, _hash)
mstore(add(size, 32), _v)
mstore(add(size, 64), _r)
mstore(add(size, 96), _s)
ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code.
addr := mload(size)
}
return (ret, addr);
}
/*
The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
*/
function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) {
bytes32 r;
bytes32 s;
uint8 v;
if (_sig.length != 65) {
return (false, address(0));
}
/*
The signature format is a compact form of:
{bytes32 r}{bytes32 s}{uint8 v}
Compact means, uint8 is not padded to 32 bytes.
*/
assembly {
r := mload(add(_sig, 32))
s := mload(add(_sig, 64))
/*
Here we are loading the last 32 bytes. We exploit the fact that
'mload' will pad with zeroes if we overread.
There is no 'mload8' to do this, but that would be nicer.
*/
v := byte(0, mload(add(_sig, 96)))
/*
Alternative solution:
'byte' is not working due to the Solidity parser, so lets
use the second best option, 'and'
v := and(mload(add(_sig, 65)), 255)
*/
}
/*
albeit non-transactional signatures are not specified by the YP, one would expect it
to match the YP range of [27, 28]
geth uses [0, 1] and some clients have followed. This might change, see:
https://github.com/ethereum/go-ethereum/issues/2053
*/
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (false, address(0));
}
return safer_ecrecover(_hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
/*assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize(), sub(msize(), fmem))
}*/
}
}
interface IUniswapPair is IERC20
{
// Addresses of the first and second pool-kens.
function token0() external view returns (address);
function token1() external view returns (address);
// Get the pair's token pool reserves.
function getReserves()
external view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
}
contract UniLotteryPool is ERC20, CoreUniLotterySettings
{
// =================== Structs & Enums =================== //
/* Lottery running mode (Auto-Lottery, manual lottery).
*
* If Auto-Lottery feature is enabled, the new lotteries will start
* automatically after the previous one finished, and will use
* the default, agreed-upon config, which is set by voting.
*
* If Manual Lottery is enabled, the new lotteries are started
* manually, by submitting and voting for a specific config.
*
* Both modes can have AVERAGE_CONFIG feature, when final lottery
* config is not set by voting for one of several user-submitted
* configs, but final config is computed by averaging all the voted
* configs, where each vote proposes a config.
*/
enum LotteryRunMode {
MANUAL,
AUTO,
MANUAL_AVERAGE_CONFIG,
AUTO_AVERAGE_CONFIG
}
// =================== Events =================== //
// Periodic stats event.
event PoolStats(
uint32 indexed lotteriesPerformed,
uint indexed totalPoolFunds,
uint indexed currentPoolBalance
);
// New poolholder joins and complete withdraws of a poolholder.
event NewPoolholderJoin(
address indexed poolholder,
uint256 initialAmount
);
event PoolholderWithdraw(
address indexed poolholder
);
// Current poolholder liquidity adds/removes.
event AddedLiquidity(
address indexed poolholder,
uint256 indexed amount
);
event RemovedLiquidity(
address indexed poolholder,
uint256 indexed amount
);
// Lottery Run Mode change (for example, from Manual to Auto lottery).
event LotteryRunModeChanged(
LotteryRunMode previousMode,
LotteryRunMode newMode
);
// Lottery configs proposed. In other words, it's a new lottery start
// initiation. If no config specified, then the default config for
// that lottery is used.
event NewConfigProposed(
address indexed initiator,
Lottery.LotteryConfig cfg,
uint configIndex
);
// Lottery started.
event LotteryStarted(
address indexed lottery,
uint256 indexed fundsUsed,
uint256 indexed poolPercentageUsed,
Lottery.LotteryConfig config
);
// Lottery finished.
event LotteryFinished(
address indexed lottery,
uint256 indexed totalReturn,
uint256 indexed profitAmount
);
// Ether transfered into the fallback receive function.
event EtherReceived(
address indexed sender,
uint256 indexed value
);
// ========= Constants ========= //
// The Core Constants (OWNER_ADDRESS, Owner's max profit amount),
// and also the percentage calculation-related constants,
// are defined in the CoreUniLotterySettings contract, which this
// contract inherits from.
// ERC-20 token's public constants.
string constant public name = "UniLottery Main Pool";
string constant public symbol = "ULPT";
uint256 constant public decimals = 18;
// ========= State variables ========= //
// --------- Slot --------- //
// The debt to the Randomness Provider.
// Incurred when we allow the Randomness Provider to execute
// requests with higher price than we have given it funds for.
// (of course, executed only when the Provider has enough balance
// to execute it).
// Paid back on next Randomness Provider request.
uint80 randomnessProviderDebt;
// Auto-Mode lottery parameters:
uint32 public autoMode_nextLotteryDelay = 1 days;
uint16 public autoMode_maxNumberOfRuns = 50;
// When the last Auto-Mode lottery was started.
uint32 public autoMode_lastLotteryStarted;
// When the last Auto-Mode lottery has finished.
// Used to compute the time until the next lottery.
uint32 public autoMode_lastLotteryFinished;
// Auto-Mode callback scheduled time.
uint32 public autoMode_timeCallbackScheduled;
// Iterations of current Auto-Lottery cycle.
uint16 autoMode_currentCycleIterations = 0;
// Is an Auto-Mode lottery currently ongoing?
bool public autoMode_isLotteryCurrentlyOngoing = false;
// Re-Entrancy Lock for Liquidity Provide/Remove functions.
bool reEntrancyLock_Locked;
// --------- Slot --------- //
// The initial funds of all currently active lotteries.
uint currentLotteryFunds;
// --------- Slot --------- //
// Most recently launched lottery.
Lottery public mostRecentLottery;
// Current lottery run-mode (Enum, so 1 byte).
LotteryRunMode public lotteryRunMode = LotteryRunMode.MANUAL;
// Last time when funds were manually sent to the Randomness Provider.
uint32 lastTimeRandomFundsSend;
// --------- Slot --------- //
// The address of the Gas Oracle (our own service which calls our
// gas price update function periodically).
address gasOracleAddress;
// --------- Slot --------- //
// Stores all lotteries that have been performed
// (including currently ongoing ones ).
Lottery[] public allLotteriesPerformed;
// --------- Slot --------- //
// Currently ongoing lotteries - a list, and a mapping.
mapping( address => bool ) ongoingLotteries;
// --------- Slot --------- //
// Owner-approved addresses, which can call functions, marked with
// modifier "ownerApprovedAddressOnly", on behalf of the Owner,
// to initiate Owner-Only operations, such as setting next lottery
// config, or moving specified part of Owner's liquidity pool share to
// Owner's wallet address.
// Note that this is equivalent of as if Owner had called the
// removeLiquidity() function from OWNER_ADDRESS.
//
// These owner-approved addresses, able to call owner-only functions,
// are used by Owner, to minimize risk of a hack in these ways:
// - OWNER_ADDRESS wallet, which might hold significant ETH amounts,
// is used minimally, to have as little log-on risk in Metamask,
// as possible.
// - The approved addresses can have very little Ether, so little
// risk of using them from Metamask.
// - Periodic liquidity removes from the Pool can help to reduce
// losses, if Pool contract was hacked (which most likely
// wouldn't ever happen given our security measures, but
// better be safe than sorry).
//
mapping( address => bool ) public ownerApprovedAddresses;
// --------- Slot --------- //
// The config to use for the next lottery that will be started.
Lottery.LotteryConfig internal nextLotteryConfig;
// --------- Slot --------- //
// Randomness Provider address.
UniLotteryRandomnessProvider immutable public randomnessProvider;
// --------- Slot --------- //
// The Lottery Factory that we're using to deploy NEW lotteries.
UniLotteryLotteryFactory immutable public lotteryFactory;
// --------- Slot --------- //
// The Lottery Storage factory that we're using to deploy
// new lottery storages. Used inside a Lottery Factory.
address immutable public storageFactory;
// ========= FUNCTIONS - METHODS ========= //
// ========= Private Functions ========= //
// Owner-Only modifier (standard).
modifier ownerOnly
{
require( msg.sender == OWNER_ADDRESS/*, "Function is Owner-Only!" */);
_;
}
// Owner, or Owner-Approved address only.
modifier ownerApprovedAddressOnly
{
require( ownerApprovedAddresses[ msg.sender ]/*,
"Function can be called only by Owner-Approved addresses!"*/);
_;
}
// Owner Approved addresses, and the Gas Oracle address.
// Used when updating RandProv's gas price.
modifier gasOracleAndOwnerApproved
{
require( ownerApprovedAddresses[ msg.sender ] ||
msg.sender == gasOracleAddress/*,
"Function can only be called by Owner-Approved addrs, "
"and by the Gas Oracle!" */);
_;
}
// Randomness Provider-Only modifier.
modifier randomnessProviderOnly
{
require( msg.sender == address( randomnessProvider )/*,
"Function can be called only by the Randomness Provider!" */);
_;
}
/**
* Modifier for checking if a caller is a currently ongoing
* lottery - that is, if msg.sender is one of addresses in
* ongoingLotteryList array, and present in ongoingLotteries.
*/
modifier calledByOngoingLotteryOnly
{
require( ongoingLotteries[ msg.sender ]/*,
"Function can be called only by ongoing lotteries!"*/);
_;
}
/**
* Lock the function to protect from re-entrancy, using
* a Re-Entrancy Mutex Lock.
*/
modifier mutexLOCKED
{
require( ! reEntrancyLock_Locked/*, "Re-Entrant Call Detected!" */);
reEntrancyLock_Locked = true;
_;
reEntrancyLock_Locked = false;
}
// Emits a statistical event, summarizing current pool state.
function emitPoolStats()
private
{
(uint32 a, uint b, uint c) = getPoolStats();
emit PoolStats( a, b, c );
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Launch a new UniLottery Lottery, from specified Lottery Config.
* Perform all initialization procedures, including initial fund
* transfer, and random provider registration.
*
* @return newlyLaunchedLottery - the Contract instance (address) of
* the newly deployed and initialized lottery.
*/
function launchLottery(
Lottery.LotteryConfig memory cfg )
private
mutexLOCKED
returns( Lottery newlyLaunchedLottery )
{
// Check config fund requirement.
// Lottery will need funds equal to:
// initial funds + gas required for randomness prov. callback.
// Now, get the price of the random datasource query with
// the above amount of callback gas, from randomness provider.
uint callbackPrice = randomnessProvider
.getPriceForRandomnessCallback( LOTTERY_RAND_CALLBACK_GAS );
// Also take into account the debt that we might owe to the
// Randomness Provider, if it previously executed requests
// with price being higher than we have gave it funds for.
//
// This situation can occur because we transfer lottery callback
// price funds before lottery starts, and when that lottery
// finishes (which can happen after several weeks), then
// the gas price might be higher than we have estimated
// and given funds for on lottery start.
// In this scenario, Randomness Provider would execute the
// request nonetheless, provided that it has enough funds in
// it's balance, to execute it.
//
// However, the Randomness Provider would notify us, that a
// debt of X ethers have been incurred, so we would have
// to transfer that debt's amount with next request's funds
// to Randomness Provider - and that's precisely what we
// are doing here, block.timestamp:
// Compute total cost of this lottery - initial funds,
// Randomness Provider callback cost, and debt from previous
// callback executions.
uint totalCost = cfg.initialFunds + callbackPrice +
randomnessProviderDebt;
// Check if our balance is enough to pay the cost.
// TODO: Implement more robust checks on minimum and maximum
// allowed fund restrictions.
require( totalCost <= address( this ).balance/*,
"Insufficient funds for this lottery start!" */);
// Deploy the new lottery contract using Factory.
Lottery lottery = Lottery( lotteryFactory.createNewLottery(
cfg, address( randomnessProvider ) ) );
// Check if the lottery's pool address and owner address
// are valid (same as ours).
require( lottery.poolAddress() == address( this ) &&
lottery.OWNER_ADDRESS() == OWNER_ADDRESS/*,
"Lottery's pool or owner addresses are invalid!" */);
// Transfer the Gas required for lottery end callback, and the
// debt (if some exists), into the Randomness Provider.
address( randomnessProvider ).transfer(
callbackPrice + randomnessProviderDebt );
// Clear the debt (if some existed) - it has been paid.
randomnessProviderDebt = 0;
// Notify the Randomness Provider about how much gas will be
// needed to run this lottery's ending callback, and how much
// funds we have given for it.
randomnessProvider.setLotteryCallbackGas(
address( lottery ),
LOTTERY_RAND_CALLBACK_GAS,
uint160( callbackPrice )
);
// Initialize the lottery - start the active lottery stage!
// Send initial funds to the lottery too.
lottery.initialize{ value: cfg.initialFunds }();
// Lottery was successfully initialized!
// Now, add it to tracking arrays, and emit events.
ongoingLotteries[ address(lottery) ] = true;
allLotteriesPerformed.push( lottery );
// Set is as the Most Recently Launched Lottery.
mostRecentLottery = lottery;
// Update current lottery funds.
currentLotteryFunds += cfg.initialFunds;
// Emit the apppproppppriate evenc.
emit LotteryStarted(
address( lottery ),
cfg.initialFunds,
( (_100PERCENT) * totalCost ) / totalPoolFunds(),
cfg
);
// Return the newly-successfully-started lottery.
return lottery;
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* When AUTO run-mode is set, this function schedules a new lottery
* to be started after the last Auto-Mode lottery has ended, after
* a specific time delay (by default, 1 day delay).
*
* Also, it's used to bootstrap the Auto-Mode loop - because
* it schedules a callback to get called.
*
* This function is called in 2 occasions:
*
* 1. When lotteryFinish() detects an AUTO run-mode, and so, a
* new Auto-Mode iteration needs to be performed.
*
* 2. When external actor bootstraps a new Auto-Mode cycle.
*
* Notice, that this function doesn't use require()'s - that's
* because it's getting called from lotteryFinish() too, and
* we don't want that function to fail just because some user
* set run mode to other value than AUTO during the time before.
* The only require() is when we check for re-entrancy.
*
* How Auto-Mode works?
* Everything is based on the Randomness Provider scheduled callback
* functionality, which is in turn based on Provable services.
* Basically, here we just schedule a scheduledCallback() to
* get called after a specified amount of time, and the
* scheduledCallback() performs the new lottery launch from the
* current next-lottery config.
*
* * What's payable?
* - We send funds to Randomness Provider, required to launch
* our callback later.
*/
function scheduleAutoModeCallback()
private
mutexLOCKED
returns( bool success )
{
// Firstly, check if mode is AUTO.
if( lotteryRunMode != LotteryRunMode.AUTO ) {
autoMode_currentCycleIterations = 0;
return false;
}
// Start a scheduled callback using the Randomness Provider
// service! But first, we gotta transfer the needed funds
// to the Provider.
// Get the price.
uint callbackPrice = randomnessProvider
.getPriceForScheduledCallback( AUTO_MODE_SCHEDULED_CALLBACK_GAS );
// Add the debt, if exists.
uint totalPrice = callbackPrice + randomnessProviderDebt;
if( totalPrice > address(this).balance ) {
return false;
}
// Send the required funds to the Rand.Provider.
// Use the send() function, because it returns false upon failure,
// and doesn't revert this transaction.
if( ! address( randomnessProvider ).send( totalPrice ) ) {
return false;
}
// Now, we've just paid the debt (if some existed).
randomnessProviderDebt = 0;
// Now, call the scheduling function of the Randomness Provider!
randomnessProvider.schedulePoolCallback(
autoMode_nextLotteryDelay,
AUTO_MODE_SCHEDULED_CALLBACK_GAS,
callbackPrice
);
// Set the time the callback was scheduled.
autoMode_timeCallbackScheduled = uint32( block.timestamp );
return true;
}
// ========= Public Functions ========= //
/**
* Constructor.
* - Here, we deploy the ULPT token contract.
* - Also, we deploy the Provable-powered Randomness Provider
* contract, which lotteries will use to get random seed.
* - We assign our Lottery Factory contract address to the passed
* parameter - the Lottery Factory contract which was deployed
* before, but not yet initialize()'d.
*
* Notice, that the msg.sender (the address who deployed the pool
* contract), doesn't play any special role in this nor any related
* contracts.
*/
constructor( address _lotteryFactoryAddr,
address _storageFactoryAddr,
address payable _randProvAddr )
{
// Initialize the randomness provider.
UniLotteryRandomnessProvider( _randProvAddr ).initialize();
randomnessProvider = UniLotteryRandomnessProvider( _randProvAddr );
// Set the Lottery Factory contract address, and initialize it!
UniLotteryLotteryFactory _lotteryFactory =
UniLotteryLotteryFactory( _lotteryFactoryAddr );
// Initialize the lottery factory, setting it to use the
// specified Storage Factory.
// After this point, factory states become immutable.
_lotteryFactory.initialize( _storageFactoryAddr );
// Assign the Storage Factory address.
// Set the immutable variables to their temporary placeholders.
storageFactory = _storageFactoryAddr;
lotteryFactory = _lotteryFactory;
// Set the first Owner-Approved address as the OWNER_ADDRESS
// itself.
ownerApprovedAddresses[ OWNER_ADDRESS ] = true;
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* The "Receive Ether" function.
* Used to receive Ether from Lotteries, and from the
* Randomness Provider, when retrieving funds.
*/
receive() external payable
{
emit EtherReceived( msg.sender, msg.value );
}
/**
* Get total funds of the pool -- the pool balance, and all the
* initial funds of every currently-ongoing lottery.
*/
function totalPoolFunds() public view
returns( uint256 )
{
// Get All Active Lotteries initial funds.
/*uint lotteryBalances = 0;
for( uint i = 0; i < ongoingLotteryList.length; i++ ) {
lotteryBalances +=
ongoingLotteryList[ i ].getActiveInitialFunds();
}*/
return address(this).balance + currentLotteryFunds;
}
/**
* Get current pool stats - number of poolholders,
* number of voters, etc.
*/
function getPoolStats()
public view
returns(
uint32 _numberOfLotteriesPerformed,
uint _totalPoolFunds,
uint _currentPoolBalance )
{
_numberOfLotteriesPerformed = uint32( allLotteriesPerformed.length );
_totalPoolFunds = totalPoolFunds();
_currentPoolBalance = address( this ).balance;
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* Provide liquidity into the pool, and become a pool shareholder.
* - Function accepts Ether payments (No minimum deposit),
* and mints a proportionate number of ULPT tokens for the
* sender.
*/
function provideLiquidity()
external
payable
ownerApprovedAddressOnly
mutexLOCKED
{
// Check for minimum deposit.
//require( msg.value > MIN_DEPOSIT/*, "Deposit amount too low!" */);
// Compute the pool share that the user should obtain with
// the amount he paid in this message -- that is, compute
// percentage of the total pool funds (with new liquidity
// added), relative to the ether transferred in this msg.
// TotalFunds can't be zero, because currently transfered
// msg.value is already added to totalFunds.
//
// Also/*, "percentage" */can't exceed 100%, because condition
// "totalPoolFunds() >= msg.value" is ALWAYS true, because
// msg.value is already added to totalPoolFunds before
// execution of this function's body - transfers to
// "payable" functions are executed before the function's
// body executes (Solidity docs).
//
uint percentage = ( (_100PERCENT) * msg.value ) /
( totalPoolFunds() );
// Now, compute the amount of new ULPT tokens (x) to mint
// for this new liquidity provided, according to formula,
// whose explanation is provided below.
//
// Here, we assume variables:
//
// uintFormatPercentage: the "percentage" Solidity variable,
// defined above, in (uint percentage = ...) statement.
//
// x: the amount of ULPT tokens to mint for this liquidity
// provider, to maintain "percentage" ratio with the
// ULPT's totalSupply after minting (newTotalSupply).
//
// totalSupply: ULPT token's current total supply
// (as returned from totalSupply() function).
//
// Let's start the formula:
//
// ratio = uintFormatPercentage / (_100PERCENT)
// newTotalSupply = totalSupply + x
//
// x / newTotalSupply = ratio
// x / (totalSupply + x) = ratio
// x = ratio * (totalSupply + x)
// x = (ratio * totalSupply) + (ratio * x)
// x - (ratio * x) = (ratio * totalSupply)
// (1 * x) - (ratio * x) = (ratio * totalSupply)
// ( 1 - ratio ) * x = (ratio * totalSupply)
// x = (ratio * totalSupply) / ( 1 - ratio )
//
// ratio * totalSupply
// x = ------------------------------------------------
// 1 - ( uintFormatPercentage / (_100PERCENT) )
//
//
// ratio * totalSupply * (_100PERCENT)
// x = ---------------------------------------------------------------
// ( 1 - (uintFormatPercentage / (_100PERCENT)) )*(_100PERCENT)
//
// Let's abbreviate "_100PERCENT" to "100%".
//
// ratio * totalSupply * 100%
// x = ---------------------------------------------------------
// ( 1 * 100% ) - ( uintFormatPercentage / (100%) ) * (100%)
//
// ratio * totalSupply * 100%
// x = -------------------------------------
// 100% - uintFormatPercentage
//
// (uintFormatPercentage / (100%)) * totalSupply * 100%
// x = -------------------------------------------------------
// 100% - uintFormatPercentage
//
// (uintFormatPercentage / (100%)) * 100% * totalSupply
// x = -------------------------------------------------------
// 100% - uintFormatPercentage
//
// uintFormatPercentage * totalSupply
// x = ------------------------------------
// 100% - uintFormatPercentage
//
// So, with our Solidity variables, that would be:
// ==================================================== //
// //
// percentage * totalSupply //
// amountToMint = ------------------------------ //
// (_100PERCENT) - percentage //
// //
// ==================================================== //
//
// We know that "percentage" is ALWAYS <= 100%, because
// msg.value is already added to address(this).balance before
// the payable function's body executes.
//
// However, notice that when "percentage" approaches 100%,
// the denominator approaches 0, and that's not good.
//
// So, we must ensure that uint256 precision is enough to
// handle such situations, and assign a "default" value for
// amountToMint if such situation occurs.
//
// The most prominent case when this situation occurs, is on
// the first-ever liquidity provide, when ULPT total supply is
// zero, and the "percentage" value is 100%, because pool's
// balance was 0 before the operation.
//
// In such situation, we mint the 100 initial ULPT, which
// represent the pool share of the first ever pool liquidity
// provider, and that's 100% of the pool.
//
// Also, we do the same thing (mint 100 ULPT tokens), on all
// on all other situations when "percentage" is too close to 100%,
// such as when there's a very tiny amount of liquidity left in
// the pool.
//
// We check for those conditions based on precision of uint256
// number type.
// We know, that 256-bit uint can store up to roughly 10^74
// base-10 values.
//
// Also, in our formula:
// "totalSupply" can go to max. 10^30 (in extreme cases).
// "percentage" up to 10^12 (with more-than-enough precision).
//
// When multiplied, that's still only 10^(30+12) = 10^42 ,
// and that's still a long way to go to 10^74.
//
// So, the denominator "(_100PERCENT) - percentage" can go down
// to 1 safely, we must only ensure that it's not zero -
// and the uint256 type will take care of all precision needed.
//
if( balanceOf( msg.sender ) == 0 )
emit NewPoolholderJoin( msg.sender, msg.value );
// If percentage is below 100%, and totalSupply is NOT ZERO,
// work with the above formula.
if( percentage < (_100PERCENT) &&
totalSupply() != 0 )
{
// Compute the formula!
uint256 amountToMint =
( percentage * totalSupply() ) /
( (_100PERCENT) - percentage );
// Mint the computed amount.
_mint( msg.sender, amountToMint );
}
// Else, if the newly-added liquidity percentage is 100%
// (pool's balance was Zero before this liquidity provide), then
// just mint the initial 100 pool tokens.
else
{
_mint( msg.sender, ( 100 * (uint( 10 ) ** decimals) ) );
}
// Emit corresponding event, that liquidity has been added.
emit AddedLiquidity( msg.sender, msg.value );
emitPoolStats();
}
/**
* Get the current pool share (percentage) of a specified
* address. Return the percentage, compute from ULPT data.
*/
function getPoolSharePercentage( address holder )
public view
returns ( uint percentage )
{
return ( (_100PERCENT) * balanceOf( holder ) )
/ totalSupply();
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Remove msg.sender's pool liquidity share, and transfer it
* back to msg.sender's wallet.
* Burn the ULPT tokens that represented msg.sender's share
* of the pool.
* Notice that no activelyManaged modifier is present, which
* means that users are able to withdraw their money anytime.
*
* However, there's a caveat - if some lotteries are currently
* ongoing, the pool's current reserve balance might not be
* enough to meet every withdrawer's needs.
*
* In such scenario, withdrawers have either have to (OR'd):
* - Wait for ongoing lotteries to finish and return their
* funds back to the pool,
* - TODO: Vote for forceful termination of lotteries
* (vote can be done whether pool is active or not).
* - TODO: Wait for OWNER to forcefully terminate lotteries.
*
* Notice that last 2 options aren't going to be implemented
* in this version, because, as the OWNER is going to be the
* only pool shareholder in the begginning, lottery participants
* might see the forceful termination feature as an exit-scam
* threat, and this would damage project's reputation.
*
* The feature is going to be implemented in later versions,
* after security audits pass, pool is open to public,
* and a significant amount of wallets join a pool.
*/
function removeLiquidity(
uint256 ulptAmount )
external
ownerApprovedAddressOnly
mutexLOCKED
{
// Find out the real liquidity owner of this call -
// Check if the msg.sender is an approved-address, which can
// call this function on behalf of the true liquidity owner.
// Currently, this feature is only supported for OWNER_ADDRESS.
address payable liquidityOwner = OWNER_ADDRESS;
// Condition "balanceOf( liquidityOwner ) > 1" automatically
// checks if totalSupply() of ULPT is not zero, so we don't have
// to check it separately.
require( balanceOf( liquidityOwner ) > 1 &&
ulptAmount != 0 &&
ulptAmount <= balanceOf( liquidityOwner )/*,
"Specified ULPT token amount is invalid!" */);
// Now, compute share percentage, and send the appropriate
// amount of Ether from pool's balance to liquidityOwner.
uint256 percentage = ( (_100PERCENT) * ulptAmount ) /
totalSupply();
uint256 shareAmount = ( totalPoolFunds() * percentage ) /
(_100PERCENT);
require( shareAmount <= address( this ).balance/*,
"Insufficient pool contract balance!" */);
// Burn the specified amount of ULPT, thus removing the
// holder's pool share.
_burn( liquidityOwner, ulptAmount );
// Transfer holder's fund share as ether to holder's wallet.
liquidityOwner.transfer( shareAmount );
// Emit appropriate events.
if( balanceOf( liquidityOwner ) == 0 )
emit PoolholderWithdraw( liquidityOwner );
emit RemovedLiquidity( liquidityOwner, shareAmount );
emitPoolStats();
}
// ======== Lottery Management Section ======== //
// Check if lottery is currently ongoing.
function isLotteryOngoing( address lotAddr )
external view
returns( bool ) {
return ongoingLotteries[ lotAddr ];
}
// Get length of all lotteries performed.
function allLotteriesPerformed_length()
external view
returns( uint )
{
return allLotteriesPerformed.length;
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* Ongoing (not-yet-completed) lottery finalization function.
* - This function is called by a currently ongoing lottery, to
* notify the pool about it's finishing.
* - After lottery calls this function, lottery is removed from
* ongoing lottery tracking list, and set to inactive.
*
* * Ether is transfered into our contract:
* Lottery transfers the pool profit share and initial funds
* back to the pool when calling this function, so the
*/
function lotteryFinish(
uint totalReturn,
uint profitAmount )
external
payable
calledByOngoingLotteryOnly
{
// "De-activate" this lottery.
//ongoingLotteries[ msg.sender ] = false;
delete ongoingLotteries[ msg.sender ]; // implies "false"
// We assume that totalReturn and profitAmount are valid,
// because this function can be called only by Lottery, which
// was deployed by us before.
// Update current lottery funds - this one is no longer active,
// so it's funds block.timestamp have been transfered to us.
uint lotFunds = Lottery( msg.sender ).getInitialFunds();
if( lotFunds < currentLotteryFunds )
currentLotteryFunds -= lotFunds;
else
currentLotteryFunds = 0;
// Emit approppriate events.
emit LotteryFinished( msg.sender, totalReturn, profitAmount );
// If AUTO-MODE is currently set, schedule a next lottery
// start using the current AUTO-MODE parameters!
// Ignore the return value, because AUTO-MODE params might be
// invalid, and we don't want our finish function to fail
// just because of that.
if( lotteryRunMode == LotteryRunMode.AUTO )
{
autoMode_isLotteryCurrentlyOngoing = false;
autoMode_lastLotteryFinished = uint32( block.timestamp );
scheduleAutoModeCallback();
}
}
/**
* The Callback function which Randomness Provider will call
* when executing the Scheduled Callback requests.
*
* We use this callback for scheduling Auto-Mode lotteries -
* when one lottery finishes, another one is scheduled to run
* after specified amount of time.
*
* In this callback, we start the scheduled Auto-Mode lottery.
*/
function scheduledCallback( uint256 /*requestID*/ )
public
{
// At first, check if mode is AUTO (not changed).
if( lotteryRunMode != LotteryRunMode.AUTO )
return;
// Check if we're not X-Ceeding the number of auto-iterations.
if( autoMode_currentCycleIterations >= autoMode_maxNumberOfRuns )
{
autoMode_currentCycleIterations = 0;
return;
}
// Launch an auto-lottery using the currently set next
// lottery config!
// When this lottery finishes, and the mode is still AUTO,
// one more lottery will be started.
launchLottery( nextLotteryConfig );
// Set the time started, and increment iterations.
autoMode_isLotteryCurrentlyOngoing = true;
autoMode_lastLotteryStarted = uint32( block.timestamp );
autoMode_currentCycleIterations++;
}
/**
* The Randomness Provider-callable function, which is used to
* ask pool for permission to execute lottery ending callback
* request with higher price than the pool-given funds for that
* specific lottery's ending request, when lottery was created.
*
* The function notifies the pool about the new and
* before-expected price, so the pool could compute a debt to
* be paid to the Randomnes Provider in next request.
*
* Here, we update our debt variable, which is the difference
* between current and expected-before request price,
* and we'll transfer the debt to Randomness Provider on next
* request to Randomness Provider.
*
* Notice, that we'll permit the execution of the lottery
* ending callback only if the new price is not more than
* 1.5x higher than before-expected price.
*
* This is designed so, because the Randomness Provider will
* call this function only if it has enough funds to execute the
* callback request, and just that the funds that we have transfered
* for this specific lottery's ending callback before, are lower
* than the current price of execution.
*
* Why is this the issue?
* Lottery can last for several weeks, and we give the callback
* execution funds for that specific lottery to Randomness Provider
* only on that lottery's initialization.
* So, after a few weeks, the Provable services might change the
* gas & fee prices, so the callback execution request price
* might change.
*/
function onLotteryCallbackPriceExceedingGivenFunds(
address /*lottery*/,
uint currentRequestPrice,
uint poolGivenExpectedRequestPrice )
external
randomnessProviderOnly
returns( bool callbackExecutionPermitted )
{
require( currentRequestPrice > poolGivenExpectedRequestPrice );
uint difference = currentRequestPrice - poolGivenExpectedRequestPrice;
// Check if the price difference is not bigger than the half
// of the before-expected pool-given price.
// Also, make sure that whole debt doesn't exceed 0.5 ETH.
if( difference <= ( poolGivenExpectedRequestPrice / 2 ) &&
( randomnessProviderDebt + difference ) < ( (1 ether) / 2 ) )
{
// Update our debt, to pay back the difference later,
// when we transfer funds for the next request.
randomnessProviderDebt += uint80( difference );
// Return true - the callback request execution is permitted.
return true;
}
// The price difference is higher - deny the execution.
return false;
}
// Below are the Owner-Callable voting-skipping functions, to set
// the next lottery config, lottery run mode, and other settings.
//
// When the final version is released, these functions will
// be removed, and every governance operation will be done
// through voting.
/**
* Set the LotteryConfig to be used by the next lottery.
* Owner-only callable.
*/
function setNextLotteryConfig(
Lottery.LotteryConfig memory cfg )
public
ownerApprovedAddressOnly
{
nextLotteryConfig = cfg;
emit NewConfigProposed( msg.sender, cfg, 0 );
// emitPoolStats();
}
/**
* Set the Lottery Run Mode to be used for further lotteries.
* It can be AUTO, or MANUAL (more about it on their descriptions).
*/
function setRunMode(
LotteryRunMode runMode )
external
ownerApprovedAddressOnly
{
// Check if it's one of allowed run modes.
require( runMode == LotteryRunMode.AUTO ||
runMode == LotteryRunMode.MANUAL/*,
"This Run Mode is not allowed in current state!" */);
// Emit a change event, with old value and new value.
emit LotteryRunModeChanged( lotteryRunMode, runMode );
// Set the new run mode!
lotteryRunMode = runMode;
// emitPoolStats();
}
/**
* Start a manual mode lottery from the previously set up
* next lottery config!
*/
function startManualModeLottery()
external
ownerApprovedAddressOnly
{
// Check if config is set - just check if initial funds
// are a valid value.
require( nextLotteryConfig.initialFunds != 0/*,
"Currently set next-lottery-config is invalid!" */);
// Launch a lottery using our private launcher function!
launchLottery( nextLotteryConfig );
emitPoolStats();
}
/**
* Set an Auto-Mode lottery run mode parameters.
* The auto-mode is implemented using Randomness Provider
* scheduled callback functionality, to schedule a lottery start
* on specific intervals.
*
* @param nextLotteryDelay - amount of time, in seconds, to wait
* when last lottery finishes, to start the next lottery.
*
* @param maxNumberOfRuns - max number of lottery runs in this
* Auto-Mode cycle. When it's reached, mode will switch to
* MANUAL automatically.
*/
function setAutoModeParameters(
uint32 nextLotteryDelay,
uint16 maxNumberOfRuns )
external
ownerApprovedAddressOnly
{
// Set params!
autoMode_nextLotteryDelay = nextLotteryDelay;
autoMode_maxNumberOfRuns = maxNumberOfRuns;
// emitPoolStats();
}
/**
* Starts an Auto-Mode lottery running cycle with currently
* specified Auto-Mode parameters.
* Notice that we must be on Auto run-mode currently.
*/
function startAutoModeCycle()
external
ownerApprovedAddressOnly
{
// Check that we're on the Auto-Mode block.timestamp.
require( lotteryRunMode == LotteryRunMode.AUTO/*,
"Current Run Mode is not AUTO!" */);
// Check if valid AutoMode params were specified.
require( autoMode_maxNumberOfRuns != 0/*,
"Invalid Auto-Mode params set!" */);
// Reset the cycle iteration counter.
autoMode_currentCycleIterations = 0;
// Start the Auto-Mode cycle using a scheduled callback!
scheduledCallback( 0 );
// emitPoolStats();
}
/**
* Set or Remove Owner-approved addresses.
* These addresses are used to call ownerOnly functions on behalf
* of the OWNER_ADDRESS (more detailed description above).
*/
function owner_setOwnerApprovedAddress( address addr )
external
ownerOnly
{
ownerApprovedAddresses[ addr ] = true;
}
function owner_removeOwnerApprovedAddress( address addr )
external
ownerOnly
{
delete ownerApprovedAddresses[ addr ];
}
/**
* ABIEncoderV2 - compatible getter for the nextLotteryConfig,
* which will be retuned as byte array internally, then internally
* de-serialized on receive.
*/
function getNextLotteryConfig()
external
view
returns( Lottery.LotteryConfig memory )
{
return nextLotteryConfig;
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* Retrieve the UnClaimed Prizes of a completed lottery, if
* that lottery's prize claim deadline has already passed.
*
* - What's payable? This function causes a specific Lottery to
* transfer Ether from it's contract balance, to our contract.
*/
function retrieveUnclaimedLotteryPrizes(
address payable lottery )
external
ownerApprovedAddressOnly
mutexLOCKED
{
// Just call that function - if the deadline hasn't passed yet,
// that function will revert.
Lottery( lottery ).getUnclaimedPrizes();
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* Retrieve the specified amount of funds from the Randomness
* Provider.
*
* WARNING: Future scheduled operations on randomness provider
* might FAIL if randomness provider won't have enough
* funds to execute that operation on that time!
*
* - What's payable? This function causes the Randomness Provider to
* transfer Ether from it's contract balance, to our contract.
*/
function retrieveRandomnessProviderFunds(
uint etherAmount )
external
ownerApprovedAddressOnly
mutexLOCKED
{
randomnessProvider.sendFundsToPool( etherAmount );
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Send specific amount of funds to Randomness Provider, from
* our contract's balance.
* This is useful in cases when gas prices change, and current
* funds inside randomness provider are not enough to execute
* operations on the new gas cost.
*
* This operation is limited to 6 ethers once in 12 hours.
*
* - What's payable? We send Ether to the randomness provider.
*/
function provideRandomnessProviderFunds(
uint etherAmount )
external
ownerApprovedAddressOnly
mutexLOCKED
{
// Check if conditions apply!
require( ( etherAmount <= 6 ether ) &&
( block.timestamp - lastTimeRandomFundsSend > 12 hours )/*,
"Random Fund Provide Conditions are not satisfied!" */);
// Set the last-time-funds-sent timestamp to block.timestamp.
lastTimeRandomFundsSend = uint32( block.timestamp );
// Transfer the funds.
address( randomnessProvider ).transfer( etherAmount );
}
/**
* Set the Gas Price to use in the Randomness Provider.
* Used when very volatile gas prices are present during network
* congestions, when default is not enough.
*/
function setGasPriceOfRandomnessProvider(
uint gasPrice )
external
gasOracleAndOwnerApproved
{
randomnessProvider.setGasPrice( gasPrice );
}
/**
* Set the address of the so-called Gas Oracle, which is an
* automated script running on our server, and fetching gas prices.
*
* The address used by this script should be able to call
* ONLY the "setGasPriceOfRandomnessProvider" function (above).
*
* Here, we set that address.
*/
function setGasOracleAddress( address addr )
external
ownerApprovedAddressOnly
{
gasOracleAddress = addr;
}
}
contract Lottery is ERC20, CoreUniLotterySettings
{
// ===================== Events ===================== //
// After initialize() function finishes.
event LotteryInitialized();
// Emitted when lottery active stage ends (Mining Stage starts),
// on Mining Stage Step 1, after transferring profits to their
// respective owners (pool and OWNER_ADDRESS).
event LotteryEnd(
uint128 totalReturn,
uint128 profitAmount
);
// Emitted when on final finish, we call Randomness Provider
// to callback us with random value.
event RandomnessProviderCalled();
// Requirements for finishing stage start have been reached -
// finishing stage has started.
event FinishingStageStarted();
// We were currently on the finishing stage, but some requirement
// is no longer met. We must stop the finishing stage.
event FinishingStageStopped();
// New Referral ID has been generated.
event ReferralIDGenerated(
address referrer,
uint256 id
);
// New referral has been registered with a valid referral ID.
event ReferralRegistered(
address referree,
address referrer,
uint256 id
);
// Fallback funds received.
event FallbackEtherReceiver(
address sender,
uint value
);
// ====================== Structs & Enums ====================== //
// Lottery Stages.
// Described in more detail above, on contract's main doc.
enum STAGE
{
// Initial stage - before the initialize() function is called.
INITIAL,
// Active Stage: On this stage, all token trading occurs.
ACTIVE,
// Finishing stage:
// This is when all finishing criteria are met, and for every
// transfer, we're rolling a pseudo-random number to determine
// if we should end the lottery (move to Ending stage).
FINISHING,
// Ending - Mining Stage:
// This stage starts after we lottery is no longer active,
// finishing stage ends. On this stage, Miners perform the
// Ending Algorithm and other operations.
ENDING_MINING,
// Lottery is completed - this is set after the Mining Stage ends.
// In this stage, Lottery Winners can claim their prizes.
COMPLETION,
// DISABLED stage. Used when we want a lottery contract to be
// absolutely disabled - so no state-modifying functions could
// be called.
// This is used in DelegateCall scenarios, where state-contract
// delegate-calls code contract, to save on deployment costs.
DISABLED
}
// Ending algorithm types enum.
enum EndingAlgoType
{
// 1. Mined Winner Selection Algorithm.
// This algorithm is executed by a Lottery Miner in a single
// transaction, on Mining Step 2.
//
// On that single transaction, all ending scores for all
// holders are computed, and a sorted winner array is formed,
// which is written onto the LotteryStorage state.
// Thus, it's gas expensive, and suitable only for small
// holder numbers (up to 300).
//
// Pros:
// + Guaranteed deterministically specifiable winner prize
// distribution - for example, if we specify that there
// must be 2 winners, of which first gets 60% of prize funds,
// and second gets 40% of prize funds, then it's
// guarateed that prize funds will be distributed just
// like that.
//
// + Low gas cost of prize claims - only ~ 40,000 gas for
// claiming a prize.
//
// Cons:
// - Not scaleable - as the Winner Selection Algorithm is
// executed in a single transaction, it's limited by
// block gas limit - 12,500,000 on the MainNet.
// Thus, the lottery is limited to ~300 holders, and
// max. ~200 winners of those holders.
// So, it's suitable for only express-lotteries, where
// a lottery runs only until ~300 holders are reached.
//
// - High mining costs - if lottery has 300 holders,
// mining transaction takes up whole block gas limit.
//
MinedWinnerSelection,
// 2. Winner Self-Validation Algorithm.
//
// This algorithm does no operations during the Mining Stage
// (except for setting up a Random Seed in Lottery Storage) -
// the winner selection (obtaining a winner rank) is done by
// the winners themselves, when calling the prize claim
// functions.
//
// This algorithm relies on a fact that by the time that
// random seed is obtained, all data needed for winner selection
// is already there - the holder scores of the Active Stage
// (ether contributed, time factors, token balance), and
// the Random Data (random seed + nonce (holder's address)),
// so, there is no need to compute and sort the scores for the
// whole holder array.
//
// It's done like this: the holder checks if he's a winner, using
// a view-function off-chain, and if so, he calls the
// claimWinnerPrize() function, which obtains his winner rank
// on O(n) time, and does no writing to contract states,
// except for prize transfer-related operations.
//
// When computing the winner's rank on LotteryStorage,
// O(n) time is needed, as we loop through the holders array,
// computing ending scores for each holder, using already-known
// data.
// However that means that for every prize claim, all scores of
// all holders must be re-computed.
// Computing a score for a single holder takes roughly 1500 gas
// (400 for 3 slots SLOAD, and ~300 for arithmetic operations).
//
// So, this algorithm makes prize claims more expensive for
// every lottery holder.
// If there's 1000 holders, prize claim takes up 1,500,000 gas,
// so, this algorithm is not suitable for small prizes,
// because gas fee would be higher than the prize amount won.
//
// Pros:
// + Guaranteed deterministically specifiable winner prize
// distribution (same as for algorithm 1).
//
// + No mining costs for winner selection algorithm.
//
// + More scalable than algorithm 1.
//
// Cons:
// - High gas costs of prize claiming, rising with the number
// of lottery holders - 1500 for every lottery holder.
// Thus, suitable for only large prize amounts.
//
WinnerSelfValidation,
// 3. Rolled-Randomness algorithm.
//
// This algorithm is the most cheapest in terms of gas, but
// the winner prize distribution is non-deterministic.
//
// This algorithm doesn't employ miners (no mining costs),
// and doesn't require to compute scores for every holder
// prior to getting a winner's rank, thus is the most scalable.
//
// It works like this: a holder checks his winner status by
// computing only his own randomized score (rolling a random
// number from the random seed, and multiplying it by holder's
// Active Stage score), and computing this randomized-score's
// ratio relative to maximum available randomized score.
// The higher the ratio, the higher the winner rank is.
//
// However, many players can roll very high or low scores, and
// get the same prizes, so it's difficult to make a fair and
// efficient deterministic prize distribution mechanism, so
// we have to fallback to specific heuristic workarounds.
//
// Pros:
// + Scalable: O(1) complexity for computing a winner rank,
// so there can be an unlimited amount of lottery holders,
// and gas costs for winner selection and prize claim would
// still be constant & low.
//
// + Gas-efficient: gas costs for all winner-related operations
// are constant and low, because only single holder's score
// is computed.
//
// + Doesn't require mining - even more gas savings.
//
// Cons:
// + Hard to make a deterministic and fair prize distribution
// mechanism, because of un-known environment - as only
// single holder's score is compared to max-available
// random score, not taking into account other holder
// scores.
//
RolledRandomness
}
/**
* Gas-efficient, minimal config, which specifies only basic,
* most-important and most-used settings.
*/
struct LotteryConfig
{
// ================ Misc Settings =============== //
// --------- Slot --------- //
// Initial lottery funds (initial market cap).
// Specified by pool, and is used to check if initial funds
// transferred to fallback are correct - equal to this value.
uint initialFunds;
// --------- Slot --------- //
// The minimum ETH value of lottery funds, that, once
// reached on an exchange liquidity pool (Uniswap, or our
// contract), must be guaranteed to not shrink below this value.
//
// This is accomplished in _transfer() function, by denying
// all sells that would drop the ETH amount in liquidity pool
// below this value.
//
// But on initial lottery stage, before this minimum requirement
// is reached for the first time, all sells are allowed.
//
// This value is expressed in ETH - total amount of ETH funds
// that we own in Uniswap liquidity pair.
//
// So, if initial funds were 10 ETH, and this is set to 100 ETH,
// after liquidity pool's ETH value reaches 100 ETH, all further
// sells which could drop the liquidity amount below 100 ETH,
// would be denied by require'ing in _transfer() function
// (transactions would be reverted).
//
uint128 fundRequirement_denySells;
// ETH value of our funds that we own in Uniswap Liquidity Pair,
// that's needed to start the Finishing Stage.
uint128 finishCriteria_minFunds;
// --------- Slot --------- //
// Maximum lifetime of a lottery - maximum amount of time
// allowed for lottery to stay active.
// By default, it's two weeks.
// If lottery is still active (hasn't returned funds) after this
// time, lottery will stop on the next token transfer.
uint32 maxLifetime;
// Maximum prize claiming time - for how long the winners
// may be able to claim their prizes after lottery ending.
uint32 prizeClaimTime;
// Token transfer burn rates for buyers, and a default rate for
// sells and non-buy-sell transfers.
uint32 burn_buyerRate;
uint32 burn_defaultRate;
// Maximum amount of tokens (in percentage of initial supply)
// to be allowed to own by a single wallet.
uint32 maxAmountForWallet_percentageOfSupply;
// The required amount of time that must pass after
// the request to Randomness Provider has been made, for
// external actors to be able to initiate alternative
// seed generation algorithm.
uint32 REQUIRED_TIME_WAITING_FOR_RANDOM_SEED;
// ================ Profit Shares =============== //
// "Mined Uniswap Lottery" ending Ether funds, which were obtained
// by removing token liquidity from Uniswap, are transfered to
// these recipient categories:
//
// 1. The Main Pool: Initial funds, plus Pool's profit share.
// 2. The Owner: Owner's profit share.
//
// 3. The Miners: Miner rewards for executing the winner
// selection algorithm stages.
// The more holders there are, the more stages the
// winner selection algorithm must undergo.
// Each Miner, who successfully completed an algorithm
// stage, will get ETH reward equal to:
// (minerProfitShare / totalAlgorithmStages).
//
// 4. The Lottery Winners: All remaining funds are given to
// Lottery Winners, which were determined by executing
// the Winner Selection Algorithm at the end of the lottery
// (Miners executed it).
// The Winners can claim their prizes by calling a
// dedicated function in our contract.
//
// The profit shares of #1 and #2 have controlled value ranges
// specified in CoreUniLotterySettings.
//
// All these shares are expressed as percentages of the
// lottery profit amount (totalReturn - initialFunds).
// Percentages are expressed using the PERCENT constant,
// defined in CoreUniLotterySettings.
//
// Here we specify profit shares of Pool, Owner, and the Miners.
// Winner Prize Fund is all that's left (must be more than 50%
// of all profits).
//
uint32 poolProfitShare;
uint32 ownerProfitShare;
// --------- Slot --------- //
uint32 minerProfitShare;
// =========== Lottery Finish criteria =========== //
// Lottery finish by design is a whole soft stage, that
// starts when criteria for holders and fund gains are met.
// During this stage, for every token transfer, a pseudo-random
// number will be rolled for lottery finish, with increasing
// probability.
//
// There are 2 ways that this probability increase is
// implemented:
// 1. Increasing on every new holder.
// 2. Increasing on every transaction after finish stage
// was initiated.
//
// On every new holder, probability increases more than on
// new transactions.
//
// However, if during this stage some criteria become
// no-longer-met, the finish stage is cancelled.
// This cancel can be implemented by setting finish probability
// to zero, or leaving it as it was, but pausing the finishing
// stage.
// This is controlled by finish_resetProbabilityOnStop flag -
// if not set, probability stays the same, when the finishing
// stage is discontinued.
// ETH value of our funds that we own in Uniswap Liquidity Pair,
// that's needed to start the Finishing Stage.
//
// LOOK ABOVE - arranged for tight-packing.
// Minimum number of token holders required to start the
// finishing stage.
uint32 finishCriteria_minNumberOfHolders;
// Minimum amount of time that lottery must be active.
uint32 finishCriteria_minTimeActive;
// Initial finish probability, when finishing stage was
// just initiated.
uint32 finish_initialProbability;
// Finishing probability increase steps, for every new
// transaction and every new holder.
// If holder number decreases, probability decreases.
uint32 finish_probabilityIncreaseStep_transaction;
uint32 finish_probabilityIncreaseStep_holder;
// =========== Winner selection config =========== //
// Winner selection algorithm settings.
//
// Algorithm is based on score, which is calculated for
// every holder on lottery finish, and is comprised of
// the following parts.
// Each part is normalized to range ( 0 - scorePoints ),
// from smallest to largest value of each holder;
//
// After scores are computed, they are multiplied by
// holder count factor (holderCount / holderCountDivisor),
// and finally, multiplied by safely-generated random values,
// to get end winning scores.
// The top scorers win prizes.
//
// By default setting, max score is 40 points, and it's
// comprised of the following parts:
//
// 1. Ether contributed (when buying from Uniswap or contract).
// Gets added when buying, and subtracted when selling.
// Default: 10 points.
//
// 2. Amount of lottery tokens holder has on finish.
// Default: 5 points.
//
// 3. Ether contributed, multiplied by the relative factor
// of time - that is/*, "block.timestamp" */minus "lotteryStartTime".
// This way, late buyers can get more points even if
// they get little tokens and don't spend much ether.
// Default: 5 points.
//
// 4. Refferrer bonus. For every player that joined with
// your referral ID, you get (that player's score) / 10
// points! This goes up to specified max score.
// Also, every player who provides a valid referral ID,
// gets 2 points for free!
// Default max bonus: 20 points.
//
int16 maxPlayerScore_etherContributed;
int16 maxPlayerScore_tokenHoldingAmount;
int16 maxPlayerScore_timeFactor;
int16 maxPlayerScore_refferalBonus;
// --------- Slot --------- //
// Score-To-Random ration data (as a rational ratio number).
// For example if 1:5, then scorePart = 1, and randPart = 5.
uint16 randRatio_scorePart;
uint16 randRatio_randPart;
// Time factor divisor - interval of time, in seconds, after
// which time factor is increased by one.
uint16 timeFactorDivisor;
// Bonus score a player should get when registering a valid
// referral code obtained from a referrer.
int16 playerScore_referralRegisteringBonus;
// Are we resetting finish probability when finishing stage
// stops, if some criteria are no longer met?
bool finish_resetProbabilityOnStop;
// =========== Winner Prize Fund Settings =========== //
// There are 2 available modes that we can use to distribute
// winnings: a computable sequence (geometrical progression),
// or an array of winner prize fund share percentages.
// More gas efficient is to use a computable sequence,
// where each winner gets a share equal to (factor * fundsLeft).
// Factor is in range [0.01 - 1.00] - simulated as [1% - 100%].
//
// For example:
// Winner prize fund is 100 ethers, Factor is 1/4 (25%), and
// there are 5 winners total (winnerCount), and sequenced winner
// count is 2 (sequencedWinnerCount).
//
// So, we pre-compute the upper shares, till we arrive to the
// sequenced winner count, in a loop:
// - Winner 1: 0.25 * 100 = 25 eth; 100 - 25 = 75 eth left.
// - Winner 2: 0.25 * 75 ~= 19 eth; 75 - 19 = 56 eth left.
//
// Now, we compute the left-over winner shares, which are
// winners that get their prizes from the funds left after the
// sequence winners.
//
// So, we just divide the leftover funds (56 eth), by 3,
// because winnerCount - sequencedWinnerCount = 3.
// - Winner 3 = 56 / 3 = 18 eth;
// - Winner 4 = 56 / 3 = 18 eth;
// - Winner 5 = 56 / 3 = 18 eth;
//
// If this value is 0, then we'll assume that array-mode is
// to be used.
uint32 prizeSequenceFactor;
// Maximum number of winners that the prize sequence can yield,
// plus the leftover winners, which will get equal shares of
// the remainder from the first-prize sequence.
uint16 prizeSequence_winnerCount;
// How many winners would get sequence-computed prizes.
// The left-over winners
// This is needed because prizes in sequence tend to zero, so
// we need to limit the sequence to avoid very small prizes,
// and to avoid the remainder.
uint16 prizeSequence_sequencedWinnerCount;
// Initial token supply (without decimals).
uint48 initialTokenSupply;
// Ending Algorithm type.
// More about the 3 algorithm types above.
uint8 endingAlgoType;
// --------- Slot --------- //
// Array mode: The winner profit share percentages array.
// For example, lottery profits can be distributed this way:
//
// Winner profit shares (8 winners):
// [ 20%, 15%, 10%, 5%, 4%, 3%, 2%, 1% ] = 60% of profits.
// Owner profits: 10%
// Pool profits: 30%
//
// Pool profit share is not defined explicitly in the config, so
// when we internally validate specified profit shares, we
// assume the pool share to be the left amount until 100% ,
// but we also make sure that this amount is at least equal to
// MIN_POOL_PROFITS, defined in CoreSettings.
//
uint32[] winnerProfitShares;
}
// ========================= Constants ========================= //
// The Miner Profits - max/min values.
// These aren't defined in Core Settings, because Miner Profits
// are only specific to this lottery type.
uint32 constant MIN_MINER_PROFITS = 1 * PERCENT;
uint32 constant MAX_MINER_PROFITS = 10 * PERCENT;
// Uniswap Router V2 contract instance.
// Address is the same for MainNet, and all public testnets.
IUniswapRouter constant uniswapRouter = IUniswapRouter(
address( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ) );
// Public-accessible ERC20 token specific constants.
string constant public name = "UniLottery Token";
string constant public symbol = "ULT";
uint256 constant public decimals = 18;
// =================== State Variables =================== //
// ------- Initial Slots ------- //
// The config which is passed to constructor.
LotteryConfig internal cfg;
// ------- Slot ------- //
// The Lottery Storage contract, which stores all holder data,
// such as scores, referral tree data, etc.
LotteryStorage public lotStorage;
// ------- Slot ------- //
// Pool address. Set on constructor from msg.sender.
address payable public poolAddress;
// ------- Slot ------- //
// Randomness Provider address.
address public randomnessProvider;
// ------- Slot ------- //
// Exchange address. In Uniswap mode, it's the Uniswap liquidity
// pair's address, where trades execute.
address public exchangeAddress;
// Start date.
uint32 public startDate;
// Completion (Mining Phase End) date.
uint32 public completionDate;
// The date when Randomness Provider was called, requesting a
// random seed for the lottery finish.
// Also, when this variable becomes Non-Zero, it indicates that we're
// on Ending Stage Part One: waiting for the random seed.
uint32 finish_timeRandomSeedRequested;
// ------- Slot ------- //
// WETH address. Set by calling Router's getter, on constructor.
address WETHaddress;
// Is the WETH first or second token in our Uniswap Pair?
bool uniswap_ethFirst;
// If we are, or were before, on finishing stage, this is the
// probability of lottery going to Ending Stage on this transaction.
uint32 finishProbablity;
// Re-Entrancy Lock (Mutex).
// We protect for reentrancy in the Fund Transfer functions.
bool reEntrancyMutexLocked;
// On which stage we are currently.
uint8 public lotteryStage;
// Indicator for whether the lottery fund gains have passed a
// minimum fund gain requirement.
// After that time point (when this bool is set), the token sells
// which could drop the fund value below the requirement, would
// be denied.
bool fundGainRequirementReached;
// The current step of the Mining Stage.
uint16 miningStep;
// If we're currently on Special Transfer Mode - that is, we allow
// direct transfers between parties even in NON-ACTIVE state.
bool specialTransferModeEnabled;
// ------- Slot ------- //
// Per-Transaction Pseudo-Random hash value (transferHashValue).
// This value is computed on every token transfer, by keccak'ing
// the last (current) transferHashValue, msg.sender, block.timestamp, and
// transaction count.
//
// This is used on Finishing Stage, as a pseudo-random number,
// which is used to check if we should end the lottery (move to
// Ending Stage).
uint256 transferHashValue;
// ------- Slot ------- //
// On lottery end, get & store the lottery total ETH return
// (including initial funds), and profit amount.
uint128 public ending_totalReturn;
uint128 public ending_profitAmount;
// ------- Slot ------- //
// The mapping that contains TRUE for addresses that already claimed
// their lottery winner prizes.
// Used only in COMPLETION, on claimWinnerPrize(), to check if
// msg.sender has already claimed his prize.
mapping( address => bool ) public prizeClaimersAddresses;
// ============= Private/internal functions ============= //
// Pool Only modifier.
modifier poolOnly {
require( msg.sender == poolAddress/*,
"Function can be called only by the pool!" */);
_;
}
// Only randomness provider allowed modifier.
modifier randomnessProviderOnly {
require( msg.sender == randomnessProvider/*,
"Function can be called only by the UniLottery"
" Randomness Provider!" */);
_;
}
// Execute function only on specific lottery stage.
modifier onlyOnStage( STAGE _stage )
{
require( lotteryStage == uint8( _stage )/*,
"Function cannot be called on current stage!" */);
_;
}
// Modifier for protecting the function from re-entrant calls,
// by using a locked Re-Entrancy Lock (Mutex).
modifier mutexLOCKED
{
require( ! reEntrancyMutexLocked/*,
"Re-Entrant Calls are NOT ALLOWED!" */);
reEntrancyMutexLocked = true;
_;
reEntrancyMutexLocked = false;
}
// Check if we're currently on a specific stage.
function onStage( STAGE _stage )
internal view
returns( bool )
{
return ( lotteryStage == uint8( _stage ) );
}
/**
* Check if token transfer to specific wallet won't exceed
* maximum token amount allowed to own by a single wallet.
*
* @return true, if holder's balance with "amount" added,
* would exceed the max allowed single holder's balance
* (by default, that is 5% of total supply).
*/
function transferExceedsMaxBalance(
address holder, uint amount )
internal view
returns( bool )
{
uint maxAllowedBalance =
( totalSupply() * cfg.maxAmountForWallet_percentageOfSupply ) /
( _100PERCENT );
return ( ( balanceOf( holder ) + amount ) > maxAllowedBalance );
}
/**
* Update holder data.
* This function is called by _transfer() function, just before
* transfering final amount of tokens directly from sender to
* receiver.
* At this point, all burns/mints have been done, and we're sure
* that this transfer is valid and must be successful.
*
* In all modes, this function is used to update the holder array.
*
* However, on external exchange modes (e.g. on Uniswap mode),
* it is also used to track buy/sell ether value, to update holder
* scores, when token buys/sells cannot be tracked directly.
*
* If, however, we use Standalone mode, we are the exchange,
* so on _transfer() we already know the ether value, which is
* set to currentBuySellEtherValue variable.
*
* @param amountSent - the token amount that is deducted from
* sender's balance. This includes burn, and owner fee.
*
* @param amountReceived - the token amount that receiver
* actually receives, after burns and fees.
*
* @return holderCountChanged - indicates whether holder count
* changes during this transfer - new holder joins or leaves
* (true), or no change occurs (false).
*/
function updateHolderData_preTransfer(
address sender,
address receiver,
uint256 amountSent,
uint256 amountReceived )
internal
returns( bool holderCountChanged )
{
// Update holder array, if new token holder joined, or if
// a holder transfered his whole balance.
holderCountChanged = false;
// Sender transferred his whole balance - no longer a holder.
if( balanceOf( sender ) == amountSent )
{
lotStorage.removeHolder( sender );
holderCountChanged = true;
}
// Receiver didn't have any tokens before - add it to holders.
if( balanceOf( receiver ) == 0 && amountReceived > 0 )
{
lotStorage.addHolder( receiver );
holderCountChanged = true;
}
// Update holder score factors: if buy/sell occured, update
// etherContributed and timeFactors scores,
// and also propagate the scores through the referral chain
// to the parent referrers (this is done in Storage contract).
// This lottery operates only on external exchange (Uniswap)
// mode, so we have to find out the buy/sell Ether value by
// calling the external exchange (Uniswap pair) contract.
// Temporary variable to store current transfer's buy/sell
// value in Ethers.
int buySellValue;
// Sender is an exchange - buy detected.
if( sender == exchangeAddress && receiver != exchangeAddress )
{
// Use the Router's functionality.
// Set the exchange path to WETH -> ULT
// (ULT is Lottery Token, and it's address is our address).
address[] memory path = new address[]( 2 );
path[ 0 ] = WETHaddress;
path[ 1 ] = address(this);
uint[] memory ethAmountIn = uniswapRouter.getAmountsIn(
amountSent, // uint amountOut,
path // address[] path
);
buySellValue = int( ethAmountIn[ 0 ] );
// Compute time factor value for the current ether value.
// buySellValue is POSITIVE.
// When computing Time Factors, leave only 2 ether decimals.
int timeFactorValue = ( buySellValue / (1 ether / 100) ) *
int( (block.timestamp - startDate) / cfg.timeFactorDivisor );
if( timeFactorValue == 0 )
timeFactorValue = 1;
// Update and propagate the buyer (receiver) scores.
lotStorage.updateAndPropagateScoreChanges(
receiver,
int80( buySellValue ),
int80( timeFactorValue ),
int80( amountReceived ) );
}
// Receiver is an exchange - sell detected.
else if( sender != exchangeAddress && receiver == exchangeAddress )
{
// Use the Router's functionality.
// Set the exchange path to ULT -> WETH
// (ULT is Lottery Token, and it's address is our address).
address[] memory path = new address[]( 2 );
path[ 0 ] = address(this);
path[ 1 ] = WETHaddress;
uint[] memory ethAmountOut = uniswapRouter.getAmountsOut(
amountReceived, // uint amountIn
path // address[] path
);
// It's a sell (ULT -> WETH), so set value to NEGATIVE.
buySellValue = int( -1 ) * int( ethAmountOut[ 1 ] );
// Compute time factor value for the current ether value.
// buySellValue is NEGATIVE.
int timeFactorValue = ( buySellValue / (1 ether / 100) ) *
int( (block.timestamp - startDate) / cfg.timeFactorDivisor );
if( timeFactorValue == 0 )
timeFactorValue = -1;
// Update and propagate the seller (sender) scores.
lotStorage.updateAndPropagateScoreChanges(
sender,
int80( buySellValue ),
int80( timeFactorValue ),
-1 * int80( amountSent ) );
}
// Neither Sender nor Receiver are exchanges - default transfer.
// Tokens just got transfered between wallets, without
// exchanging for ETH - so etherContributed_change = 0.
// On this case, update both sender's & receiver's scores.
//
else {
buySellValue = 0;
lotStorage.updateAndPropagateScoreChanges( sender, 0, 0,
-1 * int80( amountSent ) );
lotStorage.updateAndPropagateScoreChanges( receiver, 0, 0,
int80( amountReceived ) );
}
// Check if lottery liquidity pool funds have already
// reached a minimum required ETH value.
uint ethFunds = getCurrentEthFunds();
if( !fundGainRequirementReached &&
ethFunds >= cfg.fundRequirement_denySells )
{
fundGainRequirementReached = true;
}
// Check whether this token transfer is allowed if it's a sell
// (if buySellValue is negative):
//
// If we've already reached the minimum fund gain requirement,
// and this sell would shrink lottery liquidity pool's ETH funds
// below this requirement, then deny this sell, causing this
// transaction to fail.
if( fundGainRequirementReached &&
buySellValue < 0 &&
( uint( -1 * buySellValue ) >= ethFunds ||
ethFunds - uint( -1 * buySellValue ) <
cfg.fundRequirement_denySells ) )
{
require( false/*, "This sell would drop the lottery ETH funds"
"below the minimum requirement threshold!" */);
}
}
/**
* Check for finishing stage start conditions.
* - If some conditions are met, start finishing stage!
* Do it by setting "onFinishingStage" bool.
* - If we're currently on finishing stage, and some condition
* is no longer met, then stop the finishing stage.
*/
function checkFinishingStageConditions()
internal
{
// Firstly, check if lottery hasn't exceeded it's maximum lifetime.
// If so, don't check anymore, just set finishing stage, and
// end the lottery on further call of checkForEnding().
if( (block.timestamp - startDate) > cfg.maxLifetime )
{
lotteryStage = uint8( STAGE.FINISHING );
return;
}
// Compute & check the finishing criteria.
// Notice that we adjust the config-specified fund gain
// percentage increase to uint-mode, by adding 100 percents,
// because we don't deal with negative percentages, and here
// we represent loss as a percentage below 100%, and gains
// as percentage above 100%.
// So, if in regular gains notation, it's said 10% gain,
// in uint mode, it's said 110% relative increase.
//
// (Also, remember that losses are impossible in our lottery
// working scheme).
if( lotStorage.getHolderCount() >= cfg.finishCriteria_minNumberOfHolders
&&
getCurrentEthFunds() >= cfg.finishCriteria_minFunds
&&
(block.timestamp - startDate) >= cfg.finishCriteria_minTimeActive )
{
if( onStage( STAGE.ACTIVE ) )
{
// All conditions are met - start the finishing stage.
lotteryStage = uint8( STAGE.FINISHING );
emit FinishingStageStarted();
}
}
else if( onStage( STAGE.FINISHING ) )
{
// However, what if some condition was not met, but we're
// already on the finishing stage?
// If so, we must stop the finishing stage.
// But what to do with the finishing probability?
// Config specifies if it should be reset or maintain it's
// value until the next time finishing stage is started.
lotteryStage = uint8( STAGE.ACTIVE );
if( cfg.finish_resetProbabilityOnStop )
finishProbablity = cfg.finish_initialProbability;
emit FinishingStageStopped();
}
}
/**
* We're currently on finishing stage - so let's check if
* we should end the lottery block.timestamp!
*
* This function is called from _transfer(), only if we're sure
* that we're currently on finishing stage (onFinishingStage
* variable is set).
*
* Here, we compute the pseudo-random number from hash of
* current message's sender, block.timestamp, and other values,
* and modulo it to the current finish probability.
* If it's equal to 1, then we end the lottery!
*
* Also, here we update the finish probability according to
* probability update criteria - holder count, and tx count.
*
* @param holderCountChanged - indicates whether Holder Count
* has changed during this transfer (new holder joined, or
* a holder sold all his tokens).
*/
function checkForEnding( bool holderCountChanged )
internal
{
// At first, check if lottery max lifetime is exceeded.
// If so, start ending procedures right block.timestamp.
if( (block.timestamp - startDate) > cfg.maxLifetime )
{
startEndingStage();
return;
}
// Now, we know that lottery lifetime is still OK, and we're
// currently on Finishing Stage (because this function is
// called only when onFinishingStage is set).
//
// Now, check if we should End the lottery, by computing
// a modulo on a pseudo-random number, which is a transfer
// hash, computed for every transfer on _transfer() function.
//
// Get the modulo amount according to current finish
// probability.
// We use precision of 0.01% - notice the "10000 *" before
// 100 PERCENT.
// Later, when modulo'ing, we'll check if value is below 10000.
//
uint prec = 10000;
uint modAmount = (prec * _100PERCENT) / finishProbablity;
if( ( transferHashValue % modAmount ) <= prec )
{
// Finish probability is met! Commence lottery end -
// start Ending Stage.
startEndingStage();
return;
}
// Finish probability wasn't met.
// Update the finish probability, by increasing it!
// Transaction count criteria.
// As we know that this function is called on every new
// transfer (transaction), we don't check if transactionCount
// increased or not - we just perform probability update.
finishProbablity += cfg.finish_probabilityIncreaseStep_transaction;
// Now, perform holder count criteria update.
// Finish probability increases, no matter if holder count
// increases or decreases.
if( holderCountChanged )
finishProbablity += cfg.finish_probabilityIncreaseStep_holder;
}
/**
* Start the Ending Stage, by De-Activating the lottery,
* to deny all further token transfers (excluding the one when
* removing liquidity from Uniswap), and transition into the
* Mining Phase - set the lotteryStage to MINING.
*/
function startEndingStage()
internal
{
lotteryStage = uint8( STAGE.ENDING_MINING );
}
/**
* Execute the first step of the Mining Stage - request a
* Random Seed from the Randomness Provider.
*
* Here, we call the Randomness Provider, asking for a true random seed
* to be passed to us into our callback, named
* "finish_randomnessProviderCallback()".
*
* When that callback will be called, our storage's random seed will
* be set, and we'll be able to start the Ending Algorithm on
* further mining steps.
*
* Notice that Randomness Provider must already be funded, to
* have enough Ether for Provable fee and the gas costs of our
* callback function, which are quite high, because of winner
* selection algorithm, which is computationally expensive.
*
* The Randomness Provider is always funded by the Pool,
* right before the Pool deploys and starts a new lottery, so
* as every lottery calls the Randomness Provider only once,
* the one-call-fund method for every lottery is sufficient.
*
* Also notice, that Randomness Provider might fail to call
* our callback due to some unknown reasons!
* Then, the lottery profits could stay locked in this
* lottery contract forever ?!!
*
* No! We've thought about that - we've implemented the
* Alternative Ending mechanism, where, if specific time passes
* after we've made a request to Randomness Provider, and
* callback hasn't been called yet, we allow external actor to
* execute the Alternative ending, which basically does the
* same things as the default ending, just that the Random Seed
* will be computed locally in our contract, using the
* Pseudo-Random mechanism, which could compute a reasonably
* fair and safe value using data from holder array, and other
* values, described in more detail on corresponding function's
* description.
*/
function mine_requestRandomSeed()
internal
{
// We're sure that the Randomness Provider has enough funds.
// Execute the random request, and get ready for Ending Algorithm.
IRandomnessProvider( randomnessProvider )
.requestRandomSeedForLotteryFinish();
// Store the time when random seed has been requested, to
// be able to alternatively handle the lottery finish, if
// randomness provider doesn't call our callback for some
// reason.
finish_timeRandomSeedRequested = uint32( block.timestamp );
// Emit appropriate events.
emit RandomnessProviderCalled();
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Transfer the Owner & Pool profit shares, when lottery ends.
* This function is the first one that's executed on the Mining
* Stage.
* This is the first step of Mining. So, the Miner who executes this
* function gets the mining reward.
*
* This function's job is to Gather the Profits & Initial Funds,
* and Transfer them to Profiters - that is, to The Pool, and
* to The Owner.
*
* The Miners' profit share and Winner Prize Fund stay in this
* contract.
*
* On this function, we (in this order):
*
* 1. Remove all liquidity from Uniswap (if using Uniswap Mode),
* pulling it to our contract's wallet.
*
* 2. Transfer the Owner and the Pool ETH profit shares to
* Owner and Pool addresses.
*
* * This function transfers Ether out of our contract:
* - We transfer the Profits to Pool and Owner addresses.
*/
function mine_removeUniswapLiquidityAndTransferProfits()
internal
mutexLOCKED
{
// We've already approved our token allowance to Router.
// Now, approve Uniswap liquidity token's Router allowance.
ERC20( exchangeAddress ).approve( address(uniswapRouter), uint(-1) );
// Enable the SPECIAL-TRANSFER mode, to allow Uniswap to transfer
// the tokens from Pair to Router, and then from Router to us.
specialTransferModeEnabled = true;
// Remove liquidity!
uint amountETH = uniswapRouter
.removeLiquidityETHSupportingFeeOnTransferTokens(
address(this), // address token,
ERC20( exchangeAddress ).balanceOf( address(this) ),
0, // uint amountTokenMin,
0, // uint amountETHMin,
address(this), // address to,
(block.timestamp + 10000000) // uint deadline
);
// Tokens are transfered. Disable the special transfer mode.
specialTransferModeEnabled = false;
// Check that we've got a correct amount of ETH.
require( address(this).balance >= amountETH &&
address(this).balance >= cfg.initialFunds/*,
"Incorrect amount of ETH received from Uniswap!" */);
// Compute the Profit Amount (current balance - initial funds).
ending_totalReturn = uint128( address(this).balance );
ending_profitAmount = ending_totalReturn - uint128( cfg.initialFunds );
// Compute, and Transfer Owner's profit share and
// Pool's profit share to their respective addresses.
uint poolShare = ( ending_profitAmount * cfg.poolProfitShare ) /
( _100PERCENT );
uint ownerShare = ( ending_profitAmount * cfg.ownerProfitShare ) /
( _100PERCENT );
// To pool, transfer it's profit share plus initial funds.
IUniLotteryPool( poolAddress ).lotteryFinish
{ value: poolShare + cfg.initialFunds }
( ending_totalReturn, ending_profitAmount );
// Transfer Owner's profit share.
OWNER_ADDRESS.transfer( ownerShare );
// Emit ending event.
emit LotteryEnd( ending_totalReturn, ending_profitAmount );
}
/**
* Executes a single step of the Winner Selection Algorithm
* (the Ending Algorithm).
* The algorithm itself is being executed in the Storage contract.
*
* On current design, whole algorithm is executed in a single step.
*
* This function is executed only in the Mining stage, and
* accounts for most of the gas spent during mining.
*/
function mine_executeEndingAlgorithmStep()
internal
{
// Launch the winner algorithm, to execute the next step.
lotStorage.executeWinnerSelectionAlgorithm();
}
// =============== Public functions =============== //
/**
* Constructor of this delegate code contract.
* Here, we set OUR STORAGE's lotteryStage to DISABLED, because
* we don't want anybody to call this contract directly.
*/
constructor()
{
lotteryStage = uint8( STAGE.DISABLED );
}
/**
* Construct the lottery contract which is delegating it's
* call to us.
*
* @param config - LotteryConfig structure to use in this lottery.
*
* Future approach: ABI-encoded Lottery Config
* (different implementations might use different config
* structures, which are ABI-decoded inside the implementation).
*
* Also, this "config" includes the ABI-encoded temporary values,
* which are not part of persisted LotteryConfig, but should
* be used only in constructor - for example, values to be
* assigned to storage variables, such as ERC20 token's
* name, symbol, and decimals.
*
* @param _poolAddress - Address of the Main UniLottery Pool, which
* provides initial funds, and receives it's profit share.
*
* @param _randomProviderAddress - Address of a Randomness Provider,
* to use for obtaining random seeds.
*
* @param _storageAddress - Address of a Lottery Storage.
* Storage contract is a separate contract which holds all
* lottery token holder data, such as intermediate scores.
*
*/
function construct(
LotteryConfig memory config,
address payable _poolAddress,
address _randomProviderAddress,
address _storageAddress )
external
{
// Check if contract wasn't already constructed!
require( poolAddress == address( 0 )/*,
"Contract is already constructed!" */);
// Set the Pool's Address - notice that it's not the
// msg.sender, because lotteries aren't created directly
// by the Pool, but by the Lottery Factory!
poolAddress = _poolAddress;
// Set the Randomness Provider address.
randomnessProvider = _randomProviderAddress;
// Check the minimum & maximum requirements for config
// profit & lifetime parameters.
require( config.maxLifetime <= MAX_LOTTERY_LIFETIME/*,
"Lottery maximum lifetime is too high!" */);
require( config.poolProfitShare >= MIN_POOL_PROFITS &&
config.poolProfitShare <= MAX_POOL_PROFITS/*,
"Pool profit share is invalid!" */);
require( config.ownerProfitShare >= MIN_OWNER_PROFITS &&
config.ownerProfitShare <= MAX_OWNER_PROFITS/*,
"Owner profit share is invalid!" */);
require( config.minerProfitShare >= MIN_MINER_PROFITS &&
config.minerProfitShare <= MAX_MINER_PROFITS/*,
"Miner profit share is invalid!" */);
// Check if time factor divisor is higher than 2 minutes.
// That's because int40 wouldn't be able to handle precisions
// of smaller time factor divisors.
require( config.timeFactorDivisor >= 2 minutes /*,
"Time factor divisor is lower than 2 minutes!"*/ );
// Check if winner profit share is good.
uint32 totalWinnerShare =
(_100PERCENT) - config.poolProfitShare
- config.ownerProfitShare
- config.minerProfitShare;
require( totalWinnerShare >= MIN_WINNER_PROFIT_SHARE/*,
"Winner profit share is too low!" */);
// Check if ending algorithm params are good.
require( config.randRatio_scorePart != 0 &&
config.randRatio_randPart != 0 &&
( config.randRatio_scorePart +
config.randRatio_randPart ) < 10000/*,
"Random Ratio params are invalid!" */);
require( config.endingAlgoType ==
uint8( EndingAlgoType.MinedWinnerSelection ) ||
config.endingAlgoType ==
uint8( EndingAlgoType.WinnerSelfValidation ) ||
config.endingAlgoType ==
uint8( EndingAlgoType.RolledRandomness )/*,
"Wrong Ending Algorithm Type!" */);
// Set the number of winners (winner count).
// If using Computed Sequence winner prize shares, set that
// value, and if it's zero, then we're using the Array-Mode
// prize share specification.
if( config.prizeSequence_winnerCount == 0 &&
config.winnerProfitShares.length != 0 )
config.prizeSequence_winnerCount =
uint16( config.winnerProfitShares.length );
// Setup our Lottery Storage - initialize, and set the
// Algorithm Config.
LotteryStorage _lotStorage = LotteryStorage( _storageAddress );
// Setup a Winner Score Config for the winner selection algo,
// to be used in the Lottery Storage.
LotteryStorage.WinnerAlgorithmConfig memory winnerConfig;
// Algorithm type.
winnerConfig.endingAlgoType = config.endingAlgoType;
// Individual player max score parts.
winnerConfig.maxPlayerScore_etherContributed =
config.maxPlayerScore_etherContributed;
winnerConfig.maxPlayerScore_tokenHoldingAmount =
config.maxPlayerScore_tokenHoldingAmount;
winnerConfig.maxPlayerScore_timeFactor =
config.maxPlayerScore_timeFactor;
winnerConfig.maxPlayerScore_refferalBonus =
config.maxPlayerScore_refferalBonus;
// Score-To-Random ratio parts.
winnerConfig.randRatio_scorePart = config.randRatio_scorePart;
winnerConfig.randRatio_randPart = config.randRatio_randPart;
// Set winner count (no.of winners).
winnerConfig.winnerCount = config.prizeSequence_winnerCount;
// Initialize the storage (bind it to our contract).
_lotStorage.initialize( winnerConfig );
// Set our immutable variable.
lotStorage = _lotStorage;
// Now, set our config to the passed config.
cfg = config;
// Might be un-needed (can be replaced by Constant on the MainNet):
WETHaddress = uniswapRouter.WETH();
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* Fallback Receive Ether function.
* Used to receive ETH funds back from Uniswap, on lottery's end,
* when removing liquidity.
*/
receive() external payable
{
emit FallbackEtherReceiver( msg.sender, msg.value );
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<
* PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Initialization function.
* Here, the most important startup operations are made -
* such as minting initial token supply and transfering it to
* the Uniswap liquidity pair, in exchange for UNI-v2 tokens.
*
* This function is called by the pool, when transfering
* initial funds to this contract.
*
* What's payable?
* - Pool transfers initial funds to our contract.
* - We transfer that initial fund Ether to Uniswap liquidity pair
* when creating/providing it.
*/
function initialize()
external
payable
poolOnly
mutexLOCKED
onlyOnStage( STAGE.INITIAL )
{
// Check if pool transfered correct amount of funds.
require( address( this ).balance == cfg.initialFunds/*,
"Invalid amount of funds transfered!" */);
// Set start date.
startDate = uint32( block.timestamp );
// Set the initial transfer hash value.
transferHashValue = uint( keccak256(
abi.encodePacked( msg.sender, block.timestamp ) ) );
// Set initial finish probability, to be used when finishing
// stage starts.
finishProbablity = cfg.finish_initialProbability;
// ===== Active operations - mint & distribute! ===== //
// Mint full initial supply of tokens to our contract address!
_mint( address(this),
uint( cfg.initialTokenSupply ) * (10 ** decimals) );
// Now - prepare to create a new Uniswap Liquidity Pair,
// with whole our total token supply and initial funds ETH
// as the two liquidity reserves.
// Approve Uniswap Router to allow it to spend our tokens.
// Set maximum amount available.
_approve( address(this), address( uniswapRouter ), uint(-1) );
// Provide liquidity - the Router will automatically
// create a new Pair.
uniswapRouter.addLiquidityETH
{ value: address(this).balance }
(
address(this), // address token,
totalSupply(), // uint amountTokenDesired,
totalSupply(), // uint amountTokenMin,
address(this).balance, // uint amountETHMin,
address(this), // address to,
(block.timestamp + 1000) // uint deadline
);
// Get the Pair address - that will be the exchange address.
exchangeAddress = IUniswapFactory( uniswapRouter.factory() )
.getPair( WETHaddress, address(this) );
// We assume that the token reserves of the pair are good,
// and that we own the full amount of liquidity tokens.
// Find out which of the pair tokens is WETH - is it the
// first or second one. Use it later, when getting our share.
if( IUniswapPair( exchangeAddress ).token0() == WETHaddress )
uniswap_ethFirst = true;
else
uniswap_ethFirst = false;
// Move to ACTIVE lottery stage.
// Now, all token transfers will be allowed.
lotteryStage = uint8( STAGE.ACTIVE );
// Lottery is initialized. We're ready to emit event.
emit LotteryInitialized();
}
// Return this lottery's initial funds, as were specified in the config.
//
function getInitialFunds() external view
returns( uint )
{
return cfg.initialFunds;
}
// Return active (still not returned to pool) initial fund value.
// If no-longer-active, return 0 (default) - because funds were
// already returned back to the pool.
//
function getActiveInitialFunds() external view
returns( uint )
{
if( onStage( STAGE.ACTIVE ) )
return cfg.initialFunds;
return 0;
}
/**
* Get current Exchange's Token and ETH reserves.
* We're on Uniswap mode, so get reserves from Uniswap.
*/
function getReserves()
external view
returns( uint _ethReserve, uint _tokenReserve )
{
// Use data from Uniswap pair contract.
( uint112 res0, uint112 res1, ) =
IUniswapPair( exchangeAddress ).getReserves();
if( uniswap_ethFirst )
return ( res0, res1 );
else
return ( res1, res0 );
}
/**
* Get our share (ETH amount) of the Uniswap Pair ETH reserve,
* of our Lottery tokens ULT-WETH liquidity pair.
*/
function getCurrentEthFunds()
public view
returns( uint ethAmount )
{
IUniswapPair pair = IUniswapPair( exchangeAddress );
( uint112 res0, uint112 res1, ) = pair.getReserves();
uint resEth = uint( uniswap_ethFirst ? res0 : res1 );
// Compute our amount of the ETH reserve, based on our
// percentage of our liquidity token balance to total supply.
uint liqTokenPercentage =
( pair.balanceOf( address(this) ) * (_100PERCENT) ) /
( pair.totalSupply() );
// Compute and return the ETH reserve.
return ( resEth * liqTokenPercentage ) / (_100PERCENT);
}
/**
* Get current finish probability.
* If it's ACTIVE stage, return 0 automatically.
*/
function getFinishProbability()
external view
returns( uint32 )
{
if( onStage( STAGE.FINISHING ) )
return finishProbablity;
return 0;
}
/**
* Generate a referral ID for msg.sender, who must be a token holder.
* Referral ID is used to refer other wallets into playing our
* lottery.
* - Referrer gets bonus points for every wallet that bought
* lottery tokens and specified his referral ID.
* - Referrees (wallets who got referred by registering a valid
* referral ID, corresponding to some referrer), get some
* bonus points for specifying (registering) a referral ID.
*
* Referral ID is a uint256 number, which is generated by
* keccak256'ing the holder's address, holder's current
* token ballance, and current time.
*/
function generateReferralID()
external
onlyOnStage( STAGE.ACTIVE )
{
uint256 refID = lotStorage.generateReferralID( msg.sender );
// Emit approppriate events.
emit ReferralIDGenerated( msg.sender, refID );
}
/**
* Register a referral for a msg.sender (must be token holder),
* using a valid referral ID got from a referrer.
* This function is called by a referree, who obtained a
* valid referral ID from some referrer, who previously
* generated it using generateReferralID().
*
* You can only register a referral once!
* When you do so, you get bonus referral points!
*/
function registerReferral(
uint256 referralID )
external
onlyOnStage( STAGE.ACTIVE )
{
address referrer = lotStorage.registerReferral(
msg.sender,
cfg.playerScore_referralRegisteringBonus,
referralID );
// Emit approppriate events.
emit ReferralRegistered( msg.sender, referrer, referralID );
}
/**
* The most important function of this contract - Transfer Function.
*
* Here, all token burning, intermediate score tracking, and
* finish condition checking is performed, according to the
* properties specified in config.
*/
function _transfer( address sender,
address receiver,
uint256 amount )
internal
override
{
// Check if transfers are allowed in current state.
// On Non-Active stage, transfers are allowed only from/to
// our contract.
// As we don't have Standalone Mode on this lottery variation,
// that means that tokens to/from our contract are travelling
// only when we transfer them to Uniswap Pair, and when
// Uniswap transfers them back to us, on liquidity remove.
//
// On this state, we also don't perform any burns nor
// holding trackings - just transfer and return.
if( !onStage( STAGE.ACTIVE ) &&
!onStage( STAGE.FINISHING ) &&
( sender == address(this) || receiver == address(this) ||
specialTransferModeEnabled ) )
{
super._transfer( sender, receiver, amount );
return;
}
// Now, we know that we're NOT on special mode.
// Perform standard checks & brecks.
require( ( onStage( STAGE.ACTIVE ) ||
onStage( STAGE.FINISHING ) )/*,
"Token transfers are only allowed on ACTIVE stage!" */);
// Can't transfer zero tokens, or use address(0) as sender.
require( amount != 0 && sender != address(0)/*,
"Amount is zero, or transfering from zero address." */);
// Compute the Burn Amount - if buying tokens from an exchange,
// we use a lower burn rate - to incentivize buying!
// Otherwise (if selling or just transfering between wallets),
// we use a higher burn rate.
uint burnAmount;
// It's a buy - sender is an exchange.
if( sender == exchangeAddress )
burnAmount = ( amount * cfg.burn_buyerRate ) / (_100PERCENT);
else
burnAmount = ( amount * cfg.burn_defaultRate ) / (_100PERCENT);
// Now, compute the final amount to be gotten by the receiver.
uint finalAmount = amount - burnAmount;
// Check if receiver's balance won't exceed the max-allowed!
// Receiver must not be an exchange.
if( receiver != exchangeAddress )
{
require( !transferExceedsMaxBalance( receiver, finalAmount )/*,
"Receiver's balance would exceed maximum after transfer!"*/);
}
// Now, update holder data array accordingly.
bool holderCountChanged = updateHolderData_preTransfer(
sender,
receiver,
amount, // Amount Sent (Pre-Fees)
finalAmount // Amount Received (Post-Fees).
);
// All is ok - perform the burn and token transfers block.timestamp.
// Burn token amount from sender's balance.
super._burn( sender, burnAmount );
// Finally, transfer the final amount from sender to receiver.
super._transfer( sender, receiver, finalAmount );
// Compute new Pseudo-Random transfer hash, which must be
// computed for every transfer, and is used in the
// Finishing Stage as a pseudo-random unique value for
// every transfer, by which we determine whether lottery
// should end on this transfer.
//
// Compute it like this: keccak the last (current)
// transferHashValue, msg.sender, sender, receiver, amount.
transferHashValue = uint( keccak256( abi.encodePacked(
transferHashValue, msg.sender, sender, receiver, amount ) ) );
// Check if we should be starting a finishing stage block.timestamp.
checkFinishingStageConditions();
// If we're on finishing stage, check for ending conditions.
// If ending check is satisfied, the checkForEnding() function
// starts ending operations.
if( onStage( STAGE.FINISHING ) )
checkForEnding( holderCountChanged );
}
/**
* Callback function, which is called from Randomness Provider,
* after it obtains a random seed to be passed to us, after
* we have initiated The Ending Stage, on which random seed
* is used to generate random factors for Winner Selection
* algorithm.
*/
function finish_randomnessProviderCallback(
uint256 randomSeed,
uint256 /*callID*/ )
external
randomnessProviderOnly
{
// Set the random seed in the Storage Contract.
lotStorage.setRandomSeed( randomSeed );
// If algo-type is not Mined Winner Selection, then by block.timestamp
// we assume lottery as COMPL3T3D.
if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) )
{
lotteryStage = uint8( STAGE.COMPLETION );
completionDate = uint32( block.timestamp );
}
}
/**
* Function checks if we can initiate Alternative Seed generation.
*
* Alternative approach to Lottery Random Seed is used only when
* Randomness Provider doesn't work, and doesn't call the
* above callback.
*
* This alternative approach can be initiated by Miners, when
* these conditions are met:
* - Lottery is on Ending (Mining) stage.
* - Request to Randomness Provider was made at least X time ago,
* and our callback hasn't been called yet.
*
* If these conditions are met, we can initiate the Alternative
* Random Seed generation, which generates a seed based on our
* state.
*/
function alternativeSeedGenerationPossible()
internal view
returns( bool )
{
return ( onStage( STAGE.ENDING_MINING ) &&
( (block.timestamp - finish_timeRandomSeedRequested) >
cfg.REQUIRED_TIME_WAITING_FOR_RANDOM_SEED ) );
}
/**
* Return this lottery's config, using ABIEncoderV2.
*/
/*function getLotteryConfig()
external view
returns( LotteryConfig memory ourConfig )
{
return cfg;
}*/
/**
* Checks if Mining is currently available.
*/
function isMiningAvailable()
external view
returns( bool )
{
return onStage( STAGE.ENDING_MINING ) &&
( miningStep == 0 ||
( miningStep == 1 &&
( lotStorage.getRandomSeed() != 0 ||
alternativeSeedGenerationPossible() )
) );
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Mining function, to be executed on Ending (Mining) stage.
*
* "Mining" approach is used in this lottery, to use external
* actors for executing the gas-expensive Ending Algorithm,
* and other ending operations, such as profit transfers.
*
* "Miners" can be any external actors who call this function.
* When Miner successfully completes a Mining Step, he gets
* a Mining Reward, which is a certain portion of lottery's profit
* share, dedicated to Miners.
*
* NOT-IMPLEMENTED APPROACH:
*
* All these operations are divided into "mining steps", which are
* smaller components, which fit into reasonable gas limits.
* All "steps" are designed to take up similar amount of gas.
*
* For example, if total lottery profits (total ETH got from
* pulling liquidity out of Uniswap, minus initial funds),
* is 100 ETH, Miner Profit Share is 10%, and there are 5 mining
* steps total, then for a singe step executed, miner will get:
*
* (100 * 0.1) / 5 = 2 ETH.
*
* ---------------------------------
*
* CURRENTLY IMPLEMENTED APPROACH:
*
* As the above-defined approach would consume very much gas for
* inter-step intermediate state storage, we have thought that
* for block.timestamp, it's better to have only 2 mining steps, the second of
* which performs the whole Winner Selection Algorithm.
*
* This is because performing the whole algorithm at once would save
* us up to 10x more gas in total, than executing it in steps.
*
* However, this solution is not scalable, because algorithm has
* to fit into block gas limit (10,000,000 gas), so we are limited
* to a certain safe maximum number of token holders, which is
* empirically determined during testing, and defined in the
* MAX_SAFE_NUMBER_OF_HOLDERS constant, which is checked against the
* config value "finishCriteria_minNumberOfHolders" in constructor.
*
* So, in this approach, there are only 2 mining steps:
*
* 1. Remove liquidity from Uniswap, transfer profit shares to
* the Pool and the Owner Address, and request Random Seed
* from the Randomness Provider.
* Reward: 25% of total Mining Rewards.
*
* 2. Perform the whole Winner Selection Algorithm inside the
* Lottery Storage contract.
* Reward: 75% of total Mining Rewards.
*
* * Function transfers Ether out of our contract:
* - Transfers the current miner's reward to msg.sender.
*/
function mine()
external
onlyOnStage( STAGE.ENDING_MINING )
{
uint currentStepReward;
// Perform different operations on different mining steps.
// Step 0: Remove liquidity from Uniswap, transfer profits to
// Pool and Owner addresses. Also, request a Random Seed
// from the Randomness Provider.
if( miningStep == 0 )
{
mine_requestRandomSeed();
mine_removeUniswapLiquidityAndTransferProfits();
// Compute total miner reward amount, then compute this
// step's reward later.
uint totalMinerRewards =
( ending_profitAmount * cfg.minerProfitShare ) /
( _100PERCENT );
// Step 0 reward is 10% for Algo type 1.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
currentStepReward = ( totalMinerRewards * (10 * PERCENT) ) /
( _100PERCENT );
}
// If other algo-types, second step is not normally needed,
// so here we take 80% of miner rewards.
// If Randomness Provider won't give us a seed after
// specific amount of time, we'll initiate a second step,
// with remaining 20% of miner rewords.
else
{
currentStepReward = ( totalMinerRewards * (80 * PERCENT) ) /
( _100PERCENT );
}
require( currentStepReward <= totalMinerRewards/*, "BUG 1694" */);
}
// Step 1:
// If we use MinedWinnerSelection algo-type, then execute the
// winner selection algorithm.
// Otherwise, check if Random Provider hasn't given us a
// random seed long enough, so that we have to generate a
// seed locally.
else
{
// Check if we can go into this step when using specific
// ending algorithm types.
if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) )
{
require( lotStorage.getRandomSeed() == 0 &&
alternativeSeedGenerationPossible()/*,
"Second Mining Step is not available for "
"current Algo-Type on these conditions!" */);
}
// Compute total miner reward amount, then compute this
// step's reward later.
uint totalMinerRewards =
( ending_profitAmount * cfg.minerProfitShare ) /
( _100PERCENT );
// Firstly, check if random seed is already obtained.
// If not, check if we should generate it locally.
if( lotStorage.getRandomSeed() == 0 )
{
if( alternativeSeedGenerationPossible() )
{
// Set random seed inside the Storage Contract,
// but using our contract's transferHashValue as the
// random seed.
// We believe that this hash has enough randomness
// to be considered a fairly good random seed,
// because it has beed chain-computed for every
// token transfer that has occured in ACTIVE stage.
//
lotStorage.setRandomSeed( transferHashValue );
// If using Non-Mined algorithm types, reward for this
// step is 20% of miner funds.
if( cfg.endingAlgoType !=
uint8(EndingAlgoType.MinedWinnerSelection) )
{
currentStepReward =
( totalMinerRewards * (20 * PERCENT) ) /
( _100PERCENT );
}
}
else
{
// If alternative seed generation is not yet possible
// (not enough time passed since the rand.provider
// request was made), then mining is not available
// currently.
require( false/*, "Mining not yet available!" */);
}
}
// Now, we know that Random Seed is obtained.
// If we use this algo-type, perform the actual
// winner selection algorithm.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
mine_executeEndingAlgorithmStep();
// Set the prize amount to SECOND STEP prize amount (90%).
currentStepReward = ( totalMinerRewards * (90 * PERCENT) ) /
( _100PERCENT );
}
// Now we've completed both Mining Steps, it means MINING stage
// is finally completed!
// Transition to COMPLETION stage, and set lottery completion
// time to NOW.
lotteryStage = uint8( STAGE.COMPLETION );
completionDate = uint32( block.timestamp );
require( currentStepReward <= totalMinerRewards/*, "BUG 2007" */);
}
// Now, transfer the reward to miner!
// Check for bugs too - if the computed amount doesn't exceed.
// Increment the mining step - move to next step (if there is one).
miningStep++;
// Check & Lock the Re-Entrancy Lock for transfers.
require( ! reEntrancyMutexLocked/*, "Re-Entrant call detected!" */);
reEntrancyMutexLocked = true;
// Finally, transfer the reward to message sender!
msg.sender.transfer( currentStepReward );
// UnLock ReEntrancy Lock.
reEntrancyMutexLocked = false;
}
/**
* Function computes winner prize amount for winner at rank #N.
* Prerequisites: Must be called only on STAGE.COMPLETION stage,
* because we use the final profits amount here, and that value
* (ending_profitAmount) is known only on COMPLETION stage.
*
* @param rankingPosition - ranking position of a winner.
* @return finalPrizeAmount - prize amount, in Wei, of this winner.
*/
function getWinnerPrizeAmount(
uint rankingPosition )
public view
returns( uint finalPrizeAmount )
{
// Calculate total winner prize fund profit percentage & amount.
uint winnerProfitPercentage =
(_100PERCENT) - cfg.poolProfitShare -
cfg.ownerProfitShare - cfg.minerProfitShare;
uint totalPrizeAmount =
( ending_profitAmount * winnerProfitPercentage ) /
( _100PERCENT );
// We compute the prize amounts differently for the algo-type
// RolledRandomness, because distribution of these prizes is
// non-deterministic - multiple holders could fall onto the
// same ranking position, due to randomness of rolled score.
//
if( cfg.endingAlgoType == uint8(EndingAlgoType.RolledRandomness) )
{
// Here, we'll use Prize Sequence Factor approach differently.
// We'll use the prizeSequenceFactor value not to compute
// a geometric progression, but to compute an arithmetic
// progression, where each ranking position will get a
// prize equal to
// "totalPrizeAmount - rankingPosition * singleWinnerShare"
//
// singleWinnerShare is computed as a value corresponding
// to single-winner's share of total prize amount.
//
// Using such an approach, winner at rank 0 would get a
// prize equal to whole totalPrizeAmount, but, as the
// scores are rolled using random factor, it's very unlikely
// to get a such high score, so most likely such prize
// won't ever be claimed, but it is a possibility.
//
// Most of the winners in this approach are likely to
// roll scores in the middle, so would get prizes equal to
// 1-10% of total prize funds.
uint singleWinnerShare = totalPrizeAmount /
cfg.prizeSequence_winnerCount;
return totalPrizeAmount - rankingPosition * singleWinnerShare;
}
// Now, we know that ending algorithm is normal (deterministic).
// So, compute the prizes in a standard way.
// If using Computed Sequence: loop for "rankingPosition"
// iterations, while computing the prize shares.
// If "rankingPosition" is larger than sequencedWinnerCount,
// then compute the prize from sequence-leftover amount.
if( cfg.prizeSequenceFactor != 0 )
{
require( rankingPosition < cfg.prizeSequence_winnerCount/*,
"Invalid ranking position!" */);
// Leftover: If prizeSequenceFactor is 25%, it's 75%.
uint leftoverPercentage =
(_100PERCENT) - cfg.prizeSequenceFactor;
// Loop until the needed iteration.
uint loopCount = (
rankingPosition >= cfg.prizeSequence_sequencedWinnerCount ?
cfg.prizeSequence_sequencedWinnerCount :
rankingPosition
);
for( uint i = 0; i < loopCount; i++ )
{
totalPrizeAmount =
( totalPrizeAmount * leftoverPercentage ) /
( _100PERCENT );
}
// Get end prize amount - sequenced, or leftover.
// Leftover-mode.
if( loopCount == cfg.prizeSequence_sequencedWinnerCount &&
cfg.prizeSequence_winnerCount >
cfg.prizeSequence_sequencedWinnerCount )
{
// Now, totalPrizeAmount equals all leftover-group winner
// prize funds.
// So, just divide it by number of leftover winners.
finalPrizeAmount =
( totalPrizeAmount ) /
( cfg.prizeSequence_winnerCount -
cfg.prizeSequence_sequencedWinnerCount );
}
// Sequenced-mode
else
{
finalPrizeAmount =
( totalPrizeAmount * cfg.prizeSequenceFactor ) /
( _100PERCENT );
}
}
// Else, if we're using Pre-Specified Array of winner profit
// shares, just get the share at the corresponding index.
else
{
require( rankingPosition < cfg.winnerProfitShares.length );
finalPrizeAmount =
( totalPrizeAmount *
cfg.winnerProfitShares[ rankingPosition ] ) /
( _100PERCENT );
}
}
/**
* After lottery has completed, this function returns if msg.sender
* is one of lottery winners, and the position in winner rankings.
*
* Function must be used to obtain the ranking position before
* calling claimWinnerPrize().
*
* @param addr - address whose status to check.
*/
function getWinnerStatus( address addr )
external view
returns( bool isWinner, uint32 rankingPosition,
uint prizeAmount )
{
if( !onStage( STAGE.COMPLETION ) || balanceOf( addr ) == 0 )
return (false , 0, 0);
( isWinner, rankingPosition ) =
lotStorage.getWinnerStatus( addr );
if( isWinner )
{
prizeAmount = getWinnerPrizeAmount( rankingPosition );
if( prizeAmount > address(this).balance )
prizeAmount = address(this).balance;
}
}
/**
* Compute the intermediate Active Stage player score.
* This score is Player Score, not randomized.
* @param addr - address to check.
*/
function getPlayerIntermediateScore( address addr )
external view
returns( uint )
{
return lotStorage.getPlayerActiveStageScore( addr );
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Claim the winner prize of msg.sender, if he is one of the winners.
*
* This function must be provided a ranking position of msg.sender,
* which must be obtained using the function above.
*
* The Lottery Storage then just checks if holder address in the
* winner array element at position rankingPosition is the same
* as msg.sender's.
*
* If so, then claim request is valid, and we can give the appropriate
* prize to that winner.
* Prize can be determined by a computed factor-based sequence, or
* from the pre-specified winner array.
*
* * This function transfers Ether out of our contract:
* - Sends the corresponding winner prize to the msg.sender.
*
* @param rankingPosition - the position of Winner Array, that
* msg.sender says he is in (obtained using getWinnerStatus).
*/
function claimWinnerPrize(
uint32 rankingPosition )
external
onlyOnStage( STAGE.COMPLETION )
mutexLOCKED
{
// Check if msg.sender hasn't already claimed his prize.
require( ! prizeClaimersAddresses[ msg.sender ]/*,
"msg.sender has already claimed his prize!" */);
// msg.sender must have at least some of UniLottery Tokens.
require( balanceOf( msg.sender ) != 0/*,
"msg.sender's token balance can't be zero!" */);
// Check if there are any prize funds left yet.
require( address(this).balance != 0/*,
"All prize funds have already been claimed!" */);
// If using Mined Selection Algo, check if msg.sender is
// really on that ranking position - algo was already executed.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
require( lotStorage.minedSelection_isAddressOnWinnerPosition(
msg.sender, rankingPosition )/*,
"msg.sender is not on specified winner position!" */);
}
// For other algorithms, get ranking position by executing
// a specific algorithm of that algo-type.
else
{
bool isWinner;
( isWinner, rankingPosition ) =
lotStorage.getWinnerStatus( msg.sender );
require( isWinner/*, "msg.sender is not a winner!" */);
}
// Compute the prize amount, using our internal function.
uint finalPrizeAmount = getWinnerPrizeAmount( rankingPosition );
// If prize is small and computation precision errors occured,
// leading it to be larger than our balance, fix it.
if( finalPrizeAmount > address(this).balance )
finalPrizeAmount = address(this).balance;
// Transfer the Winning Prize to msg.sender!
msg.sender.transfer( finalPrizeAmount );
// Mark msg.sender as already claimed his prize.
prizeClaimersAddresses[ msg.sender ] = true;
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Transfer the leftover Winner Prize Funds of this contract to the
* Main UniLottery Pool, if prize claim deadline has been exceeded.
*
* Function can only be called from the Main Pool, and if some
* winners haven't managed to claim their prizes on time, their
* prizes will go back to UniLottery Pool.
*
* * Function transfers Ether out of our contract:
* - Transfer the leftover funds to the Pool (msg.sender).
*/
function getUnclaimedPrizes()
external
poolOnly
onlyOnStage( STAGE.COMPLETION )
mutexLOCKED
{
// Check if prize claim deadline has passed.
require( completionDate != 0 &&
( block.timestamp - completionDate ) > cfg.prizeClaimTime/*,
"Prize claim deadline not reached yet!" */);
// Just transfer it all to the Pool.
poolAddress.transfer( address(this).balance );
}
}
contract UniLotteryRandomnessProvider is usingProvable
{
// =============== E-Vent Section =============== //
// New Lottery Random Seed Request made.
event LotteryRandomSeedRequested(
uint id,
address lotteryAddress,
uint gasLimit,
uint totalEtherGiven
);
// Random seed obtained, and callback successfully completed.
event LotteryRandomSeedCallbackCompleted(
uint id
);
// UniLottery Pool scheduled a call.
event PoolCallbackScheduled(
uint id,
address poolAddress,
uint timeout,
uint gasLimit,
uint totalEtherGiven
);
// Pool scheduled callback successfully completed.
event PoolCallbackCompleted(
uint id
);
// Ether transfered into fallback.
event EtherTransfered(
address sender,
uint value
);
// =============== Structs & Enums =============== //
// Enum - type of the request.
enum RequestType {
LOTTERY_RANDOM_SEED,
POOL_SCHEDULED_CALLBACK
}
// Call Request Structure.
struct CallRequestData
{
// -------- Slot -------- //
// The ID of the request.
uint256 requestID;
// -------- Slot -------- //
// Requester address. Can be pool, or an ongoing lottery.
address requesterAddress;
// The Type of request (Random Seed or Pool Scheduled Callback).
RequestType reqType;
}
// Lottery request config - specifies gas limits that must
// be used for that specific lottery's callback.
// Must be set separately from CallRequest, because gas required
// is specified and funds are transfered by The Pool, before starting
// a lottery, and when that lottery ends, it just calls us, expecting
// it's gas cost funds to be already sent to us.
struct LotteryGasConfig
{
// -------- Slot -------- //
// The total ether funds that the pool has transfered to
// our contract for execution of this lottery's callback.
uint160 etherFundsTransferedForGas;
// The gas limit provided for that callback.
uint64 gasLimit;
}
// =============== State Variables =============== //
// -------- Slot -------- //
// Mapping of all currently pending or on-process requests
// from their Query IDs.
mapping( uint256 => CallRequestData ) pendingRequests;
// -------- Slot -------- //
// A mapping of Pool-specified-before-their-start lottery addresses,
// to their corresponding Gas Configs, which will be used for
// their end callbacks.
mapping( address => LotteryGasConfig ) lotteryGasConfigs;
// -------- Slot -------- //
// The Pool's address. We receive funds from it, and use it
// to check whether the requests are coming from ongoing lotteries.
address payable poolAddress;
// ============ Private/Internal Functions ============ //
// Pool-Only modifier.
modifier poolOnly
{
require( msg.sender == poolAddress/*,
"Function can only be called by the Main Pool!" */);
_;
}
// Ongoing Lottery Only modifier.
// Data must be fetch'd from the Pool.
modifier ongoingLotteryOnly
{
require( IMainUniLotteryPool( poolAddress )
.isLotteryOngoing( msg.sender )/*,
"Function can be called only by ongoing lotteries!" */);
_;
}
// ================= Public Functions ================= //
/**
* Constructor.
* Here, we specify the Provable proof type, to use for
* Random Datasource queries.
*/
constructor()
{
// Set the Provable proof type for Random Queries - Ledger.
provable_setProof( proofType_Ledger );
}
/**
* Initialization function.
* Called by the Pool, on Pool's constructor, to initialize this
* randomness provider.
*/
function initialize() external
{
// Check if we were'nt initialized yet (pool address not set yet).
require( poolAddress == address( 0 )/*,
"Contract is already initialized!" */);
poolAddress = msg.sender;
}
/**
* The Payable Fallback function.
* This function is used by the Pool, to transfer the required
* funds to us, to be able to pay for Provable gas & fees.
*/
receive () external payable
{
emit EtherTransfered( msg.sender, msg.value );
}
/**
* Get the total Ether price for a request to specific
* datasource with specific gas limit.
* It just calls the Provable's internal getPrice function.
*/
// Random datasource.
function getPriceForRandomnessCallback( uint gasLimit )
external
returns( uint totalEtherPrice )
{
return provable_getPrice( "random", gasLimit );
}
// URL datasource (for callback scheduling).
function getPriceForScheduledCallback( uint gasLimit )
external
returns( uint totalEtherPrice )
{
return provable_getPrice( "URL", gasLimit );
}
/**
* Set the gas limit which should be used by the lottery deployed
* on address "lotteryAddr", when that lottery finishes and
* requests us to call it's ending callback with random seed
* provided.
* Also, specify the amount of Ether that the pool has transfered
* to us for the execution of this lottery's callback.
*/
function setLotteryCallbackGas(
address lotteryAddr,
uint64 callbackGasLimit,
uint160 totalEtherTransferedForThisOne )
external
poolOnly
{
LotteryGasConfig memory gasConfig;
gasConfig.gasLimit = callbackGasLimit;
gasConfig.etherFundsTransferedForGas = totalEtherTransferedForThisOne;
// Set the mapping entry for this lottery address.
lotteryGasConfigs[ lotteryAddr ] = gasConfig;
}
/**
* The Provable Callback, which will get called from Off-Chain
* Provable service, when it completes execution of our request,
* made before previously with provable_query variant.
*
* Here, we can perform 2 different tasks, based on request type
* (we get the CallRequestData from the ID passed by Provable).
*
* The different tasks are:
* 1. Pass Random Seed to Lottery Ending Callback.
* 2. Call a Pool's Scheduled Callback.
*/
function __callback(
bytes32 _queryId,
string memory _result,
bytes memory _proof )
public
override
{
// Check that the sender is Provable Services.
require( msg.sender == provable_cbAddress() );
// Get the Request Data storage pointer, and check if it's Set.
CallRequestData storage reqData =
pendingRequests[ uint256( _queryId ) ];
require( reqData.requestID != 0/*,
"Invalid Request Data structure (Response is Invalid)!" */);
// Check the Request Type - if it's a lottery asking for a
// random seed, or a Pool asking to call it's scheduled callback.
if( reqData.reqType == RequestType.LOTTERY_RANDOM_SEED )
{
// It's a lottery asking for a random seed.
// Check if Proof is valid, using the Base Contract's built-in
// checking functionality.
require( provable_randomDS_proofVerify__returnCode(
_queryId, _result, _proof ) == 0/*,
"Random Datasource Proof Verification has FAILED!" */);
// Get the Random Number by keccak'ing the random bytes passed.
uint256 randomNumber = uint256(
keccak256( abi.encodePacked( _result ) ) );
// Pass this Random Number as a Seed to the requesting lottery!
ILottery( reqData.requesterAddress )
.finish_randomnessProviderCallback(
randomNumber, uint( _queryId ) );
// Emit appropriate events.
emit LotteryRandomSeedCallbackCompleted( uint( _queryId ) );
}
// It's a pool, asking to call it's callback, that it scheduled
// to get called in some time before.
else if( reqData.reqType == RequestType.POOL_SCHEDULED_CALLBACK )
{
IMainUniLotteryPool( poolAddress )
.scheduledCallback( uint( _queryId ) );
// Emit appropriate events.
emit PoolCallbackCompleted( uint( _queryId ) );
}
// We're finished! Remove the request data from the pending
// requests mapping.
delete pendingRequests[ uint256( _queryId ) ];
}
/**
* This is the function through which the Lottery requests a
* Random Seed for it's ending callback.
* The gas funds needed for that callback's execution were already
* transfered to us from The Pool, at the moment the Pool created
* and deployed that lottery.
* The gas specifications are set in the LotteryGasConfig of that
* specific lottery.
* TODO: Also set the custom gas price.
*/
function requestRandomSeedForLotteryFinish()
external
ongoingLotteryOnly
returns( uint256 requestId )
{
// Check if gas limit (amount of gas) for this lottery was set.
require( lotteryGasConfigs[ msg.sender ].gasLimit != 0/*,
"Gas limit for this lottery was not set!" */);
// Check if the currently estimated price for this request
// is not higher than the one that the pool transfered funds for.
uint transactionPrice = provable_getPrice( "random",
lotteryGasConfigs[ msg.sender ].gasLimit );
if( transactionPrice >
lotteryGasConfigs[ msg.sender ].etherFundsTransferedForGas )
{
// If our balance is enough to execute the transaction, then
// ask pool if it agrees that we execute this transaction
// with higher price than pool has given funds to us for.
if( address(this).balance >= transactionPrice )
{
bool response = IMainUniLotteryPool( poolAddress )
.onLotteryCallbackPriceExceedingGivenFunds(
msg.sender,
transactionPrice,
lotteryGasConfigs[msg.sender].etherFundsTransferedForGas
);
require( response/*, "Pool has denied the request!" */);
}
// If price absolutely exceeds our contract's balance:
else {
require( false/*, "Request price exceeds contract's balance!" */);
}
}
// Set the Provable Query parameters.
// Execute the query as soon as possible.
uint256 QUERY_EXECUTION_DELAY = 0;
// Set the gas amount to the previously specified gas limit.
uint256 GAS_FOR_CALLBACK = lotteryGasConfigs[ msg.sender ].gasLimit;
// Request 8 random bytes (that's enough randomness with keccak).
uint256 NUM_RANDOM_BYTES_REQUESTED = 8;
// Execute the Provable Query!
uint256 queryId = uint256( provable_newRandomDSQuery(
QUERY_EXECUTION_DELAY,
NUM_RANDOM_BYTES_REQUESTED,
GAS_FOR_CALLBACK
) );
// Populate & Add the pending requests mapping entry.
CallRequestData memory requestData;
requestData.requestID = queryId;
requestData.reqType = RequestType.LOTTERY_RANDOM_SEED;
requestData.requesterAddress = msg.sender;
pendingRequests[ queryId ] = requestData;
// Emit an event - lottery just requested a random seed.
emit LotteryRandomSeedRequested(
queryId, msg.sender,
lotteryGasConfigs[ msg.sender ].gasLimit,
lotteryGasConfigs[ msg.sender ].etherFundsTransferedForGas
);
// Remove the just-used Lottery Gas Configs mapping entry.
delete lotteryGasConfigs[ msg.sender ];
// Return the ID of the query.
return queryId;
}
/**
* Schedule a call for the pool, using specified amount of gas,
* and executing after specified amount of time.
* Accomplished using an empty URL query, and setting execution
* delay to the specified timeout.
* On execution, __callback() calls the Pool's scheduledCallback()
* function.
*
* @param timeout - how much time to delay the execution of callback.
* @param gasLimit - gas limit to use for the callback's execution.
* @param etherFundsTransferedForGas - how much Ether has the Pool
* transfered to our contract before calling this function,
* to be used only for this operation.
*/
function schedulePoolCallback(
uint timeout,
uint gasLimit,
uint etherFundsTransferedForGas )
external
poolOnly
returns( uint256 requestId )
{
// Price exceeding transfered funds doesn't need to be checked
// here, because pool transfers required funds just before
// calling this function, so price can't change between transfer
// and this function's call.
// Execute the query on specified timeout, with a
// specified Gas Limit.
uint queryId = uint(
provable_query( timeout, "URL", "", gasLimit )
);
// Populate & Add the pending requests mapping entry.
CallRequestData memory requestData;
requestData.requestID = queryId;
requestData.reqType = RequestType.POOL_SCHEDULED_CALLBACK;
requestData.requesterAddress = msg.sender;
pendingRequests[ queryId ] = requestData;
// Emit an event - lottery just requested a random seed.
emit PoolCallbackScheduled( queryId, poolAddress, timeout, gasLimit,
etherFundsTransferedForGas );
// Return a query ID.
return queryId;
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Sends the specified amount of Ether back to the Pool.
* WARNING: Future Provable requests might fail due to insufficient
* funds! No checks are made to ensure sufficiency.
*/
function sendFundsToPool( uint etherAmount )
external
poolOnly
{
poolAddress.transfer( etherAmount );
}
/**
* Set the gas price to be used for future Provable queries.
* Used to change the default gas in times of congested networks.
*/
function setGasPrice( uint _gasPrice )
external
poolOnly
{
// Limit gas price to 600 GWei.
require( _gasPrice <= 600 * (10 ** 9)/*,
"Specified gas price is higher than 600 GWei !" */);
provable_setCustomGasPrice( _gasPrice );
}
}
|
Update holder array, if new token holder joined, or if a holder transfered his whole balance. Sender transferred his whole balance - no longer a holder. Use the Router's functionality. Set the exchange path to WETH -> ULT (ULT is Lottery Token, and it's address is our address). Compute time factor value for the current ether value. buySellValue is POSITIVE. When computing Time Factors, leave only 2 ether decimals. Update and propagate the buyer (receiver) scores. Use the Router's functionality. Set the exchange path to ULT -> WETH (ULT is Lottery Token, and it's address is our address). It's a sell (ULT -> WETH), so set value to NEGATIVE. Compute time factor value for the current ether value. buySellValue is NEGATIVE. Update and propagate the seller (sender) scores.
|
function updateHolderData_preTransfer(
address sender,
address receiver,
uint256 amountSent,
uint256 amountReceived )
internal
returns( bool holderCountChanged )
{
holderCountChanged = false;
if( balanceOf( sender ) == amountSent )
{
lotStorage.removeHolder( sender );
holderCountChanged = true;
}
if( balanceOf( receiver ) == 0 && amountReceived > 0 )
{
lotStorage.addHolder( receiver );
holderCountChanged = true;
}
int buySellValue;
if( sender == exchangeAddress && receiver != exchangeAddress )
{
address[] memory path = new address[]( 2 );
path[ 0 ] = WETHaddress;
path[ 1 ] = address(this);
uint[] memory ethAmountIn = uniswapRouter.getAmountsIn(
);
buySellValue = int( ethAmountIn[ 0 ] );
int timeFactorValue = ( buySellValue / (1 ether / 100) ) *
int( (block.timestamp - startDate) / cfg.timeFactorDivisor );
if( timeFactorValue == 0 )
timeFactorValue = 1;
lotStorage.updateAndPropagateScoreChanges(
receiver,
int80( buySellValue ),
int80( timeFactorValue ),
int80( amountReceived ) );
}
else if( sender != exchangeAddress && receiver == exchangeAddress )
{
address[] memory path = new address[]( 2 );
path[ 0 ] = address(this);
path[ 1 ] = WETHaddress;
uint[] memory ethAmountOut = uniswapRouter.getAmountsOut(
);
buySellValue = int( -1 ) * int( ethAmountOut[ 1 ] );
int timeFactorValue = ( buySellValue / (1 ether / 100) ) *
int( (block.timestamp - startDate) / cfg.timeFactorDivisor );
if( timeFactorValue == 0 )
timeFactorValue = -1;
lotStorage.updateAndPropagateScoreChanges(
sender,
int80( buySellValue ),
int80( timeFactorValue ),
-1 * int80( amountSent ) );
}
else {
buySellValue = 0;
lotStorage.updateAndPropagateScoreChanges( sender, 0, 0,
-1 * int80( amountSent ) );
lotStorage.updateAndPropagateScoreChanges( receiver, 0, 0,
int80( amountReceived ) );
}
uint ethFunds = getCurrentEthFunds();
if( !fundGainRequirementReached &&
ethFunds >= cfg.fundRequirement_denySells )
{
fundGainRequirementReached = true;
}
if( fundGainRequirementReached &&
buySellValue < 0 &&
( uint( -1 * buySellValue ) >= ethFunds ||
ethFunds - uint( -1 * buySellValue ) <
cfg.fundRequirement_denySells ) )
{
require( false/*, "This sell would drop the lottery ETH funds"
"below the minimum requirement threshold!" */);
}
}
| 7,578,526
|
pragma solidity >=0.5;
pragma experimental ABIEncoderV2;
/**
* @title DexStatus
* @dev Status for Dex
*/
contract DexStatus {
string constant ONLY_RELAYER = "ONLY_RELAYER";
string constant ONLY_AIRDROP = "ONLY_AIRDROP";
string constant ONLY_INACTIVITY = "ONLY_INACTIVITY";
string constant ONLY_WITHDRAWALAPPROVED = "ONLY_WITHDRAWALAPPROVED";
string constant INVALID_NONCE = "INVALID_NONCE";
string constant INVALID_PERIOD = "INVALID_PERIOD";
string constant INVALID_AMOUNT = "INVALID_AMOUNT";
string constant INVALID_TIME = "INVALID_TIME";
string constant INVALID_GASTOKEN = "INVALID_GASTOKEN";
string constant TRANSFER_FAILED = "TRANSFER_FAILED";
string constant ECRECOVER_FAILED = "ECRECOVER_FAILED";
string constant INSUFFICIENT_FOUND = "INSUFFICIENT";
string constant TRADE_EXISTS = "TRADED";
string constant WITHDRAW_EXISTS = "WITHDRAWN";
string constant MAX_VALUE_LIMIT = "MAX_LIMIT";
string constant AMOUNT_EXCEEDED = "AMOUNT_EXCEEDED";
}
/**
* @title IGasStorage
* @dev GasStorage interface to burn and mint gastoken
*/
interface IGasStorage
{
function mint(uint256 value) external;
function burn(uint256 value) external;
function balanceOf() external view returns (uint256 balance);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = tx.origin;
}
/**
* @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;
}
}
/**
* @dev ERC20 interface
*/
interface ERC20 {
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success) ;
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) view external returns (uint256 remaining);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title Dex
* @dev Smart contract for https://www.dex.io
*/
contract Dex is Ownable,DexStatus {
using SafeMath for uint256;
struct Order
{
address token;
address baseToken;
address user;
uint256 tokenAmount;
uint256 baseTokenAmount;
uint nonce;
uint expireTime;
uint maxGasFee;
uint timestamp;
address gasToken;
bool sell;
uint8 V;
bytes32 R;
bytes32 S;
uint signType;
}
struct TradeInfo {
uint256 tradeTokenAmount;
uint256 tradeTakerFee;
uint256 tradeMakerFee;
uint256 tradeGasFee;
uint tradeNonce;
address tradeGasToken;
}
mapping (address => mapping (address => uint256)) public _balances;
mapping (address => uint) public _invalidOrderNonce;
mapping (bytes32 => uint256) public _orderFills;
mapping (address => bool) public _relayers;
mapping (bytes32 => bool) public _traded;
mapping (bytes32 => bool) public _withdrawn;
mapping (bytes32 => uint256) public _orderGasFee;
mapping (address => uint) public _withdrawalApplication;
address public _feeAccount;
address public _airdropContract;
address public _gasStorage;
uint256 public _withdrawalApplicationPeriod = 10 days;
uint256 public _takerFeeRate = 0.002 ether;
uint256 public _makerFeeRate = 0.001 ether;
string private constant EIP712DOMAIN_TYPE = "EIP712Domain(string name)";
bytes32 private constant EIP712DOMAIN_TYPEHASH = keccak256(abi.encodePacked(EIP712DOMAIN_TYPE));
bytes32 private constant DOMAIN_SEPARATOR = keccak256(abi.encode(EIP712DOMAIN_TYPEHASH,keccak256(bytes("Dex.io"))));
string private constant ORDER_TYPE = "Order(address token,address baseToken,uint256 tokenAmount,uint256 baseTokenAmount,uint256 nonce,bool sell,uint256 expireTime,uint256 maxGasFee,address gasToken,uint timestamp)";
bytes32 private constant ORDER_TYPEHASH = keccak256(abi.encodePacked(ORDER_TYPE));
string private constant WITHDRAW_TYPE = "Withdraw(address token,uint256 tokenAmount,address to,uint256 nonce,address feeToken,uint256 feeWithdrawal,uint timestamp)";
bytes32 private constant WITHDRAW_TYPEHASH = keccak256(abi.encodePacked(WITHDRAW_TYPE));
event Trade(bytes32 takerHash,bytes32 makerHash,uint256 tradeAmount,uint256 tradeBaseTokenAmount,uint256 tradeNonce,uint256 takerCostFee,
uint makerCostFee,bool sellerIsMaker,uint256 gasFee);
event Balance(uint256 takerBaseTokenBalance,uint256 takerTokenBalance,uint256 makerBaseTokenBalance,uint256 makerTokenBalance);
event Deposit(address indexed token, address indexed user, uint256 amount, uint256 balance);
event Withdraw(address indexed token,address indexed from,address indexed to, uint256 amount, uint256 balance);
event Transfer(address indexed token,address indexed from,address indexed to, uint256 amount, uint256 fromBalance,uint256 toBalance);
event Airdrop(address indexed to, address indexed token,uint256 amount);
event WithdrawalApplication(address user,uint timestamp);
modifier onlyRelayer {
if (msg.sender != owner && !_relayers[msg.sender]) revert(ONLY_RELAYER);
_;
}
modifier onlyAirdropContract {
if (msg.sender != _airdropContract) revert(ONLY_AIRDROP);
_;
}
/**
* @dev approved in 10 days
*/
modifier onlyWithdrawalApplicationApproved {
require (
_withdrawalApplication[msg.sender] != uint(0) &&
block.timestamp - _withdrawalApplicationPeriod > _withdrawalApplication[msg.sender],
ONLY_WITHDRAWALAPPROVED);
_;
}
/**
* @param feeAccount account to receive the fee
*/
constructor(address feeAccount) public {
_feeAccount = feeAccount;
}
/**
* @dev do no send eth to dex contract directly.
*/
function() external {
revert();
}
/**
* @dev set a relayer
*/
function setRelayer(address relayer, bool isRelayer) public onlyOwner {
_relayers[relayer] = isRelayer;
}
/**
* @dev check a relayer
*/
function isRelayer(address relayer) public view returns(bool) {
return _relayers[relayer];
}
/**
* @dev set account that receive the fee
*/
function setFeeAccount(address feeAccount) public onlyOwner {
_feeAccount = feeAccount;
}
/**
* @dev set set maker and taker fee rate
* @param makerFeeRate maker fee rate can't be more than 0.5%
* @param takerFeeRate taker fee rate can't be more than 0.5%
*/
function setFee(uint256 makerFeeRate,uint256 takerFeeRate) public onlyOwner {
require(makerFeeRate <= 0.005 ether && takerFeeRate <= 0.005 ether,MAX_VALUE_LIMIT);
_makerFeeRate = makerFeeRate;
_takerFeeRate = takerFeeRate;
}
/**
* @dev set gasStorage contract to save gas
*/
function setGasStorage(address gasStorage) public onlyOwner {
_gasStorage = gasStorage;
}
/**
* @dev set airdrop contract to implement airdrop function
*/
function setAirdrop(address airdrop) public onlyOwner{
_airdropContract = airdrop;
}
/**
* @dev set withdraw application period
* @param period the period can't be more than 10 days
*/
function setWithdrawalApplicationPeriod(uint period) public onlyOwner {
if(period > 10 days ){
return;
}
_withdrawalApplicationPeriod = period;
}
/**
* @dev invalid the orders before nonce
*/
function invalidateOrdersBefore(address user, uint256 nonce) public onlyRelayer {
if (nonce < _invalidOrderNonce[user]) {
revert(INVALID_NONCE);
}
_invalidOrderNonce[user] = nonce;
}
/**
* @dev deposit token
*/
function depositToken(address token, uint256 amount) public {
require(ERC20(token).transferFrom(msg.sender, address(this), amount),TRANSFER_FAILED);
_deposit(msg.sender,token,amount);
}
/**
* @dev deposit token from msg.sender to someone
*/
function depositTokenTo(address to,address token, uint256 amount) public {
require(ERC20(token).transferFrom(msg.sender, address(this), amount),TRANSFER_FAILED);
_deposit(to,token,amount);
}
/**
* @dev deposit eth
*/
function deposit() public payable {
_deposit(msg.sender,address(0),msg.value);
}
/**
* @dev deposit eth from msg.sender to someone
*/
function depositTo(address to) public payable {
_deposit(to,address(0),msg.value);
}
/**
* @dev _deposit
*/
function _deposit(address user,address token,uint256 amount) internal {
_balances[token][user] = _balances[token][user].add(amount);
emit Deposit(token, user, amount, _balances[token][user]);
}
/**
* @dev submit a withdrawal application, user can not place any orders after submit a withdrawal application
*/
function submitWithdrawApplication() public {
_withdrawalApplication[msg.sender] = block.timestamp;
emit WithdrawalApplication(msg.sender,block.timestamp);
}
/**
* @dev cancel withdraw application
*/
function cancelWithdrawApplication() public {
_withdrawalApplication[msg.sender] = 0;
emit WithdrawalApplication(msg.sender,0);
}
/**
* @dev check user withdraw application status
*/
function isWithdrawApplication(address user) view public returns(bool) {
if(_withdrawalApplication[user] == uint(0)) {
return false;
}
return true;
}
/**
* @dev withdraw token
*/
function _withdraw(address from,address payable to,address token,uint256 amount) internal {
if ( _balances[token][from] < amount) {
revert(INSUFFICIENT_FOUND);
}
_balances[token][from] = _balances[token][from].sub(amount);
if(token == address(0)) {
to.transfer(amount);
}else{
require(ERC20(token).transfer(to, amount),TRANSFER_FAILED);
}
emit Withdraw(token, from, to, amount, _balances[token][from]);
}
/**
* @dev user withdraw token
*/
function withdraw(address token) public onlyWithdrawalApplicationApproved {
uint256 amount = _balances[token][msg.sender];
if(amount != 0){
_withdraw(msg.sender,msg.sender,token,amount);
}
}
/**
* @dev user withdraw many tokens
*/
function withdrawAll(address[] memory tokens) public onlyWithdrawalApplicationApproved {
for(uint256 i = 0; i< tokens.length ;i++){
uint256 amount = _balances[tokens[i]][msg.sender];
if(amount == 0){
continue;
}
_withdraw(msg.sender,msg.sender,tokens[i],amount);
}
}
/**
* @dev user send withdraw request with relayer's authorized signature
*/
function authorizedWithdraw(address payable to,address token,uint256 amount,
uint256 nonce,uint expiredTime,address relayer,uint8 v, bytes32 r,bytes32 s) public
{
require(_withdrawalApplication[msg.sender] == uint(0));
require(expiredTime >= block.timestamp,INVALID_TIME);
require(_relayers[relayer] == true,ONLY_RELAYER);
bytes32 hash = keccak256(abi.encodePacked(msg.sender,to, token, amount, nonce, expiredTime));
if (_withdrawn[hash]) {
revert(WITHDRAW_EXISTS);
}
_withdrawn[hash] = true;
if (ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), v, r, s) != relayer) {
revert(ECRECOVER_FAILED);
}
_withdraw(msg.sender,to,token,amount);
}
/**
* @dev withdraw the token from Dex Wallet to Etheruem Wallet,signType [0 = signTypeDataV3, 1 = eth_sign]
*/
function adminWithdraw(address from,address payable to,address token,uint256 amount,uint256 nonce,uint8 v,bytes32[2] memory rs,
address feeToken,uint256 feeWithdrawal,uint timestamp,uint signType) public onlyRelayer {
bytes32 hash = ecrecoverWithdraw(from,to,token,amount,nonce,v,rs,feeToken,feeWithdrawal,timestamp,signType);
if (_withdrawn[hash]) {
revert(WITHDRAW_EXISTS);
}
_withdrawn[hash] = true;
_transfer(from,to,token,amount,feeToken,feeWithdrawal,false);
}
/**
* @dev transfer the token between Dex Wallet,signType [0 = signTypeDataV3, 1 = eth_sign]
*/
function adminTransfer(address from,address payable to,address token,uint256 amount,uint256 nonce,uint8 v,bytes32[2] memory rs,
address feeToken,uint256 feeWithdrawal,uint timestamp,uint signType) public onlyRelayer {
bytes32 hash = ecrecoverWithdraw(from,to,token,amount,nonce,v,rs,feeToken,feeWithdrawal,timestamp,signType);
if (_withdrawn[hash]) {
revert(WITHDRAW_EXISTS);
}
_withdrawn[hash] = true;
_transfer(from,to,token,amount,feeToken,feeWithdrawal,true);
}
/**
* @dev transfer the token
* @param from token sender
* @param to token receiver
* @param token The address of token to transfer
* @param amount The amount to transfer
* @param feeToken The address of token to pay the fee
* @param feeWithdrawal The amount of feeToken to pay the fee
* @param isInternal True is transfer token from a Dex Wallet to a Dex Wallet, False is transfer a token from Dex wallet to a Etheruem Wallet
*/
function _transfer(address from,address payable to,address token,uint256 amount, address feeToken,uint256 feeWithdrawal, bool isInternal) internal {
if (feeWithdrawal > 0)
{
require(_balances[feeToken][from] >= feeWithdrawal, INSUFFICIENT_FOUND );
_balances[feeToken][from] = _balances[feeToken][from].sub(feeWithdrawal);
_balances[feeToken][_feeAccount] = _balances[feeToken][_feeAccount].add(feeWithdrawal);
}
if ( _balances[token][from] < amount) { revert(INSUFFICIENT_FOUND); }
_balances[token][from] = _balances[token][from].sub(amount);
if(isInternal)
{
_balances[token][to] = _balances[token][to].add(amount);
emit Transfer(token, from, to, amount, _balances[token][from], _balances[token][to]);
}else{
if(token == address(0)) {
to.transfer(amount);
}else{
require(ERC20(token).transfer(to, amount),TRANSFER_FAILED);
}
emit Withdraw(token, from, to, amount, _balances[token][from]);
}
}
/**
* @dev mirgate function will withdraw all user token balances to wallet
*/
function adminWithdrawAll(address payable user,address[] memory tokens) public onlyOwner {
for(uint256 i = 0; i< tokens.length ;i++){
address token = tokens[i];
uint256 amount = _balances[token][user];
if(amount == 0){
continue;
}
_withdraw(user,user,token,amount);
}
}
/**
* @dev get the balance of the account
*/
function balanceOf(address token, address user) public view returns (uint256) {
return _balances[token][user];
}
/**
* @dev trade order only call by relayer, ti.signType: 0 = signTypeDataV3, 1 = eth_sign
*/
function tradeOrder(Order memory taker,Order memory maker, TradeInfo memory ti) public onlyRelayer
{
uint256 gasInitial = gasleft();
bytes32 takerHash = ecrecoverOrder(taker,taker.signType);
bytes32 makerHash = ecrecoverOrder(maker,maker.signType);
bytes32 tradeHash = keccak256(abi.encodePacked(takerHash ,makerHash));
require(_traded[tradeHash] == false,TRADE_EXISTS);
_traded[tradeHash] = true;
_tradeOrder(taker,maker,ti,takerHash,makerHash);
uint256 gasUsed = gasInitial - gasleft();
_burnGas(gasUsed);
}
/**
* @dev trade order internal
*/
function _tradeOrder(Order memory taker,Order memory maker, TradeInfo memory ti, bytes32 takerHash,bytes32 makerHash) internal
{
require(taker.baseToken == maker.baseToken && taker.token == maker.token);
require(ti.tradeTokenAmount > 0 , INVALID_AMOUNT );
require((block.timestamp <= taker.expireTime) && (block.timestamp <= maker.expireTime) , INVALID_TIME );
require( (_invalidOrderNonce[taker.user] < taker.nonce) &&(_invalidOrderNonce[maker.user] < maker.nonce),INVALID_NONCE) ;
require( (taker.tokenAmount.sub(_orderFills[takerHash]) >= ti.tradeTokenAmount) &&
(maker.tokenAmount.sub(_orderFills[makerHash]) >= ti.tradeTokenAmount), AMOUNT_EXCEEDED);
require(taker.gasToken == ti.tradeGasToken, INVALID_GASTOKEN);
uint256 tradeBaseTokenAmount = ti.tradeTokenAmount.mul(maker.baseTokenAmount).div(maker.tokenAmount);
(uint256 takerFee,uint256 makerFee) = calcMaxFee(ti,tradeBaseTokenAmount,maker.sell);
uint gasFee = ti.tradeGasFee;
if(gasFee != 0)
{
if( taker.maxGasFee < _orderGasFee[takerHash].add(gasFee))
{
gasFee = taker.maxGasFee.sub(_orderGasFee[takerHash]);
}
if(gasFee != 0)
{
_orderGasFee[takerHash] = _orderGasFee[takerHash].add(gasFee);
_balances[taker.gasToken][taker.user] = _balances[taker.gasToken][taker.user].sub(gasFee);
}
}
if( maker.sell)
{
//maker is seller
_updateOrderBalance(taker.user,maker.user,taker.baseToken,taker.token,
tradeBaseTokenAmount,ti.tradeTokenAmount,takerFee,makerFee);
}else
{
//maker is buyer
_updateOrderBalance(maker.user,taker.user,taker.baseToken,taker.token,
tradeBaseTokenAmount,ti.tradeTokenAmount,makerFee,takerFee);
}
//fill order
_orderFills[takerHash] = _orderFills[takerHash].add(ti.tradeTokenAmount);
_orderFills[makerHash] = _orderFills[makerHash].add(ti.tradeTokenAmount);
emit Trade(takerHash,makerHash,ti.tradeTokenAmount,tradeBaseTokenAmount,ti.tradeNonce,takerFee,makerFee, maker.sell ,gasFee);
emit Balance(_balances[taker.baseToken][taker.user],_balances[taker.token][taker.user],_balances[maker.baseToken][maker.user],_balances[maker.token][maker.user]);
}
/**
* @dev update the balance after each order traded
*/
function _updateOrderBalance(address buyer,address seller,address base,address token,uint256 baseAmount,uint256 amount,uint256 buyFee,uint256 sellFee) internal
{
_balances[base][seller] = _balances[base][seller].add(baseAmount.sub(sellFee));
_balances[base][buyer] = _balances[base][buyer].sub(baseAmount);
_balances[token][buyer] = _balances[token][buyer].add(amount.sub(buyFee));
_balances[token][seller] = _balances[token][seller].sub(amount);
_balances[base][_feeAccount] = _balances[base][_feeAccount].add(sellFee);
_balances[token][_feeAccount] = _balances[token][_feeAccount].add(buyFee);
}
/**
* @dev calc max fee for maker and taker
* @return return a taker and maker fee limit by _takerFeeRate and _makerFeeRate
*/
function calcMaxFee(TradeInfo memory ti,uint256 tradeBaseTokenAmount,bool sellerIsMaker) view public returns (uint256 takerFee,uint256 makerFee) {
uint maxTakerFee;
uint maxMakerFee;
takerFee = ti.tradeTakerFee;
makerFee = ti.tradeMakerFee;
if(sellerIsMaker)
{
// taker is buyer
maxTakerFee = (ti.tradeTokenAmount * _takerFeeRate) / 1 ether;
maxMakerFee = (tradeBaseTokenAmount * _makerFeeRate) / 1 ether;
}else{
// maker is buyer
maxTakerFee = (tradeBaseTokenAmount * _takerFeeRate) / 1 ether;
maxMakerFee = (ti.tradeTokenAmount * _makerFeeRate) / 1 ether;
}
if(ti.tradeTakerFee > maxTakerFee)
{
takerFee = maxTakerFee;
}
if(ti.tradeMakerFee > maxMakerFee)
{
makerFee = maxMakerFee;
}
}
/**
* @dev get fee Rate
*/
function getFeeRate() view public returns(uint256 makerFeeRate,uint256 takerFeeRate)
{
return (_makerFeeRate,_takerFeeRate);
}
/**
* @dev get order filled amount
* @param orderHash the order hash
* @return return the filled amount for a order
*/
function getOrderFills(bytes32 orderHash) view public returns(uint256 filledAmount)
{
return _orderFills[orderHash];
}
///@dev check orders traded
function isTraded(bytes32 buyOrderHash,bytes32 sellOrderHash) view public returns(bool traded)
{
return _traded[keccak256(abi.encodePacked(buyOrderHash, sellOrderHash))];
}
/**
* @dev Airdrop the token directly to Dex user's walle,only airdrop contract can call this function.
* @param to the recipient
* @param token the ERC20 token to send
* @param amount the token amount to send
*/
function airdrop(address to,address token,uint256 amount) public onlyAirdropContract
{
//Not EOA
require(tx.origin != msg.sender);
require(_balances[token][msg.sender] >= amount ,INSUFFICIENT_FOUND);
_balances[token][msg.sender] = _balances[token][msg.sender].sub(amount);
_balances[token][to] = _balances[token][to].add(amount);
emit Airdrop(to,token,amount);
}
/**
* @dev ecreover the order sign
* @return return a order hash
*/
function ecrecoverOrder(Order memory order,uint signType) public pure returns (bytes32 orderHash) {
if(signType == 0 )
{
orderHash = keccak256(abi.encode(
ORDER_TYPEHASH,
order.token,order.baseToken,order.tokenAmount,order.baseTokenAmount,order.nonce,order.sell,order.expireTime,order.maxGasFee,order.gasToken,order.timestamp));
if (ecrecover(keccak256(abi.encodePacked("\x19\x01",DOMAIN_SEPARATOR,orderHash)),order.V,order.R, order.S) != order.user) {
revert(ECRECOVER_FAILED);
}
}else {
orderHash = keccak256(abi.encodePacked(order.token,order.baseToken,order.tokenAmount,order.baseTokenAmount,order.nonce,order.sell,order.expireTime,order.maxGasFee,order.gasToken,order.timestamp));
if(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",orderHash)),order.V,order.R, order.S) != order.user) {
revert(ECRECOVER_FAILED);
}
}
}
/**
* @dev ecrecover the withdraw sign
* @return return a withdraw hash
*/
function ecrecoverWithdraw(address from,address payable to,address token,uint256 amount,uint256 nonce,uint8 v,bytes32[2] memory rs,
address feeToken,uint256 feeWithdrawal,uint timestamp,uint signType) public pure returns (bytes32 orderHash) {
if(signType == 1 ) {
orderHash = keccak256(abi.encodePacked(token, amount, to, nonce,feeToken,feeWithdrawal,timestamp));
if (ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), v, rs[0], rs[1]) != from) {
revert(ECRECOVER_FAILED);
}
} else {
orderHash = keccak256(abi.encode(WITHDRAW_TYPEHASH,token, amount, to, nonce,feeToken,feeWithdrawal,timestamp));
if (ecrecover(keccak256(abi.encodePacked("\x19\x01",DOMAIN_SEPARATOR,orderHash)), v, rs[0], rs[1]) != from) {
revert(ECRECOVER_FAILED);
}
}
}
/**
* @dev burn the stored gastoken
* @param gasUsed The gas uesed to calc the gastoken to burn
*/
function _burnGas(uint gasUsed) internal {
if(_gasStorage == address(0x0)){
return;
}
IGasStorage(_gasStorage).burn(gasUsed);
}
}
|
ecrecover the withdraw sign return return a withdraw hash/
|
function ecrecoverWithdraw(address from,address payable to,address token,uint256 amount,uint256 nonce,uint8 v,bytes32[2] memory rs,
address feeToken,uint256 feeWithdrawal,uint timestamp,uint signType) public pure returns (bytes32 orderHash) {
if(signType == 1 ) {
orderHash = keccak256(abi.encodePacked(token, amount, to, nonce,feeToken,feeWithdrawal,timestamp));
if (ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), v, rs[0], rs[1]) != from) {
revert(ECRECOVER_FAILED);
}
orderHash = keccak256(abi.encode(WITHDRAW_TYPEHASH,token, amount, to, nonce,feeToken,feeWithdrawal,timestamp));
if (ecrecover(keccak256(abi.encodePacked("\x19\x01",DOMAIN_SEPARATOR,orderHash)), v, rs[0], rs[1]) != from) {
revert(ECRECOVER_FAILED);
}
}
}
| 1,805,345
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title A base MisBlock token contract
/// @author Anderson L
/// @notice This contract is inherited by MisBlockETH and MisBlockBSC token contracts.
/// @dev All functions requiring onlyOwner are also pausable.
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import '@openzeppelin/contracts/access/Ownable.sol';
import "@openzeppelin/contracts/utils/Address.sol";
import '@openzeppelin/contracts/security/Pausable.sol';
import "./interfaces/UniswapInterfaces.sol";
contract MisBlockBase is ERC20, Pausable, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _tokenAllowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0) / 1000;
uint256 private _tTotal = 0;
uint256 private _rTotal = 0;
uint256 private _tFeeTotal;
uint256 public deployTime = block.timestamp;
uint256 public taxFee;
uint256 public liquidityFee;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
mapping (address => bool) private _isMintAvailable;
address[] private _mintAvailableAddresses;
mapping (address => bool) private _isBurnAvailable;
address[] private _burnAvailableAddresses;
// Should re-set following 2 values as our token's requirement.
uint256 public maxTxAmount = 5000000 ether;
uint256 private constant TOKEN_SELL_TO_LIQUIDITY = 500000 ether;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event TransferForVesting(address recipient, uint256 amount);
event Mint(address account, uint256 amount);
event AllocateVesting(address indexed vestingContract, uint256 amount, uint256 timestamp);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
struct LockFund {
uint256 amount;
uint256 releasetime;
}
mapping (address => bool) public isSwapAddress;
address[] public swapAddresses;
mapping (address => LockFund[]) private _lockFundsArray;
/// @notice Constructor. The token name is UNICOIN and the symbol name is UNICN.
/// @dev Should input swapaddress as PCS router address in BSC contract and UNISWAP router addres in ETH contract.
/// @param swapaddress An address of pcs or uniswap router contract.
/// @param initialMintAmount An address of pcs or uniswap router contract.
constructor(address swapaddress, uint256 initialMintAmount) ERC20("UNICOIN", "UNICN") {
_tTotal = initialMintAmount;
_rTotal = MAX.sub(MAX.mod(_tTotal));
_rOwned[_msgSender()] = _rTotal;
// Uniswap Address should be in SwapAddress list
isSwapAddress[swapaddress] = true;
swapAddresses.push(swapaddress);
// Owner should be in burn/mint available list
_isMintAvailable[_msgSender()] = true;
_mintAvailableAddresses.push(_msgSender());
_isBurnAvailable[_msgSender()] = true;
_burnAvailableAddresses.push(_msgSender());
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(swapaddress);
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
emit Transfer(address(0), _msgSender(), _tTotal);
}
/**
* @notice Throws if called by any account other than mint available addresses.
*/
modifier onlyMintAvailable() {
require(_isMintAvailable[_msgSender()], "caller is not in the mint available list");
_;
}
/**
* @notice Throws if called by any account other than burn available addresses.
*/
modifier onlyBurnAvailable() {
require(_isBurnAvailable[_msgSender()], "caller is not in the burn available list");
_;
}
/**
* @notice add mint available address
*/
function addMintAvailableAddress(address account) external onlyOwner whenNotPaused {
require(!_isMintAvailable[account], "Account is already in list of mint available addresses");
_isMintAvailable[account] = true;
_mintAvailableAddresses.push(account);
}
/**
* @notice remove mint available address
*/
function removeMintAvailableAddress(address account) external onlyOwner whenNotPaused {
require(_isMintAvailable[account] == true, "Account is not in list of mint available addresses");
for (uint256 i = 0; i < _mintAvailableAddresses.length; i++) {
if (_mintAvailableAddresses[i] == account) {
_mintAvailableAddresses[i] = _mintAvailableAddresses[_mintAvailableAddresses.length - 1];
_isMintAvailable[account] = false;
_mintAvailableAddresses.pop();
break;
}
}
}
/**
* @notice add burn available address
*/
function addBurnAvailableAddress(address account) external onlyOwner whenNotPaused {
require(!_isBurnAvailable[account], "Account is already in list of burn available addresses");
_isBurnAvailable[account] = true;
_burnAvailableAddresses.push(account);
}
/**
* @notice remove burn available address
*/
function removeBurnAvailableAddress(address account) external onlyOwner whenNotPaused {
require(_isBurnAvailable[account] == true, "Account is not in list of burn available addresses");
for (uint256 i = 0; i < _burnAvailableAddresses.length; i++) {
if (_burnAvailableAddresses[i] == account) {
_burnAvailableAddresses[i] = _burnAvailableAddresses[_burnAvailableAddresses.length - 1];
_isBurnAvailable[account] = false;
_burnAvailableAddresses.pop();
break;
}
}
}
/// @notice We are despositing 1T tokens initially and allowing to mint 9T tokens more. This function can be called by only owner.
function mint(address account, uint256 amount) external onlyMintAvailable whenNotPaused {
_mint(account, amount);
emit Mint(account, amount);
}
/// @dev We should check reflection value should not be overr uint256's max value.
function _mint(address account, uint256 amount) internal override virtual {
require(account != address(0), "ERC20: mint to the zero address");
(uint256 rAmount,,,,,) = _getValues(amount);
require((~uint256(0) - rAmount) > _rTotal , "Mint value is exceeded limitation");
_rOwned[account] = _rOwned[account].add(rAmount);
if(_isExcluded[account]) {
_tOwned[account] = _tOwned[account].add(amount);
}
_rTotal += rAmount;
_tTotal += amount;
}
/// @notice Getting totalSupply.
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
/**
* @notice Getting balance of the account.
* @dev Checking the account is including in Reward List or not.
*/
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
/**
* @dev Checking whether the account is contract address or not.
*/
// function isContract(address account) internal view returns (bool) {
// uint32 size;
// assembly {
// size := extcodesize(account)
// }
// return (size > 0);
// }
/**
* @notice This function is standard transfer function.
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Taking fees and set timelock by proper logic.
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transferBase(_msgSender(), recipient, amount);
return true;
}
/**
* @notice This function is to getting allowance of spender.
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `sender` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address sender, address spender) public view override returns (uint256) {
return _tokenAllowances[sender][spender];
}
/**
* @notice This function is to approve transfer.
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approveBase(_msgSender(), spender, amount);
return true;
}
/**
* @notice This function is for delegating transfer.
* @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) public override returns (bool) {
require(sender != recipient, "sender and recipient is same address");
_transferBase(sender, recipient, amount);
_approveBase(sender, _msgSender(), _tokenAllowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @notice This function is to increase allowance.
* @dev Adds `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits an {Approval} event.
*/
function increaseAllowance(address spender, uint256 addedValue) public override virtual returns (bool) {
_approveBase(_msgSender(), spender, _tokenAllowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @notice This function is to decrease allowance.
* @dev Subs `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits an {Approval} event.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public override virtual returns (bool) {
_approveBase(_msgSender(), spender, _tokenAllowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @notice This function is to check whether the account is excluded from reward or not.
* @dev Check the account is excluded from reward or not.
*
* Returns a boolean value indicating whether the account is excluded from reward or not.
*
*/
function isExcludedFromReward(address account) external view returns (bool) {
return _isExcluded[account];
}
/**
* @notice Get total Fees taken by taxes.
*/
function totalFees() external view returns (uint256) {
return _tFeeTotal;
}
/**
* @notice This function is to deliver tokens to account holders.
*/
function deliver(uint256 tAmount) external {
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);
}
/**
* @notice Getting reflection value from token value.
*/
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external 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;
}
}
/**
* @notice Getting token value from reflection value.
*/
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);
}
/**
* @notice exclude the account from the reward list.
*
* Must be called from only owner.
*
*/
function excludeFromReward(address account) external onlyOwner whenNotPaused {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, '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);
}
/**
* @notice include the account into the reward list.
*
* Must be called from only owner.
*
*/
function includeInReward(address account) external onlyOwner whenNotPaused {
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;
}
}
}
/**
* @notice exclude the account from the taking fee. taxes are not applied for accounts from this list.
*
* Must be called from only owner.
*
*/
function excludeFromFee(address account) external onlyOwner whenNotPaused {
_isExcludedFromFee[account] = true;
}
/**
* @notice include the account into the taking fee. taxes would be applied for accounts from this list.
*
* Must be called from only owner.
*
*/
function includeInFee(address account) external onlyOwner {
_isExcludedFromFee[account] = false;
}
/**
* @notice setting maximum transfer amount as percentage.
*
* Must be called from only owner.
*
*/
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner whenNotPaused {
maxTxAmount = _tTotal.mul(maxTxPercent).div(
10**2
);
}
/**
* @notice enable/disable Swap and Liquidity feature.
*
* Must be called from only owner.
*
*/
function setSwapAndLiquifyEnabled(bool enabled) external onlyOwner whenNotPaused {
swapAndLiquifyEnabled = enabled;
emit SwapAndLiquifyEnabledUpdated(enabled);
}
/**
* @notice burn tokens from the account.
*
* Must be called from only owner.
*
*/
function burn(address account, uint256 tAmount) external onlyBurnAvailable whenNotPaused {
uint256 burnerBalance = balanceOf(account);
require(burnerBalance >= tAmount, "Burnning amount is exceed balance");
(uint256 rAmount, , , , , ) = _getValues(tAmount);
_rOwned[account] = _rOwned[account].sub(rAmount);
if(_isExcluded[account]) {
_tOwned[account] = _tOwned[account].sub(tAmount);
}
_rTotal = _rTotal.sub(rAmount);
_tTotal = _tTotal.sub(tAmount);
}
/**
* @dev Inspired from Reflect Finance concept.
* to recieve ETH from uniswapV2Router when swaping
*/
receive() external payable {}
/**
* @dev applying fees. called by transfer functions.
*
* Internal function.
*
*/
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
/**
* @dev Internal function to get values related with reflection feature based on transfer amount.
* - rAmount : reflection amount for tAmount
* - rTransferAmount : reflection amount for tTransferAmount
* - rFee : reflection amount for tFee
* - tTransferAmount : transfer amount without all taxes(fee and liquidity)
* - tFee : tax fee for account holders
* - tLiquidity : tax fee for liquidity
*/
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
/**
* @dev Internal function to get token values based on transfer amount. called by {_getValues}
* - tTransferAmount : transfer amount without all taxes(fee and liquidity)
* - tFee : tax fee for account holders
* - tLiquidity : tax fee for liquidity
*/
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
/**
* @dev Internal function to get reflection values based on token values. called by {_getValues}
* - rAmount : reflection amount for tAmount
* - rTransferAmount : reflection amount for tTransferAmount
* - rFee : reflection amount for tFee
*/
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
/**
* @dev Internal function to get rate between token and reflection value
*/
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
/**
* @dev Internal function to get total Supply of token and reflection. called by {_getRate}
*/
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);
}
/**
* @dev Internal function to to apply liquidity fee.
*/
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);
}
/**
* @dev Internal function to calculate tax fee. Used 1000 instead of 100 for max percent to avoid decimals. For example, 7.5% will be calculated by 75/1000
*/
function calculateTaxFee(uint256 amount) private view returns (uint256) {
return amount.mul(taxFee).div(
10**3
);
}
/**
* @dev Internal function to calculate liquidity fee. Used 1000 instead of 100 for max percent to avoid decimals. For example, 7.5% will be calculated by 75/1000
*/
function calculateLiquidityFee(uint256 amount) private view returns (uint256) {
return amount.mul(liquidityFee).div(
10**3
);
}
/**
* @dev Internal function to set tax fees.
* First Month : 7.5%, Second Month : 5%, Third Month : 2.5%, From Fourth Month : 0
*/
function _setTaxFee(bool takeFee) private {
if (!takeFee) {
taxFee = 0;
liquidityFee = 0;
} else if ( block.timestamp < deployTime + 30 days) {
taxFee = 75;
liquidityFee = 75;
} else if ( block.timestamp < deployTime + 60 days) {
taxFee = 50;
liquidityFee = 50;
} else if ( block.timestamp < deployTime + 90 days) {
taxFee = 25;
liquidityFee = 25;
} else {
taxFee = 0;
liquidityFee = 0;
}
}
/**
* @notice Checking whether the address is excluded from fee or not
*/
function isExcludedFromFee(address account) external view returns(bool) {
return _isExcludedFromFee[account];
}
/**
* @dev Internal function to approve.
* Emits a {Approval} event.
*/
function _approveBase(address sender, address spender, uint256 amount) private {
require(sender != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_tokenAllowances[sender][spender] = amount;
emit Approval(sender, spender, amount);
}
/**
* @dev Internal function for standard transfer.
*/
function _transferBase(
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");
if(from != owner() && to != owner())
require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
uint256 senderBalance = balanceOf(from);
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if from address is not in SwapAddress list, not taking fee
if(!isSwapAddress[from]){
takeFee = false;
}
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//it will check timelock
_beforeTokenTransferBase(from, amount);
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
//it will calculate timelock
_afterTokenTransferBase(from, to, amount);
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= maxTxAmount)
{
contractTokenBalance = maxTxAmount;
}
bool overMinTokenBalance = contractTokenBalance >= TOKEN_SELL_TO_LIQUIDITY;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = TOKEN_SELL_TO_LIQUIDITY;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
}
/**
* @dev Internal function of swap feature.
* Emits {SwapAndLiquify}
*/
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// split the contract balance into halves
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
}
/**
* @dev Internal function for swapTokensForEth.
*/
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();
_approveBase(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
/**
* @dev Internal function for addLiquidity.
*/
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approveBase(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
(uint token, uint eth, uint liquidity) = uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
emit SwapAndLiquify(token, eth, liquidity);
}
/**
* @dev Internal function of transfer.
* this method is responsible for taking all fee, if takeFee is true
*/
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
_setTaxFee(takeFee);
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);
}
}
/**
* @dev called in case of both of sender and recipient are in reward list.
*/
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
/**
* @dev called in case of only sender is in reward list.
*/
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
/**
* @dev called in case of only recipient is in reward list.
*/
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
/**
* @dev called in case of both are not in reward list.
*/
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _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);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
/**
* @notice getting the list of addresses set as applying timelock from. All tokens transfered from addresses of this list is time locked by proper logic.
*/
function getSwapAddresses() external view returns (address[] memory){
return swapAddresses;
}
/**
* @notice add swap address
*/
function addSwapAddress(address account) external onlyOwner whenNotPaused {
require(!isSwapAddress[account], "Account is already in list of swap addresses");
isSwapAddress[account] = true;
swapAddresses.push(account);
}
/**
* @notice remove swap address
*/
function removeSwapAddress(address account) external onlyOwner whenNotPaused {
require(isSwapAddress[account] == true, "Account is not in list of swap addresses");
for (uint256 i = 0; i < swapAddresses.length; i++) {
if (swapAddresses[i] == account) {
swapAddresses[i] = swapAddresses[swapAddresses.length - 1];
isSwapAddress[account] = false;
swapAddresses.pop();
break;
}
}
}
/**
* @dev Internal function to be called before token transfer.
* Check time locked funds.
* If the address is having 1000 tokens. And 500 tokens were time locked.
* At this point if the account wants to transfer 600 tokens, then it will be reverted since the user is having only 500 tokens available.
*/
function _beforeTokenTransferBase(
address from,
uint256 amount
) private view {
LockFund[] storage lockFunds = _lockFundsArray[from];
if(lockFunds.length < 1) return;
uint256 lockedFundsSum = 0;
for (uint i = 0; i < lockFunds.length; i++) {
if(lockFunds[i].releasetime > block.timestamp)
{
lockedFundsSum += lockFunds[i].amount;
}
}
require(balanceOf(from) - lockedFundsSum >= amount, "Some of your balances were locked. And you don't have enough unlocked balance for this transaction.");
}
/**
* @dev Internal function to be called after token transfer.
* Applying time lock against tokens transferred from addresses in the timelock list
*/
function _afterTokenTransferBase(
address from,
address to,
uint256 amount
) private {
if(!isSwapAddress[from]) return;
LockFund[] storage lockFunds = _lockFundsArray[to];
lockFunds.push(LockFund(amount.div(10), block.timestamp + 1 days));
for (uint256 i = 1; i < 10; i++) {
lockFunds.push(LockFund(amount.div(10), block.timestamp + 1 days + i * 1 weeks));
}
}
}
|
include the account into the reward list. Must be called from only owner./
|
function includeInReward(address account) external onlyOwner whenNotPaused {
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;
}
}
}
| 5,426,042
|
//Address: 0x75ca11f71b53cb72dde48a78a3b3d5fe0df5e0df
//Contract name: TESTTESTToken
//Balance: -
//Verification Date: 5/27/2018
//Transacion Count: 0
// CODE STARTS HERE
pragma solidity ^ 0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20
* @dev Standart ERC20 token interface
*/
contract ERC20 {
function balanceOf(address _owner) public constant returns(uint256);
function transfer(address _to, uint256 _value) public returns(bool);
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
function approve(address _spender, uint256 _value) public returns(bool);
function allowance(address _owner, address _spender) public constant returns(uint256);
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* @dev LTO token contract
*/
contract TESTTESTToken is ERC20 {
using SafeMath for uint256;
string public name = "TESTTEST TOKEN";
string public symbol = "TTT";
uint256 public decimals = 18;
uint256 public totalSupply = 0;
uint256 public constant MAX_TOKENS = 166000000 * 1e18;
// Ico contract address
address public owner;
event Burn(address indexed from, uint256 value);
// Disables token transfers
bool public tokensAreFrozen = true;
// Allows execution by the owner only
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function TESTTESTToken(address _owner) public {
owner = _owner;
}
/**
* @dev Mint tokens
* @param _investor address the tokens will be issued to
* @param _value number of tokens
*/
function mintTokens(address _investor, uint256 _value) external onlyOwner {
require(_value > 0);
require(totalSupply.add(_value) <= MAX_TOKENS);
balances[_investor] = balances[_investor].add(_value);
totalSupply = totalSupply.add(_value);
emit Transfer(0x0, _investor, _value);
}
/**
* @dev Enables token transfers
*/
function defrostTokens() external onlyOwner {
tokensAreFrozen = false;
}
/**
* @dev Disables token transfers
*/
function frostTokens() external onlyOwner {
tokensAreFrozen = true;
}
/**
* @dev Burn Tokens
* @param _investor token holder address which the tokens will be burnt
* @param _value number of tokens to burn
*/
function burnTokens(address _investor, uint256 _value) external onlyOwner {
require(balances[_investor] > 0);
totalSupply = totalSupply.sub(_value);
balances[_investor] = balances[_investor].sub(_value);
emit Burn(_investor, _value);
}
/**
* @dev Get balance of investor
* @param _owner investor's address
* @return balance of investor
*/
function balanceOf(address _owner) public constant returns(uint256) {
return balances[_owner];
}
/**
* @return true if the transfer was successful
*/
function transfer(address _to, uint256 _amount) public returns(bool) {
require(!tokensAreFrozen);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
/**
* @return true if the transfer was successful
*/
function transferFrom(address _from, address _to, uint256 _amount) public returns(bool) {
require(!tokensAreFrozen);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
/**
* @dev Allows another account/contract to spend some tokens on its behalf
* throws on any error rather then return a false flag to minimize user errors
*
* also, to minimize the risk of the approve/transferFrom attack vector
* approve has to be called twice in 2 separate transactions - once to
* change the allowance to 0 and secondly to change it to the new allowance
* value
*
* @param _spender approved address
* @param _amount allowance amount
*
* @return true if the approval was successful
*/
function approve(address _spender, uint256 _amount) public returns(bool) {
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
*
* @param _owner the address which owns the funds
* @param _spender the address which will spend the funds
*
* @return the amount of tokens still avaible for the spender
*/
function allowance(address _owner, address _spender) public constant returns(uint256) {
return allowed[_owner][_spender];
}
}
contract TESTTESTICO {
TESTTESTToken public LTO = new TESTTESTToken(this);
using SafeMath for uint256;
// Token price parameters
uint256 public Rate_Eth = 700; // Rate USD per ETH
uint256 public Tokens_Per_Dollar = 50; // Lto token per dollar
uint256 public Token_Price = Tokens_Per_Dollar.mul(Rate_Eth); // Lto token per ETH
uint256 constant bountyPart = 20; // 2% of TotalSupply for BountyFund
uint256 constant teamPart = 30; //3% of TotalSupply for TeamFund
uint256 constant companyPart = 120; //12% of TotalSupply for company
uint256 constant MAX_PREICO_TOKENS = 27556000 * 1e18;
uint256 constant TOKENS_FOR_SALE = 137780000 * 1e18; // 83% of maximum 166M tokens fo sale
uint256 constant SOFT_CAP = 36300000 * 1e18; // 726 000$ in ICO
uint256 constant HARD_CAP = 93690400 * 1e18; // ~1 900 000$ in ICO (1 873 808)
uint256 public soldTotal; // total sold without bonus
bool public isItIco = false;
bool public canIBuy = false;
bool public canIWithdraw = false;
address public BountyFund;
address public TeamFund;
address public Company;
address public Manager; // Manager controls contract
StatusICO statusICO;
// Possible ICO statuses
enum StatusICO {
Created,
PreIcoStage1,
PreIcoStage2,
PreIcoStage3,
PreIcoFinished,
IcoStage1,
IcoStage2,
IcoStage3,
IcoStage4,
IcoStage5,
IcoFinished
}
// Mapping
mapping(address => uint256) public preInvestments; // Mapping for remembering investors eth in preICO
mapping(address => uint256) public icoInvestments; // Mapping for remembering investors eth in ICO
mapping(address => bool) public returnStatusPre; // Users can return their funds one time in PreICO and ICO
mapping(address => bool) public returnStatusIco; // Users can return their funds one time in PreICO and ICO
mapping(address => uint256) public tokensPreIco; // Mapping for remembering tokens of investors who paid at preICO in ether
mapping(address => uint256) public tokensIco; // Mapping for remembering tokens of investors who paid at ICO in ether
mapping(address => uint256) public tokensPreIcoInOtherCrypto; // Mapping for remembering tokens of investors who paid at preICO in other crypto
mapping(address => uint256) public tokensIcoInOtherCrypto; // Mapping for remembering tokens of investors who paid at ICO in other crypto
mapping(address => uint256) public tokensNoBonusSold;
// Events Log
event LogStartPreIcoStage(uint stageNum);
event LogFinishPreICO();
event LogStartIcoStage(uint stageNum);
event LogFinishICO(address bountyFund, address Company, address teamFund);
event LogBuyForInvestor(address investor, uint256 value);
event LogReturnEth(address investor, uint256 eth);
event LogReturnOtherCrypto(address investor);
// Modifier
// Allows execution by the contract manager only
modifier managerOnly {
require(msg.sender == Manager);
_;
}
/**
* @dev Contract constructor function
*/
function TESTTESTICO(
address _BountyFund,
address _TeamFund,
address _Company,
address _Manager
)
public {
BountyFund = _BountyFund;
TeamFund = _TeamFund;
Company = _Company;
Manager = _Manager;
statusICO = StatusICO.Created;
}
function currentStage() public view returns (string) {
if(statusICO == StatusICO.Created){return "Created";}
else if(statusICO == StatusICO.PreIcoStage1){return "PreIcoStage1";}
else if(statusICO == StatusICO.PreIcoStage2){return "PreIcoStage2";}
else if(statusICO == StatusICO.PreIcoStage3){return "PreIcoStage3";}
else if(statusICO == StatusICO.PreIcoFinished){return "PreIcoFinished";}
else if(statusICO == StatusICO.IcoStage1){return "IcoStage1";}
else if(statusICO == StatusICO.IcoStage2){return "IcoStage2";}
else if(statusICO == StatusICO.IcoStage1){return "IcoStage3";}
else if(statusICO == StatusICO.IcoStage1){return "IcoStage4";}
else if(statusICO == StatusICO.IcoStage1){return "IcoStage5";}
else if(statusICO == StatusICO.IcoStage1){return "IcoFinished";}
}
/**
* @dev Set rate of ETH and update token price
* @param _RateEth current ETH rate
*/
function setRate(uint256 _RateEth) external managerOnly {
Rate_Eth = _RateEth;
Token_Price = Tokens_Per_Dollar.mul(Rate_Eth);
}
/**
*
* Set PreICO status
*/
function setPreIcoStatus(uint _numb) external managerOnly {
require(statusICO == StatusICO.Created
|| statusICO == StatusICO.PreIcoStage1
|| statusICO == StatusICO.PreIcoStage2);
require(_numb == 1 || _numb == 2 || _numb == 3);
StatusICO stat = StatusICO.PreIcoStage1;
if(_numb == 2){stat = StatusICO.PreIcoStage2;}
else if(_numb == 3){stat = StatusICO.PreIcoStage3;}
statusICO = stat;
canIBuy = true;
canIWithdraw = true;
emit LogStartPreIcoStage(_numb);
}
/**
* @dev Finish PreIco
* Set Ico status to PreIcoFinished
*/
function finishPreIco() external managerOnly {
require(statusICO == StatusICO.PreIcoStage3);
statusICO = StatusICO.PreIcoFinished;
isItIco = true;
canIBuy = false;
canIWithdraw = false;
emit LogFinishPreICO();
}
/**
* @dev Start ICO
* Set ICO status
*/
function setIcoStatus(uint _numb) external managerOnly {
require(statusICO == StatusICO.PreIcoFinished
|| statusICO == StatusICO.IcoStage1
|| statusICO == StatusICO.IcoStage2
|| statusICO == StatusICO.IcoStage3
|| statusICO == StatusICO.IcoStage4);
require(_numb == 1 || _numb == 2 || _numb == 3 || _numb == 4 || _numb == 5);
StatusICO stat = StatusICO.IcoStage1;
if(_numb == 2){stat = StatusICO.IcoStage2;}
else if(_numb == 3){stat = StatusICO.IcoStage3;}
else if(_numb == 4){stat = StatusICO.IcoStage4;}
else if(_numb == 5){stat = StatusICO.IcoStage5;}
statusICO = stat;
canIBuy = true;
canIWithdraw = true;
emit LogStartIcoStage(_numb);
}
/**
* @dev Finish ICO and emit tokens for bounty company and team
*/
function finishIco() external managerOnly {
require(statusICO == StatusICO.IcoStage5);
uint256 totalAmount = LTO.totalSupply();
LTO.mintTokens(BountyFund, bountyPart.mul(totalAmount).div(1000));
LTO.mintTokens(TeamFund, teamPart.mul(totalAmount).div(1000));
LTO.mintTokens(Company, companyPart.mul(totalAmount).div(1000));
statusICO = StatusICO.IcoFinished;
canIBuy = false;
if(soldTotal >= SOFT_CAP){canIWithdraw = false;}
emit LogFinishICO(BountyFund, Company, TeamFund);
}
/**
* @dev Unfreeze tokens(enable token transfers)
*/
function enableTokensTransfer() external managerOnly {
LTO.defrostTokens();
}
/**
* @dev Freeze tokens(disable token transfers)
*/
function disableTokensTransfer() external managerOnly {
require(statusICO != StatusICO.IcoFinished);
LTO.frostTokens();
}
/**
* @dev Fallback function calls function to create tokens
* when investor sends ETH to address of ICO contract
*/
function() external payable {
require(canIBuy);
require(msg.value > 0);
createTokens(msg.sender, msg.value.mul(Token_Price), msg.value);
}
function buyToken() external payable {
require(canIBuy);
require(msg.value > 0);
createTokens(msg.sender, msg.value.mul(Token_Price), msg.value);
}
function buyForInvestor(address _investor, uint256 _value) external managerOnly {
require(_value > 0);
require(canIBuy);
uint256 decvalue = _value.mul(1 ether);
uint256 bonus = getBonus(decvalue);
uint256 total = decvalue.add(bonus);
if(!isItIco){
require(LTO.totalSupply().add(total) <= MAX_PREICO_TOKENS);
tokensPreIcoInOtherCrypto[_investor] = tokensPreIcoInOtherCrypto[_investor].add(total);}
else {
require(LTO.totalSupply().add(total) <= TOKENS_FOR_SALE);
require(soldTotal.add(decvalue) <= HARD_CAP);
tokensIcoInOtherCrypto[_investor] = tokensIcoInOtherCrypto[_investor].add(total);
soldTotal = soldTotal.add(decvalue);}
LTO.mintTokens(_investor, total);
tokensNoBonusSold[_investor] = tokensNoBonusSold[_investor].add(decvalue);
emit LogBuyForInvestor(_investor, _value);
}
function createTokens(address _investor, uint256 _value, uint256 _ethValue) internal {
require(_value > 0);
uint256 bonus = getBonus(_value);
uint256 total = _value.add(bonus);
if(!isItIco){
require(LTO.totalSupply().add(total) <= MAX_PREICO_TOKENS);
tokensPreIco[_investor] = tokensPreIco[_investor].add(total);
preInvestments[_investor] = preInvestments[_investor].add(_ethValue);}
else {
require(LTO.totalSupply().add(total) <= TOKENS_FOR_SALE);
require(soldTotal.add(_value) <= HARD_CAP);
tokensIco[_investor] = tokensIco[_investor].add(total);
icoInvestments[_investor] = icoInvestments[_investor].add(_ethValue);
soldTotal = soldTotal.add(_value);}
LTO.mintTokens(_investor, total);
tokensNoBonusSold[_investor] = tokensNoBonusSold[_investor].add(_value);
}
/**
* @dev Calculates bonus
* @param _value amount of tokens
* @return bonus value
*/
function getBonus(uint256 _value) public view returns(uint256) {
uint256 bonus = 0;
if (statusICO == StatusICO.PreIcoStage1) {
bonus = _value.mul(300).div(1000);
} else if (statusICO == StatusICO.PreIcoStage2) {
bonus = _value.mul(250).div(1000);
} else if (statusICO == StatusICO.PreIcoStage3) {
bonus = _value.mul(200).div(1000);
} else if (statusICO == StatusICO.IcoStage1) {
bonus = _value.mul(150).div(1000);
} else if (statusICO == StatusICO.IcoStage2) {
bonus = _value.mul(100).div(1000);
} else if (statusICO == StatusICO.IcoStage3) {
bonus = _value.mul(60).div(1000);
} else if (statusICO == StatusICO.IcoStage4) {
bonus = _value.mul(30).div(1000);
}
return bonus;
}
/**
* @dev Allows investors to return their investments
*/
function returnEther() public {
uint256 eth = 0;
uint256 tokens = 0;
require(canIWithdraw);
if (!isItIco) {
require(!returnStatusPre[msg.sender]);
require(preInvestments[msg.sender] > 0);
eth = preInvestments[msg.sender];
tokens = tokensPreIco[msg.sender];
preInvestments[msg.sender] = 0;
tokensPreIco[msg.sender] = 0;
returnStatusPre[msg.sender] = true;
}
else {
require(!returnStatusIco[msg.sender]);
require(icoInvestments[msg.sender] > 0);
eth = icoInvestments[msg.sender];
tokens = tokensIco[msg.sender];
icoInvestments[msg.sender] = 0;
tokensIco[msg.sender] = 0;
returnStatusIco[msg.sender] = true;
soldTotal = soldTotal.sub(tokensNoBonusSold[msg.sender]);}
LTO.burnTokens(msg.sender, tokens);
msg.sender.transfer(eth);
emit LogReturnEth(msg.sender, eth);
}
/**
* @dev Burn tokens who paid in other cryptocurrencies
*/
function returnOtherCrypto(address _investor)external managerOnly {
uint256 tokens = 0;
require(canIWithdraw);
if (!isItIco) {
require(!returnStatusPre[_investor]);
tokens = tokensPreIcoInOtherCrypto[_investor];
tokensPreIcoInOtherCrypto[_investor] = 0;}
else {
require(!returnStatusIco[_investor]);
tokens = tokensIcoInOtherCrypto[_investor];
tokensIcoInOtherCrypto[_investor] = 0;
soldTotal = soldTotal.sub(tokensNoBonusSold[_investor]);}
LTO.burnTokens(_investor, tokens);
emit LogReturnOtherCrypto(_investor);
}
/**
* @dev Allows Company withdraw investments
*/
function takeInvestments() external managerOnly {
require(statusICO == StatusICO.PreIcoFinished || statusICO == StatusICO.IcoFinished);
if(statusICO == StatusICO.PreIcoFinished){
uint256 totalb = address(this).balance;
uint256 fivePercent = (totalb.mul(50)).div(1000);
TeamFund.transfer(fivePercent);
Company.transfer(totalb.sub(fivePercent));
} else {
Company.transfer(address(this).balance);
LTO.defrostTokens();
}
}
}
// woopchain.com
|
return true if the transfer was successful/
|
function transferFrom(address _from, address _to, uint256 _amount) public returns(bool) {
require(!tokensAreFrozen);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
| 2,514,699
|
pragma solidity ^0.4.24;
import "zos-lib/contracts/migrations/Migratable.sol";
import "../access/Blacklist.sol";
/**
* @title Nexty governance smart contract
*/
contract Nexty is Migratable, Blacklist {
mapping(address => uint256) balances;
mapping(address => address) public coinbase;
mapping(address => bool) public sealer;
address[] public signers;
address[] public holders;
event SetCoinbase(address _holder, address _coinbase);
event UnSetCoinbase(address _holder, address _coinbase);
/**
* Check if address is a valid destination to transfer tokens to
* - must not be zero address
* - must not be the token address
* - must not be the owner's address
* - must not be the sender's address
*/
modifier validDestination(address to) {
require(to != address(0x0));
require(to != address(this));
require(to != owner);
require(to != msg.sender);
_;
}
/**
* Token contract initialize
*/
function initialize() isInitializer("Nexty", "0.1") public {
}
/**
* @dev Get all the list of current token holder.
* @return array of all token holder.
*/
function getHolders() public view returns (address[]) {
return holders;
}
/**
* @dev Get all the list of current singer.
*/
function getSigners() public view returns (address[]) {
return signers;
}
/**
* Token holder can call method to set their coinbase for mining.
*
* @param _coinbase Destination address
*/
function setCoinbase(address _coinbase) public validDestination(_coinbase) returns (bool) {
require(balances[msg.sender] > 0);
require(sealer[msg.sender] == false);
coinbase[_coinbase] = msg.sender;
signers.push(_coinbase);
sealer[msg.sender] = true;
emit SetCoinbase(msg.sender, _coinbase);
return true;
}
/**
* Token holder can call method to remove their coinbase and reset to other coinbase later for mining.
*
* @param _coinbase Destination address
*/
function unSetCoinbase(address _coinbase) public returns (bool) {
require(coinbase[_coinbase] == msg.sender);
require(sealer[msg.sender] == true);
delete coinbase[_coinbase];
removeSigner(_coinbase);
delete sealer[msg.sender];
emit UnSetCoinbase(msg.sender, _coinbase);
return true;
}
/**
* @dev Remove a specific address/account out of signer list
*/
function removeSigner(address _signer) internal {
for (uint i = 0; i < signers.length; i++) {
if (_signer == signers[i]) {
signers[i] = signers[signers.length - 1];
signers.length--;
return;
}
}
}
}
|
Token holder can call method to set their coinbase for mining. _coinbase Destination address/
|
function setCoinbase(address _coinbase) public validDestination(_coinbase) returns (bool) {
require(balances[msg.sender] > 0);
require(sealer[msg.sender] == false);
coinbase[_coinbase] = msg.sender;
signers.push(_coinbase);
sealer[msg.sender] = true;
emit SetCoinbase(msg.sender, _coinbase);
return true;
}
| 7,291,911
|
./full_match/4/0x8EF7B88a59Db9eaACd80E5E249D6F1AeF8755C7E/sources/browser/ClaimToken.sol
|
Function that withdraws all available tokens for the current period/
|
function claim() public {
require(whiteListedAddresses[msg.sender].exists, "The requested address is not whitelisted!");
require(whiteListedAddresses[msg.sender].notClaimed, "Claimed already!");
whiteListedAddresses[msg.sender].withdrawnAmount = whiteListedAddresses[msg.sender].withdrawPercentage;
whiteListedAddresses[msg.sender].notClaimed = false;
bool result = token.transfer(msg.sender, whiteListedAddresses[msg.sender].withdrawPercentage);
require(result, "The claim was not successful");
emit LogTokensClaimed(msg.sender, whiteListedAddresses[msg.sender].withdrawPercentage);
}
| 13,361,494
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(
address indexed operator,
address indexed from,
address indexed to,
uint256 id,
uint256 value
);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(
address indexed account,
address indexed operator,
bool approved
);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id)
external
view
returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator)
external
view
returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev 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);
}
}
interface IGenArt {
function getTokensByOwner(address owner)
external
view
returns (uint256[] memory);
function ownerOf(uint256 tokenId) external view returns (address);
function balanceOf(address owner) external view returns (uint256);
function isGoldToken(uint256 _tokenId) external view returns (bool);
}
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract GenArtTokenAirdropPass is
Context,
Ownable,
ERC165,
IERC1155,
IERC1155MetadataURI
{
using Address for address;
using Strings for uint256;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
mapping(uint256 => uint256) private _totalSupply;
uint256[3] tokenIds = [1, 2, 3];
uint256[3] tokenId_prices = [0.5 ether, 2.25 ether, 10 ether];
uint256[3] tokenId_cap = [1875, 500, 25];
bool private _paused = false;
address genArtMembershipAddress;
uint256 endBlock;
/**
* @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);
/**
* @dev See {_setURI}.
*/
constructor(
address genArtMembershipAddress_,
uint256 endBlock_,
string memory uri_
) {
genArtMembershipAddress = genArtMembershipAddress_;
endBlock = endBlock_;
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
function uri(uint256 _tokenId)
external
view
virtual
override
returns (string memory)
{
return string(abi.encodePacked(_uri, _tokenId.toString()));
}
/**
* @dev Total amount of tokens in with a given id.
*/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev Indicates weither any token exist with a given id, or not.
*/
function exists(uint256 id) public view virtual returns (bool) {
return GenArtTokenAirdropPass.totalSupply(id) > 0;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id)
public
view
virtual
override
returns (uint256)
{
require(
account != address(0),
"GenArtTokenAirdropPass: balance query for the zero address"
);
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(
accounts.length == ids.length,
"GenArtTokenAirdropPass: accounts and ids length mismatch"
);
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function setPaused(bool _pause) public onlyOwner {
_paused = _pause;
if (_paused) {
emit Paused(_msgSender());
} else {
emit Unpaused(_msgSender());
}
}
function setUri(string memory newUri) public onlyOwner {
_setURI(newUri);
}
function withdraw(uint256 value) public onlyOwner {
address _owner = owner();
payable(_owner).transfer(value);
}
/**
* @dev See {ERC1155-_mint}.
*/
function mint(
uint256 membershipId,
address account,
uint256 id,
uint256 amount
) public payable {
require(
block.number < endBlock,
"GenArtTokenAirdropPass: mint pass sale ended"
);
require(
id == 1 || id == 2 || id == 3,
"GenArtTokenAirdropPass: invalid token id"
);
uint256 index = id - 1;
require(
_totalSupply[id] + amount <= tokenId_cap[index],
"GenArtTokenAirdropPass: requested amount too high"
);
require(
IGenArt(genArtMembershipAddress).ownerOf(membershipId) ==
msg.sender,
"GenArtTokenAirdropPass: sender is not owner of membership"
);
uint256 ethValue;
unchecked {
ethValue = tokenId_prices[index] * amount;
}
require(
ethValue <= msg.value,
"GenArtTokenAirdropPass: wrong amount sent"
);
_mint(account, id, amount, "");
_totalSupply[id] += amount;
}
/**
* @dev See {ERC1155-_burn}.
*/
function burn(
address account,
uint256 id,
uint256 amount
) public {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"GenArtTokenAirdropPass: caller is not owner nor approved"
);
_burn(account, id, amount);
_totalSupply[id] -= amount;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(
_msgSender() != operator,
"GenArtTokenAirdropPass: setting approval status for self"
);
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"GenArtTokenAirdropPass: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"GenArtTokenAirdropPass: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(
to != address(0),
"GenArtTokenAirdropPass: transfer to the zero address"
);
address operator = _msgSender();
_beforeTokenTransfer();
uint256 fromBalance = _balances[id][from];
require(
fromBalance >= amount,
"GenArtTokenAirdropPass: insufficient balance for transfer"
);
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(
ids.length == amounts.length,
"GenArtTokenAirdropPass: ids and amounts length mismatch"
);
require(
to != address(0),
"GenArtTokenAirdropPass: transfer to the zero address"
);
address operator = _msgSender();
_beforeTokenTransfer();
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(
fromBalance >= amount,
"GenArtTokenAirdropPass: insufficient balance for transfer"
);
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(
operator,
from,
to,
ids,
amounts,
data
);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(
account != address(0),
"GenArtTokenAirdropPass: mint to the zero address"
);
address operator = _msgSender();
_beforeTokenTransfer();
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(
operator,
address(0),
account,
id,
amount,
data
);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(
account != address(0),
"GenArtTokenAirdropPass: burn from the zero address"
);
address operator = _msgSender();
_beforeTokenTransfer();
uint256 accountBalance = _balances[id][account];
require(
accountBalance >= amount,
"GenArtTokenAirdropPass: burn amount exceeds balance"
);
unchecked {
_balances[id][account] = accountBalance - amount;
}
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer() internal virtual {
require(!paused(), "ERC1155Pausable: token transfer while paused");
}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155Receiver(to).onERC1155Received(
operator,
from,
id,
amount,
data
)
returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert(
"GenArtTokenAirdropPass: ERC1155Receiver rejected tokens"
);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(
"GenArtTokenAirdropPass: transfer to non ERC1155Receiver implementer"
);
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try
IERC1155Receiver(to).onERC1155BatchReceived(
operator,
from,
ids,
amounts,
data
)
returns (bytes4 response) {
if (
response != IERC1155Receiver.onERC1155BatchReceived.selector
) {
revert(
"GenArtTokenAirdropPass: ERC1155Receiver rejected tokens"
);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(
"GenArtTokenAirdropPass: transfer to non ERC1155Receiver implementer"
);
}
}
}
function _asSingletonArray(uint256 element)
private
pure
returns (uint256[] memory)
{
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
|
See {ERC1155-_mint}./
|
function mint(
uint256 membershipId,
address account,
uint256 id,
uint256 amount
) public payable {
require(
block.number < endBlock,
"GenArtTokenAirdropPass: mint pass sale ended"
);
require(
id == 1 || id == 2 || id == 3,
"GenArtTokenAirdropPass: invalid token id"
);
uint256 index = id - 1;
require(
_totalSupply[id] + amount <= tokenId_cap[index],
"GenArtTokenAirdropPass: requested amount too high"
);
require(
IGenArt(genArtMembershipAddress).ownerOf(membershipId) ==
msg.sender,
"GenArtTokenAirdropPass: sender is not owner of membership"
);
uint256 ethValue;
unchecked {
ethValue = tokenId_prices[index] * amount;
}
require(
ethValue <= msg.value,
"GenArtTokenAirdropPass: wrong amount sent"
);
_mint(account, id, amount, "");
_totalSupply[id] += amount;
}
| 11,994,834
|
pragma solidity ^0.4.24;
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
contract PlayerBook {
using NameFilter for string;
using SafeMath for uint256;
address private admin;
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) .
//=============================|================================================
uint256 public registrationFee_ = 10 finney; // price to register a name
mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games
mapping(address => bytes32) public gameNames_; // lookup a games name
mapping(address => uint256) public gameIDs_; // lokup a games ID
uint256 public gID_; // total number of games
uint256 public pID_; // total number of players
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own)
mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns
struct Player {
address addr;
bytes32 name;
uint256 laff;
uint256 names;
}
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
pID_ = 1;
admin = msg.sender;
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isRegisteredGame()
{
require(gameIDs_[msg.sender] != 0);
_;
}
//==============================================================================
// _ _ _ _|_ _ .
// (/_\/(/_| | | _\ .
//==============================================================================
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
function checkIfNameValid(string _nameStr)
public
view
returns(bool)
{
bytes32 _name = _nameStr.nameFilter();
if (pIDxName_[_name] == 0)
return (true);
else
return (false);
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev registers a name. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who refered you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given, no new affiliate code was given, or the
// player tried to use their own pID as an affiliate code, lolz
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
// update last affiliate
plyr_[_pID].laff = _affCode;
} else if (_affCode == _pID) {
_affCode = 0;
}
// register name
registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// filter name + condition checks
bytes32 _name = NameFilter.nameFilter(_nameString);
// set up address
address _addr = msg.sender;
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
/**
* @dev players, if you registered a profile, before a game was released, or
* set the all bool to false when you registered, use this function to push
* your profile to a single game. also, if you've updated your name, you
* can use this to push your name to games of your choosing.
* -functionhash- 0x81c5b206
* @param _gameID game id
*/
function addMeToGame(uint256 _gameID)
isHuman()
public
{
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _totalNames = plyr_[_pID].names;
// add players profile and most recent name
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
// add list of all names
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
/**
* @dev players, use this to push your player profile to all registered games.
* -functionhash- 0x0c6940ea
*/
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
/**
* @dev players use this to change back to one of your old names. tip, you'll
* still need to push that info to existing games.
* -functionhash- 0xb9291296
* @param _nameString the name you want to use
*/
function useMyOldName(string _nameString)
isHuman()
public
{
// filter name, and get pID
bytes32 _name = _nameString.nameFilter();
uint256 _pID = pIDxAddr_[msg.sender];
// make sure they own the name
require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own");
// update their current name
plyr_[_pID].name = _name;
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ .
//=====================_|=======================================================
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
// if names already has been used, require that current msg sender owns the name
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
// add name to player profile, registry, and name book
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
// registration fee goes directly to community rewards
admin.transfer(address(this).balance);
// push player info to games
if (_all == true)
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
// fire event
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
// set the new player bool to true
return (true);
} else {
return (false);
}
}
//==============================================================================
// _ _|_ _ _ _ _ | _ _ || _ .
// (/_>< | (/_| | |(_|| (_(_|||_\ .
//==============================================================================
function getPlayerID(address _addr)
isRegisteredGame()
external
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
external
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
external
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
external
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
external
view
returns (uint256)
{
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given, no new affiliate code was given, or the
// player tried to use their own pID as an affiliate code, lolz
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
// update last affiliate
plyr_[_pID].laff = _affID;
} else if (_affID == _pID) {
_affID = 0;
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
// make sure name fees paid
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
// set up our tx event data and determine if player is new or not
bool _isNewPlayer = determinePID(_addr);
// fetch player id
uint256 _pID = pIDxAddr_[_addr];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// register name
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
//==============================================================================
// _ _ _|_ _ .
// _\(/_ | |_||_) .
//=============|================================================================
function addGame(address _gameAddress, string _gameNameStr)
public
{
require(admin == msg.sender,"Oops, only admin can add the games");
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
gID_++;
bytes32 _name = _gameNameStr.nameFilter();
gameIDs_[_gameAddress] = gID_;
gameNames_[_gameAddress] = _name;
games_[gID_] = PlayerBookReceiverInterface(_gameAddress);
games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0);
games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0);
games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0);
games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0);
}
function setRegistrationFee(uint256 _fee)
public
{
require(admin == msg.sender,"Oops, only admin can change the fees");
registrationFee_ = _fee;
}
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @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;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
============================================================================== _ |_ |. _ |` _ __|_. _ _ _ . |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)====|========================================================================= registers a name. UI will always display the last name you registered. but you will still own all previously registered names to use as affiliate links. - must pay a registration fee. - name must be unique - names will be converted to lowercase - name cannot start or end with a space - cannot have more than 1 space in a row - cannot be only numbers - cannot start with 0x - name must be at least 1 char - max length of 32 characters long - allowed characters: a-z, 0-9, and space -functionhash- 0x921dec21 (using ID for affiliate) -functionhash- 0x3ddd4698 (using address for affiliate) -functionhash- 0x685ffd83 (using name for affiliate) _nameString players desired name _affCode affiliate ID, address, or name of who refered you _all set to true if you want this to push your info to all games (this might cost a lot of gas)/ make sure name fees paid filter name + condition checks set up address set up our tx event data and determine if player is new or not fetch player id manage affiliate residuals if no affiliate code was given, no new affiliate code was given, or the player tried to use their own pID as an affiliate code, lolz update last affiliate
|
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
plyr_[_pID].laff = _affCode;
_affCode = 0;
}
}
| 2,083,466
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
// Part: IBasicRewards
interface IBasicRewards {
function stakeFor(address, uint256) external returns (bool);
function balanceOf(address) external view returns (uint256);
function earned(address) external view returns (uint256);
function withdrawAll(bool) external returns (bool);
function withdraw(uint256, bool) external returns (bool);
function withdrawAndUnwrap(uint256 amount, bool claim)
external
returns (bool);
function getReward() external returns (bool);
function stake(uint256) external returns (bool);
function extraRewards(uint256) external view returns (address);
}
// Part: IBooster
interface IBooster {
function depositAll(uint256 _pid, bool _stake) external returns (bool);
function deposit(
uint256 _pid,
uint256 _amount,
bool _stake
) external returns (bool);
function withdraw(uint256 _pid, uint256 _amount) external returns (bool);
function withdrawAll(uint256 _pid) external returns (bool);
}
// Part: ICVXLocker
interface ICVXLocker {
function lock(
address _account,
uint256 _amount,
uint256 _spendRatio
) external;
function balances(address _user)
external
view
returns (
uint112 locked,
uint112 boosted,
uint32 nextUnlockIndex
);
}
// Part: ICurveFactoryPool
interface ICurveFactoryPool {
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_balances() external view returns (uint256[2] memory);
function add_liquidity(
uint256[2] memory _amounts,
uint256 _min_mint_amount,
address _receiver
) external returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 _dx,
uint256 _min_dy,
address _receiver
) external returns (uint256);
}
// Part: ICurveTriCrypto
interface ICurveTriCrypto {
function exchange(
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy,
bool use_eth
) external payable;
function get_dy(
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256);
}
// Part: ICurveV2Pool
interface ICurveV2Pool {
function get_dy(
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256);
function exchange_underlying(
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy
) external payable returns (uint256);
function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount)
external
returns (uint256);
function future_A_gamma_time() external view returns (uint256);
function lp_price() external view returns (uint256);
}
// Part: IMerkleDistributorV2
interface IMerkleDistributorV2 {
enum Option {
Claim,
ClaimAsETH,
ClaimAsCRV,
ClaimAsCVX,
ClaimAndStake
}
function vault() external view returns (address);
function merkleRoot() external view returns (bytes32);
function week() external view returns (uint32);
function frozen() external view returns (bool);
function isClaimed(uint256 index) external view returns (bool);
function setApprovals() external;
function claim(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof
) external;
function claimAs(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof,
Option option
) external;
function claimAs(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof,
Option option,
uint256 minAmountOut
) external;
function freeze() external;
function unfreeze() external;
function stake() external;
function updateMerkleRoot(bytes32 newMerkleRoot, bool unfreeze) external;
function updateDepositor(address newDepositor) external;
function updateAdmin(address newAdmin) external;
function updateVault(address newVault) external;
event Claimed(
uint256 index,
uint256 amount,
address indexed account,
uint256 indexed week,
Option option
);
event DepositorUpdated(
address indexed oldDepositor,
address indexed newDepositor
);
event AdminUpdated(address indexed oldAdmin, address indexed newAdmin);
event VaultUpdated(address indexed oldVault, address indexed newVault);
event MerkleRootUpdated(bytes32 indexed merkleRoot, uint32 indexed week);
}
// Part: IRewards
interface IRewards {
function balanceOf(address) external view returns (uint256);
function stake(address, uint256) external;
function stakeFor(address, uint256) external;
function withdraw(address, uint256) external;
function exit(address) external;
function getReward(address) external;
function queueNewRewards(uint256) external;
function notifyRewardAmount(uint256) external;
function addExtraReward(address) external;
function stakingToken() external view returns (address);
function rewardToken() external view returns (address);
function earned(address account) external view returns (uint256);
}
// Part: ITriPool
interface ITriPool {
function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount)
external;
function get_virtual_price() external view returns (uint256);
}
// Part: IUniV2Router
interface IUniV2Router {
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] memory path)
external
view
returns (uint256[] memory amounts);
}
// Part: IUnionVault
interface IUnionVault {
enum Option {
Claim,
ClaimAsETH,
ClaimAsCRV,
ClaimAsCVX,
ClaimAndStake
}
function withdraw(address _to, uint256 _shares)
external
returns (uint256 withdrawn);
function withdrawAll(address _to) external returns (uint256 withdrawn);
function withdrawAs(
address _to,
uint256 _shares,
Option option
) external;
function withdrawAs(
address _to,
uint256 _shares,
Option option,
uint256 minAmountOut
) external;
function withdrawAllAs(address _to, Option option) external;
function withdrawAllAs(
address _to,
Option option,
uint256 minAmountOut
) external;
function depositAll(address _to) external returns (uint256 _shares);
function deposit(address _to, uint256 _amount)
external
returns (uint256 _shares);
function harvest() external;
function balanceOfUnderlying(address user)
external
view
returns (uint256 amount);
function outstanding3CrvRewards() external view returns (uint256 total);
function outstandingCvxRewards() external view returns (uint256 total);
function outstandingCrvRewards() external view returns (uint256 total);
function totalUnderlying() external view returns (uint256 total);
function underlying() external view returns (address);
function setPlatform(address _platform) external;
function setPlatformFee(uint256 _fee) external;
function setCallIncentive(uint256 _incentive) external;
function setWithdrawalPenalty(uint256 _penalty) external;
function setApprovals() external;
}
// Part: OpenZeppelin/openzeppelin-contracts@4.1.0/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/openzeppelin-contracts@4.1.0/Context
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Part: OpenZeppelin/openzeppelin-contracts@4.1.0/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/openzeppelin-contracts@4.1.0/Ownable
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// Part: OpenZeppelin/openzeppelin-contracts@4.1.0/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using 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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: UnionBase
// Common variables and functions
contract UnionBase {
address public constant CVXCRV_STAKING_CONTRACT =
0x3Fe65692bfCD0e6CF84cB1E7d24108E434A7587e;
address public constant CURVE_CRV_ETH_POOL =
0x8301AE4fc9c624d1D396cbDAa1ed877821D7C511;
address public constant CURVE_CVX_ETH_POOL =
0xB576491F1E6e5E62f1d8F26062Ee822B40B0E0d4;
address public constant CURVE_CVXCRV_CRV_POOL =
0x9D0464996170c6B9e75eED71c68B99dDEDf279e8;
address public constant CRV_TOKEN =
0xD533a949740bb3306d119CC777fa900bA034cd52;
address public constant CVXCRV_TOKEN =
0x62B9c7356A2Dc64a1969e19C23e4f579F9810Aa7;
address public constant CVX_TOKEN =
0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
uint256 public constant CRVETH_ETH_INDEX = 0;
uint256 public constant CRVETH_CRV_INDEX = 1;
int128 public constant CVXCRV_CRV_INDEX = 0;
int128 public constant CVXCRV_CVXCRV_INDEX = 1;
uint256 public constant CVXETH_ETH_INDEX = 0;
uint256 public constant CVXETH_CVX_INDEX = 1;
IBasicRewards cvxCrvStaking = IBasicRewards(CVXCRV_STAKING_CONTRACT);
ICurveV2Pool cvxEthSwap = ICurveV2Pool(CURVE_CVX_ETH_POOL);
ICurveV2Pool crvEthSwap = ICurveV2Pool(CURVE_CRV_ETH_POOL);
ICurveFactoryPool crvCvxCrvSwap = ICurveFactoryPool(CURVE_CVXCRV_CRV_POOL);
/// @notice Swap CRV for cvxCRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @return amount of CRV obtained after the swap
function _swapCrvToCvxCrv(uint256 amount, address recipient)
internal
returns (uint256)
{
return _crvToCvxCrv(amount, recipient, 0);
}
/// @notice Swap CRV for cvxCRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _swapCrvToCvxCrv(
uint256 amount,
address recipient,
uint256 minAmountOut
) internal returns (uint256) {
return _crvToCvxCrv(amount, recipient, minAmountOut);
}
/// @notice Swap CRV for cvxCRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _crvToCvxCrv(
uint256 amount,
address recipient,
uint256 minAmountOut
) internal returns (uint256) {
return
crvCvxCrvSwap.exchange(
CVXCRV_CRV_INDEX,
CVXCRV_CVXCRV_INDEX,
amount,
minAmountOut,
recipient
);
}
/// @notice Swap cvxCRV for CRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @return amount of CRV obtained after the swap
function _swapCvxCrvToCrv(uint256 amount, address recipient)
internal
returns (uint256)
{
return _cvxCrvToCrv(amount, recipient, 0);
}
/// @notice Swap cvxCRV for CRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _swapCvxCrvToCrv(
uint256 amount,
address recipient,
uint256 minAmountOut
) internal returns (uint256) {
return _cvxCrvToCrv(amount, recipient, minAmountOut);
}
/// @notice Swap cvxCRV for CRV on Curve
/// @param amount - amount to swap
/// @param recipient - where swapped tokens will be sent to
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _cvxCrvToCrv(
uint256 amount,
address recipient,
uint256 minAmountOut
) internal returns (uint256) {
return
crvCvxCrvSwap.exchange(
CVXCRV_CVXCRV_INDEX,
CVXCRV_CRV_INDEX,
amount,
minAmountOut,
recipient
);
}
/// @notice Swap CRV for native ETH on Curve
/// @param amount - amount to swap
/// @return amount of ETH obtained after the swap
function _swapCrvToEth(uint256 amount) internal returns (uint256) {
return _crvToEth(amount, 0);
}
/// @notice Swap CRV for native ETH on Curve
/// @param amount - amount to swap
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of ETH obtained after the swap
function _swapCrvToEth(uint256 amount, uint256 minAmountOut)
internal
returns (uint256)
{
return _crvToEth(amount, minAmountOut);
}
/// @notice Swap CRV for native ETH on Curve
/// @param amount - amount to swap
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of ETH obtained after the swap
function _crvToEth(uint256 amount, uint256 minAmountOut)
internal
returns (uint256)
{
return
crvEthSwap.exchange_underlying{value: 0}(
CRVETH_CRV_INDEX,
CRVETH_ETH_INDEX,
amount,
minAmountOut
);
}
/// @notice Swap native ETH for CRV on Curve
/// @param amount - amount to swap
/// @return amount of CRV obtained after the swap
function _swapEthToCrv(uint256 amount) internal returns (uint256) {
return _ethToCrv(amount, 0);
}
/// @notice Swap native ETH for CRV on Curve
/// @param amount - amount to swap
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _swapEthToCrv(uint256 amount, uint256 minAmountOut)
internal
returns (uint256)
{
return _ethToCrv(amount, minAmountOut);
}
/// @notice Swap native ETH for CRV on Curve
/// @param amount - amount to swap
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _ethToCrv(uint256 amount, uint256 minAmountOut)
internal
returns (uint256)
{
return
crvEthSwap.exchange_underlying{value: amount}(
CRVETH_ETH_INDEX,
CRVETH_CRV_INDEX,
amount,
minAmountOut
);
}
/// @notice Swap native ETH for CVX on Curve
/// @param amount - amount to swap
/// @return amount of CRV obtained after the swap
function _swapEthToCvx(uint256 amount) internal returns (uint256) {
return _ethToCvx(amount, 0);
}
/// @notice Swap native ETH for CVX on Curve
/// @param amount - amount to swap
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _swapEthToCvx(uint256 amount, uint256 minAmountOut)
internal
returns (uint256)
{
return _ethToCvx(amount, minAmountOut);
}
/// @notice Swap native ETH for CVX on Curve
/// @param amount - amount to swap
/// @param minAmountOut - minimum expected amount of output tokens
/// @return amount of CRV obtained after the swap
function _ethToCvx(uint256 amount, uint256 minAmountOut)
internal
returns (uint256)
{
return
cvxEthSwap.exchange_underlying{value: amount}(
CVXETH_ETH_INDEX,
CVXETH_CVX_INDEX,
amount,
minAmountOut
);
}
modifier notToZeroAddress(address _to) {
require(_to != address(0), "Invalid address!");
_;
}
}
// File: ExtraZaps.sol
contract ExtraZaps is Ownable, UnionBase {
using SafeERC20 for IERC20;
address public immutable vault;
address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address private constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address private constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
address private constant TRICRYPTO =
0xD51a44d3FaE010294C616388b506AcdA1bfAAE46;
address private constant TRIPOOL =
0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7;
address private constant TRICRV =
0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490;
address private constant BOOSTER =
0xF403C135812408BFbE8713b5A23a04b3D48AAE31;
address private constant CONVEX_TRIPOOL_TOKEN =
0x30D9410ED1D5DA1F6C8391af5338C93ab8d4035C;
address private constant CONVEX_TRIPOOL_REWARDS =
0x689440f2Ff927E1f24c72F1087E1FAF471eCe1c8;
address private constant CONVEX_LOCKER =
0x72a19342e8F1838460eBFCCEf09F6585e32db86E;
ICurveTriCrypto triCryptoSwap = ICurveTriCrypto(TRICRYPTO);
ITriPool triPool = ITriPool(TRIPOOL);
IBooster booster = IBooster(BOOSTER);
IRewards triPoolRewards = IRewards(CONVEX_TRIPOOL_REWARDS);
ICVXLocker locker = ICVXLocker(CONVEX_LOCKER);
IMerkleDistributorV2 distributor;
constructor(address _vault, address _distributor) {
vault = _vault;
distributor = IMerkleDistributorV2(_distributor);
}
function setApprovals() external {
IERC20(TRICRV).safeApprove(BOOSTER, 0);
IERC20(TRICRV).safeApprove(BOOSTER, type(uint256).max);
IERC20(USDT).safeApprove(TRIPOOL, 0);
IERC20(USDT).safeApprove(TRIPOOL, type(uint256).max);
IERC20(CONVEX_TRIPOOL_TOKEN).safeApprove(CONVEX_TRIPOOL_REWARDS, 0);
IERC20(CONVEX_TRIPOOL_TOKEN).safeApprove(
CONVEX_TRIPOOL_REWARDS,
type(uint256).max
);
IERC20(CRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, 0);
IERC20(CRV_TOKEN).safeApprove(CURVE_CVXCRV_CRV_POOL, type(uint256).max);
IERC20(CVXCRV_TOKEN).safeApprove(vault, 0);
IERC20(CVXCRV_TOKEN).safeApprove(vault, type(uint256).max);
IERC20(CVX).safeApprove(CONVEX_LOCKER, 0);
IERC20(CVX).safeApprove(CONVEX_LOCKER, type(uint256).max);
}
/// @notice Retrieves user's uCRV and unstake to ETH
/// @param amount - the amount of uCRV to unstake
function _withdrawFromVaultAsEth(uint256 amount) internal {
IERC20(vault).safeTransferFrom(msg.sender, address(this), amount);
IUnionVault(vault).withdrawAllAs(
address(this),
IUnionVault.Option.ClaimAsETH
);
}
/// @notice swap ETH to USDT via Curve's tricrypto
/// @param amount - the amount of ETH to swap
/// @param minAmountOut - the minimum amount expected
function _swapEthToUsdt(
uint256 amount,
uint256 minAmountOut,
address to
) internal {
triCryptoSwap.exchange{value: amount}(
2, // ETH
0, // USDT
amount,
minAmountOut,
true
);
}
/// @notice Unstake from the Pounder to USDT
/// @param amount - the amount of uCRV to unstake
/// @param minAmountOut - the min expected amount of USDT to receive
/// @param to - the adress that will receive the USDT
/// @return amount of USDT obtained
function claimFromVaultAsUsdt(
uint256 amount,
uint256 minAmountOut,
address to
) public notToZeroAddress(to) returns (uint256) {
_withdrawFromVaultAsEth(amount);
_swapEthToUsdt(address(this).balance, minAmountOut, to);
uint256 _usdtAmount = IERC20(USDT).balanceOf(address(this));
if (to != address(this)) {
IERC20(USDT).safeTransfer(to, _usdtAmount);
}
return _usdtAmount;
}
/// @notice Claim from the distributor, unstake and returns USDT.
/// @param index - claimer index
/// @param account - claimer account
/// @param amount - claim amount
/// @param merkleProof - merkle proof for the claim
/// @param minAmountOut - the min expected amount of USDT to receive
/// @param to - the adress that will receive the USDT
/// @return amount of USDT obtained
function claimFromDistributorAsUsdt(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof,
uint256 minAmountOut,
address to
) external notToZeroAddress(to) returns (uint256) {
distributor.claim(index, account, amount, merkleProof);
return claimFromVaultAsUsdt(amount, minAmountOut, to);
}
/// @notice Unstake from the Pounder to stables and stake on 3pool convex for yield
/// @param amount - amount of uCRV to unstake
/// @param minAmountOut - minimum amount of 3CRV (NOT USDT!)
/// @param to - address on behalf of which to stake
function claimFromVaultAndStakeIn3PoolConvex(
uint256 amount,
uint256 minAmountOut,
address to
) public notToZeroAddress(to) {
// claim as USDT
uint256 _usdtAmount = claimFromVaultAsUsdt(amount, 0, address(this));
// add USDT to Tripool
triPool.add_liquidity([0, 0, _usdtAmount], minAmountOut);
// deposit on Convex
booster.depositAll(9, false);
// stake on behalf of user
triPoolRewards.stakeFor(
to,
IERC20(CONVEX_TRIPOOL_TOKEN).balanceOf(address(this))
);
}
/// @notice Claim from the distributor, unstake and deposits in 3pool.
/// @param index - claimer index
/// @param account - claimer account
/// @param amount - claim amount
/// @param merkleProof - merkle proof for the claim
/// @param minAmountOut - minimum amount of 3CRV (NOT USDT!)
/// @param to - address on behalf of which to stake
function claimFromDistributorAndStakeIn3PoolConvex(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof,
uint256 minAmountOut,
address to
) external notToZeroAddress(to) {
distributor.claim(index, account, amount, merkleProof);
claimFromVaultAndStakeIn3PoolConvex(amount, minAmountOut, to);
}
/// @notice Claim to any token via a univ2 router
/// @notice Use at your own risk
/// @param amount - amount of uCRV to unstake
/// @param minAmountOut - min amount of output token expected
/// @param router - address of the router to use. e.g. 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F for Sushi
/// @param outputToken - address of the token to swap to
/// @param to - address of the final recipient of the swapped tokens
function claimFromVaultViaUniV2EthPair(
uint256 amount,
uint256 minAmountOut,
address router,
address outputToken,
address to
) public notToZeroAddress(to) {
require(router != address(0));
_withdrawFromVaultAsEth(amount);
address[] memory _path = new address[](2);
_path[0] = WETH;
_path[1] = outputToken;
IUniV2Router(router).swapExactETHForTokens{
value: address(this).balance
}(minAmountOut, _path, to, block.timestamp + 60);
}
/// @notice Claim to any token via a univ2 router
/// @notice Use at your own risk
/// @param amount - amount of uCRV to unstake
/// @param minAmountOut - min amount of output token expected
/// @param router - address of the router to use. e.g. 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F for Sushi
/// @param outputToken - address of the token to swap to
/// @param to - address of the final recipient of the swapped tokens
function claimFromDistributorViaUniV2EthPair(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof,
uint256 minAmountOut,
address router,
address outputToken,
address to
) external notToZeroAddress(to) {
distributor.claim(index, account, amount, merkleProof);
claimFromVaultViaUniV2EthPair(
amount,
minAmountOut,
router,
outputToken,
to
);
}
/// @notice Unstake from the Pounder as CVX and locks it
/// @param amount - amount of uCRV to unstake
/// @param minAmountOut - min amount of CVX expected
/// @param to - address to lock on behalf of
function claimFromVaultAsCvxAndLock(
uint256 amount,
uint256 minAmountOut,
address to
) public notToZeroAddress(to) {
IERC20(vault).safeTransferFrom(msg.sender, address(this), amount);
IUnionVault(vault).withdrawAllAs(
address(this),
IUnionVault.Option.ClaimAsCVX,
minAmountOut
);
locker.lock(to, IERC20(CVX).balanceOf(address(this)), 0);
}
/// @notice Claim from the distributor, unstake to CVX and lock.
/// @param index - claimer index
/// @param account - claimer account
/// @param amount - claim amount
/// @param merkleProof - merkle proof for the claim
/// @param minAmountOut - min amount of CVX expected
/// @param to - address to lock on behalf of
function claimFromDistributorAsCvxAndLock(
uint256 index,
address account,
uint256 amount,
bytes32[] calldata merkleProof,
uint256 minAmountOut,
address to
) external notToZeroAddress(to) {
distributor.claim(index, account, amount, merkleProof);
claimFromVaultAsCvxAndLock(amount, minAmountOut, to);
}
/// @notice Deposit into the pounder from ETH
/// @param minAmountOut - min amount of cvxCRV expected
/// @param to - address to stake on behalf of
function depositFromEth(uint256 minAmountOut, address to)
external
payable
notToZeroAddress(to)
{
require(msg.value > 0, "cheap");
_depositFromEth(msg.value, minAmountOut, to);
}
/// @notice Internal function to deposit ETH to the pounder
/// @param amount - amount of ETH
/// @param minAmountOut - min amount of cvxCRV expected
/// @param to - address to stake on behalf of
function _depositFromEth(
uint256 amount,
uint256 minAmountOut,
address to
) internal {
uint256 _crvAmount = _swapEthToCrv(amount);
uint256 _cvxCrvAmount = _swapCrvToCvxCrv(
_crvAmount,
address(this),
minAmountOut
);
IUnionVault(vault).deposit(to, _cvxCrvAmount);
}
/// @notice Deposit into the pounder from CRV
/// @param minAmountOut - min amount of cvxCRV expected
/// @param to - address to stake on behalf of
function depositFromCrv(
uint256 amount,
uint256 minAmountOut,
address to
) external notToZeroAddress(to) {
IERC20(CRV_TOKEN).safeTransferFrom(msg.sender, address(this), amount);
uint256 _cvxCrvAmount = _swapCrvToCvxCrv(
amount,
address(this),
minAmountOut
);
IUnionVault(vault).deposit(to, _cvxCrvAmount);
}
/// @notice Deposit into the pounder from any token via Uni interface
/// @notice Use at your own risk
/// @dev Zap contract needs approval for spending of inputToken
/// @param amount - min amount of input token
/// @param minAmountOut - min amount of cvxCRV expected
/// @param router - address of the router to use. e.g. 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F for Sushi
/// @param inputToken - address of the token to swap from, needs to have an ETH pair on router used
/// @param to - address to stake on behalf of
function depositViaUniV2EthPair(
uint256 amount,
uint256 minAmountOut,
address router,
address inputToken,
address to
) external notToZeroAddress(to) {
require(router != address(0));
IERC20(inputToken).safeTransferFrom(msg.sender, address(this), amount);
address[] memory _path = new address[](2);
_path[0] = inputToken;
_path[1] = WETH;
IERC20(inputToken).safeApprove(router, 0);
IERC20(inputToken).safeApprove(router, amount);
IUniV2Router(router).swapExactTokensForETH(
amount,
1,
_path,
address(this),
block.timestamp + 1
);
_depositFromEth(address(this).balance, minAmountOut, to);
}
/// @notice Execute calls on behalf of contract
/// (for instance to retrieve locked tokens)
function execute(
address _to,
uint256 _value,
bytes calldata _data
) external onlyOwner returns (bool, bytes memory) {
(bool success, bytes memory result) = _to.call{value: _value}(_data);
return (success, result);
}
receive() external payable {}
}
|
Swap native ETH for CVX on Curve amount - amount to swap minAmountOut - minimum expected amount of output tokens return amount of CRV obtained after the swap
|
function _ethToCvx(uint256 amount, uint256 minAmountOut)
internal
returns (uint256)
{
return
CVXETH_ETH_INDEX,
CVXETH_CVX_INDEX,
amount,
minAmountOut
);
}
| 75,331
|
pragma solidity 0.5.10;
import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/// @title DShops - Online Market Place Contract
/// @author CHET S
contract DShops is Pausable {
using SafeMath for uint256;
//////////////////////////////////////// State Variables & Mappings
address private contractOwner;
mapping(address => AdminStruct) private admins;
address[] private adminIndexes;
mapping(address => StoreOwnerApplicantStruct) private storeOwnerApplicants;
address[] private storeOwnerApplicantIndexes;
mapping(address => StoreOwnerStruct) private storeOwners;
address[] private storeOwnerIndexes;
mapping(bytes32 => storefrontStruct) private storefronts; // bytes32 represents uniqueId
bytes32[] private storefrontIndexes; // bytes32[] stores a collection of uniqueIds
mapping(bytes32 => ProductStruct) private products; // bytes32 represents productCode
bytes32[] private productIndexes; // bytes32[] stores a collection of productCodes
//////////////////////////////////////// Enums
enum StoreOwnerApplicantStatus {None, Applied, Approved}
//////////////////////////////////////// Structs
struct AdminStruct {
uint256 index;
}
struct StoreOwnerApplicantStruct {
StoreOwnerApplicantStatus status;
string name;
uint256 index;
}
struct StoreOwnerStruct {
bytes32[] storefrontUniqueIds;
string name;
uint256 index;
}
struct storefrontStruct {
string storefrontName;
address payable storeOwner;
uint256 balance;
mapping(bytes32 => uint256) productCodeIndexes;
bytes32[] productCodes;
uint256 index;
}
struct ProductStruct {
bytes32 storefrontUniqueId;
string name;
uint256 price;
uint256 availQty;
uint256 index;
string infoHash;
string imageHash;
}
//////////////////////////////////////// Contructor
/// @notice Assign msg.sender as the contractOwner as well as an Admin
constructor() public {
contractOwner = msg.sender;
assignUserAsAdmin(msg.sender);
}
//////////////////////////////////////// Modifiers
modifier onlyAdmin() {
if (adminIndexes.length > 0) {
require(isAdmin(msg.sender), "msg.sender must be an admin!");
} else {
require(contractOwner == msg.sender, "msg.sender must at least the contract owner!");
}
_;
}
modifier onlyStoreOwner() {
require(isStoreOwner(msg.sender), "msg.sender must be a store owner!");
_;
}
modifier onlyStoreOwnerOfProduct(bytes32 productCode) {
require(productExists(productCode), "product does not exist!");
require(
msg.sender == storefronts[products[productCode].storefrontUniqueId].storeOwner,
"msg.sender must be the store owner of the product!"
);
_;
}
modifier onlyStoreOwnerOfStorefront(bytes32 storefrontUniqueId) {
require(storefrontExists(storefrontUniqueId), "storefront does not exist!");
require(
storefronts[storefrontUniqueId].storeOwner == msg.sender,
"msg.sender must be the store owner of the storefront!"
);
_;
}
//////////////////////////////////////// Events
event LogAssignUserAsAdmin(address indexed adminAddr);
event LogRequestToBeStoreOwner(address indexed storeOwnerApplicantAddr);
event LogApproveStoreOwner(address indexed storeOwnerAddr);
event LogCreateStorefront(bytes32 indexed storefrontUniqueId);
event LogCreateProduct(bytes32 indexed productCode);
event LogDeleteProduct(bytes32 indexed productCode);
event LogUpdateProduct(bytes32 indexed productCode);
event LogBuyProduct(address indexed buyer, bytes32 indexed productCode);
event LogWithdrawBalanceFromStorefront(bytes32 indexed storefrontUniqueId);
//////////////////////////////////////// Functions
/// @notice Check if a user is an Admin or not
/// @param userAddr The address of the user
/// @return userIsAdmin as a boolean true or false
function isAdmin(address userAddr) public view returns (bool userIsAdmin) {
if (adminIndexes.length == 0) return false;
return (adminIndexes[admins[userAddr].index] == userAddr);
}
/// @notice Assign a non-admin user as an Admin. Only an Admin can invoke this function
/// and when the contract is not paused.
/// @param userAddr The address to be assigned as an Admin
/// @return index (uint256) of the added admin
function assignUserAsAdmin(address userAddr)
public
whenNotPaused
onlyAdmin
returns (uint256 index)
{
require(!isAdmin(userAddr), "Operation aborted. User is already an Admin");
admins[userAddr].index = (adminIndexes.push(userAddr)).sub(1);
emit LogAssignUserAsAdmin(userAddr);
return (adminIndexes.length).sub(1);
}
/// @notice Get the total number of Admins
/// @return count The total number of Admins in uint256
function getAdminsCount() public view returns (uint256 count) {
return (adminIndexes.length);
}
/// @notice Get the address of an Admin by an index
/// @param index The index of the Admin
/// @return adminAddr The address of the Admin
function getAdminByIndex(uint256 index) public view returns (address adminAddr) {
require(adminIndexes.length > 0, "Operation aborted. No admins to retrieve");
adminAddr = adminIndexes[index];
return (adminAddr);
}
/// @notice Get the total number of Store Owner Applicants
/// @return count The total number of Store Owner Applicants in uint256
function getStoreOwnerApplicantsCount() public view returns (uint256 count) {
return (storeOwnerApplicantIndexes.length);
}
/// @notice Get the Store Owner Applicant by index
/// @dev The storeOwnerApplicants contains data such as store owner name (name)
/// and the application status (status). The storeOwnerApplicantIndexes is
/// an array containing the store owner applicant addresses
/// @param index The index of the store owner applicant
/// @return userIsAdmin as a boolean true or false
function getStoreOwnerApplicantByIndex(uint256 index)
public
view
returns (
address storeOwnerApplicantAddr,
string memory storeOwnerApplicantName,
StoreOwnerApplicantStatus status
)
{
require(
storeOwnerApplicantIndexes.length > 0,
"Operation aborted. No store owner applicant to retrieve"
);
/// Get the address of the store owner using the index
/// and then use the address as the key to access the
/// store owner applicant details such as name and status
storeOwnerApplicantAddr = storeOwnerApplicantIndexes[index];
return (
storeOwnerApplicantAddr,
storeOwnerApplicants[storeOwnerApplicantAddr].name,
storeOwnerApplicants[storeOwnerApplicantAddr].status
);
}
/// @notice Check if a user is a store owner applicant
/// @param userAddr The address of the user
/// @return userIsStoreOwnerApplicant The boolean result
function isStoreOwnerApplicant(address userAddr)
public
view
returns (bool userIsStoreOwnerApplicant)
{
if (storeOwnerApplicantIndexes.length == 0) return false;
return (storeOwnerApplicantIndexes[storeOwnerApplicants[userAddr].index] == userAddr);
}
/// @notice Make a user become a store owner applicant. Any user can make this request.
/// @dev Only the first time applicant can be made an applicant. OpenZeppelin SafeMath is used
/// @param applicantAddr The address of the store owner applicant
/// @return index of the added store owner applicant in uint256
function requestToBeStoreOwner(address applicantAddr, string memory applicantName)
public
whenNotPaused
returns (uint256 index)
{
require(
!isStoreOwnerApplicant(applicantAddr),
"Request ignored. The user is already an Applicant"
);
/// Update initialize the status with 'Applied' and assign applicant name
storeOwnerApplicants[applicantAddr].status = StoreOwnerApplicantStatus.Applied;
storeOwnerApplicants[applicantAddr].name = applicantName;
/// storeOnerApplicantIndexes.push would return the updated length of the array,
/// subtract it by 1 would be the index of this newly added applicant
/// OpenZeppelin SafeMath is used .sub(1)
storeOwnerApplicants[applicantAddr].index = (storeOwnerApplicantIndexes.push(applicantAddr))
.sub(1);
emit LogRequestToBeStoreOwner(applicantAddr);
return (storeOwnerApplicantIndexes.length).sub(1);
}
/// @notice Add store owner applicant into the list of approved store owners.
/// Only Admin is allow to invoke this function
/// @param applicantAddr The address of the store owner applicant
/// @return index The uint256 index of the approved store owner indexes array
function approveStoreOwner(address applicantAddr)
public
whenNotPaused
onlyAdmin
returns (uint256 index)
{
require(isStoreOwnerApplicant(applicantAddr), "User must be a store applicant first");
require(
storeOwnerApplicants[applicantAddr].status == StoreOwnerApplicantStatus.Applied,
"User must be in the status of applied"
);
/// Update the store owner applicant's application status to 'Approved'
storeOwnerApplicants[applicantAddr].status = StoreOwnerApplicantStatus.Approved;
/// Add the new store owner into storeOwners using the applicantAddr as the key
/// storeOwners maps to a struct which holds the storeOwner's information
/// storeOwnerIndexes is an array containing the storeOwner addresses
/// Adding a store owner involves updating both the storeOwners and storeOwnerIndexes
storeOwners[applicantAddr].name = storeOwnerApplicants[applicantAddr].name;
storeOwners[applicantAddr].index = (storeOwnerIndexes.push(applicantAddr)).sub(1);
emit LogApproveStoreOwner(applicantAddr);
return (storeOwnerIndexes.length).sub(1);
}
/// @notice Check if a user is a store owner or not
/// @param userAddr The address of the user
/// @return userIsStoreOwner The boolean result
function isStoreOwner(address userAddr) public view returns (bool userIsStoreOwner) {
if (storeOwnerIndexes.length == 0) return false;
return (storeOwnerIndexes[storeOwners[userAddr].index] == userAddr);
}
/// @notice Get the total number of store owners
/// @return count The total number of store owners in uint256
function getStoreOwnersCount() public view returns (uint256 count) {
return (storeOwnerIndexes.length);
}
/// @notice Get a store owner's data by Index
/// @param index The index of the store owner
/// @return storeOwnerAddr The address of the store owner
/// @return storeOwnerName The store owner name
/// @return storefrontsCount The total number of storefronts the store owner has
function getStoreOwnerByIndex(uint256 index)
public
view
returns (address storeOwnerAddr, string memory storeOwnerName, uint256 storefrontsCount)
{
require(storeOwnerIndexes.length > 0, "Operation aborted. No store owner to retrieve");
storeOwnerAddr = storeOwnerIndexes[index];
return (
storeOwnerAddr,
storeOwners[storeOwnerAddr].name,
storeOwners[storeOwnerAddr].storefrontUniqueIds.length
);
}
/// @notice Get a store owner's data by store owner's address
/// @param addr The address of the store owner
/// @return storeOwnerAddr The address of the store owner
/// @return storeOwnerName The store owner name
/// @return storefrontsCount The total number of storefronts the store owner has
function getStoreOwner(address addr)
public
view
returns (uint256 storeOwnerIndex, string memory storeOwnerName, uint256 storefrontsCount)
{
storeOwnerIndex = storeOwners[addr].index;
storeOwnerName = storeOwners[addr].name;
storefrontsCount = storeOwners[addr].storefrontUniqueIds.length;
return (storeOwnerIndex, storeOwnerName, storefrontsCount);
}
/// @notice Create a storefront. Only a store owner can invoke this function.
/// @dev A unique storefront identity would be generated based on the storefront name,
/// a hash of the storefront name would be generated.
/// Each store owner can own multiple storefronts, represented by an array of
/// storefront unique IDs (hashes)
/// @param newStorefrontName The name of the storefront to be created.
/// @return index The index of the newly added storefront
function createStorefront(string memory newStorefrontName)
public
whenNotPaused
onlyStoreOwner
returns (uint256 index)
{
/// Generate the hash to be used as the storefront unique ID
bytes32 uniqueId = keccak256(abi.encodePacked(newStorefrontName));
require(
!storefrontExists(uniqueId),
"storefront name or storefront uniqueId already exists!"
);
/// The msg.sender should be the store owner.
/// Add the newly generated hash or storefront unique Id into
/// the storefrontUniqueIds array
storeOwners[msg.sender].storefrontUniqueIds.push(uniqueId);
/// Populate the store owner's storefront record with the details
/// Both storefronts (mapping to storefront struct) and
/// storefrontIndexes (array of hashes) would be updated accordingly
storefronts[uniqueId].storeOwner = msg.sender;
storefronts[uniqueId].index = (storefrontIndexes.push(uniqueId)).sub(1);
storefronts[uniqueId].storefrontName = newStorefrontName;
storefronts[uniqueId].balance = 0;
emit LogCreateStorefront(uniqueId);
return (storefrontIndexes.length).sub(1);
}
/// @notice Get the total number of storefronts of all store owners
/// @return count The total number of storefronts of all store owners in uint256
function getStorefrontsCount() public view returns (uint256 count) {
return storefrontIndexes.length;
}
/// @notice Get the total number of storefronts of a particular store owner.
/// Must provide a valid store owner's address
/// @param storeOwnerAddr The storeowner's address
/// @return count The total number of storefronts of a store store owner in uint256
function getStorefrontsCountForStoreOwner(address storeOwnerAddr)
public
view
returns (uint256 count)
{
require(isStoreOwner(storeOwnerAddr), "Input address must be a store owner address");
return storeOwners[storeOwnerAddr].storefrontUniqueIds.length;
}
/// @notice Get the data of a storeowner's storefront by the storefront index
/// @dev Get the data from the storefrontUniqueIds array based on index,
/// where the storefrontUniqueIds belongs to a store owner identified by
/// the storeOwnerAddr
/// @param storeOwnerAddr The address of the store owner
/// @param index The index (unint256) for fetching the storefront hash in the
/// storefrontUniqueIds array
/// @return storefrontName The name of the store owner's storefront indexed by index
/// @return storefrontUniqueId The storefront unique id or hash
/// @return productsCount The total number of products that the storefront has
/// @return balance The balance in uint256 (wei) that the storefront has.
/// The true balance will only be revealed to the storeowner who invokes this function.
/// Non store owner to this storefront will only see zero for the balance.
function getStorefrontForStoreOwnerByIndex(address storeOwnerAddr, uint256 index)
public
view
returns (
string memory storefrontName,
bytes32 storefrontUniqueId,
uint256 productsCount,
uint256 balance
)
{
/// Only the store owner who owns this storefront will get to see the actual balance,
/// others would see a zero balance
if (msg.sender == storeOwnerAddr)
balance = storefronts[storeOwners[storeOwnerAddr].storefrontUniqueIds[index]].balance;
else balance = 0;
return (
storefronts[storeOwners[storeOwnerAddr].storefrontUniqueIds[index]].storefrontName,
storeOwners[storeOwnerAddr].storefrontUniqueIds[index],
storefronts[storeOwners[storeOwnerAddr].storefrontUniqueIds[index]].productCodes.length,
balance
);
}
/// @notice Get a storefront by index, irrespective of store owner
/// @dev Get the storefront by using the index to access the storefrontIndexes array
/// @param index The index of the storefront, represented in storefrontIndexes
/// @return uniqueId The unique storefront Id or hash
/// @return storefrontName The storefront name
/// @return storeOwner The store owner's address that owns this storefront
/// @return productCodes The array of bytes32 representing the product codes that
/// this storefront owns
function getStorefrontByIndex(uint256 index)
public
view
returns (
bytes32 uniqueId,
string memory storefrontName,
address storeOwner,
uint256 productsCount,
bytes32[] memory productCodes
)
{
uniqueId = storefrontIndexes[index];
productCodes = storefronts[uniqueId].productCodes;
return (
uniqueId,
storefronts[uniqueId].storefrontName,
storefronts[uniqueId].storeOwner,
storefronts[uniqueId].productCodes.length,
productCodes
);
}
/// @notice Get as storefront by its storefront unique id or hash
/// @param storefrontUniqueId The storefront unique id or hash
/// @return storefrontName The storefront name
/// @return storeOwner The storeowner's address who owns this storefront
/// @return productsCount The total number of products that the storefront has
/// @return balance The balance in uint256 (wei) that the storefront has.
/// The true balance will only be revealed to the storeowner who invokes this function.
/// Non store owner to this storefront will only see zero for the balance.
function getStorefront(bytes32 storefrontUniqueId)
public
view
returns (
string memory storefrontName,
address storeOwner,
uint256 productsCount,
uint256 index,
uint256 balance
)
{
require(storefrontExists(storefrontUniqueId), "storefront does not exist!");
storefrontName = storefronts[storefrontUniqueId].storefrontName;
storeOwner = storefronts[storefrontUniqueId].storeOwner;
productsCount = storefronts[storefrontUniqueId].productCodes.length;
index = storefronts[storefrontUniqueId].index;
if (msg.sender == storeOwner) balance = storefronts[storefrontUniqueId].balance;
else balance = 0; // Only store owner can access to the balance
return (storefrontName, storeOwner, productsCount, index, balance);
}
/// @notice Check if a storefront exists, using its storefront unique id or hash
/// @param uniqueId The storefront unique id or hash
/// @return doesExist The boolean result of whether the storefront exists
function storefrontExists(bytes32 uniqueId) public view returns (bool doesExist) {
if (storefrontIndexes.length == 0) return false;
return (storefrontIndexes[storefronts[uniqueId].index] == uniqueId);
}
/// @notice Check if a product exists by its productCode
/// @param productCode The productCode
/// @return doesExist The boolean result of whether the product exists
function productExists(bytes32 productCode) public view returns (bool doesExist) {
if (productIndexes.length == 0) return false;
return (productIndexes[products[productCode].index] == productCode);
}
/// @notice Create a product for a storefront. Only store owner of the storefront
/// can invoke this function
/// @dev Creating a product involves updating products, productIndexes,
/// storefronts' productCodes (array of product codes) and storefront's
/// productCodeIndexes (mapping of productCode to index)
/// @param storefrontUniqueId The storefront unique id or hash
/// @param productCode The product code of the product.
/// This should be a hex generated code based on the product name.
/// The frontend app should generate this
/// @param newProductName The name of the product
/// @param price The unit price of the product
/// @param availQty The available quantity for the product
/// @param infoHash The IPFS hash for accessing the product info stored in IPFS
/// @param imageHash The IPFS hash for accessing the product image stored in IPFS
/// @return index The index of the created product in uint256
function createProduct(
bytes32 storefrontUniqueId,
bytes32 productCode,
string memory newProductName,
uint256 price,
uint256 availQty,
string memory infoHash,
string memory imageHash
) public whenNotPaused onlyStoreOwnerOfStorefront(storefrontUniqueId) returns (uint256 index) {
// require(storefrontExists(storefrontUniqueId), "storefront does not exist!");
// require(
// storefronts[storefrontUniqueId].storeOwner == msg.sender,
// "user is not the storefront owner"
// );
require(!productExists(productCode), "Product Code already exists!");
/// Add the productCode into storefront's productCodes array
/// and at the same time update the storefront's productCodeIndexes
/// with the index of the inserted productCode
storefronts[storefrontUniqueId]
.productCodeIndexes[productCode] = storefronts[storefrontUniqueId]
.productCodes
.push(productCode)
.sub(1);
/// Add the product info into products
/// at the same time update productIndexes.
/// The product index is derived from the productIndexes.push subtracted by 1
products[productCode].storefrontUniqueId = storefrontUniqueId;
products[productCode].name = newProductName;
products[productCode].price = price;
products[productCode].availQty = availQty;
products[productCode].infoHash = infoHash;
products[productCode].imageHash = imageHash;
products[productCode].index = (productIndexes.push(productCode)).sub(1);
emit LogCreateProduct(productCode);
return productIndexes.length.sub(1);
}
/// @notice Update the price of a product. Only the store owner of the storefront
/// that owns the product can invoke this function
/// @param productCode The product code of the product to be updated
/// @param newPrice The new product price to replace the old product price
function updateProductPrice(bytes32 productCode, uint256 newPrice)
public
whenNotPaused
onlyStoreOwnerOfProduct(productCode)
{
//require(productExists(productCode), "Product does not exist!");
// bytes32 storefrontUniqueId = products[productCode].storefrontUniqueId;
// require(
// msg.sender == storefronts[storefrontUniqueId].storeOwner,
// "Only store owner of product can update the price!"
// );
products[productCode].price = newPrice;
emit LogUpdateProduct(productCode);
}
/// @notice Delete a product by its productCode. Only the store owner of
/// the storefront that owns the product can invoke this function
/// @dev Delete requires updates to the products, productIndexes,
/// storefront's productCodes and storefront's productIndexes
/// @param productCode The productCode of the product to be deleted
function deleteProduct(bytes32 productCode)
public
whenNotPaused
onlyStoreOwnerOfProduct(productCode)
{
//require(productExists(productCode), "Product does not exist!");
// Get the index (uint256) of the productCode of the products mappping
// We name this index rowToDelete
// We will use this index later to swap position of the last item in the productIndexes array
// with the item we want to delete (productCode) in the array
uint256 rowToDelete = products[productCode].index;
// Get the product code of the last item in the productIndexes array
bytes32 keyToMove = productIndexes[productIndexes.length.sub(1)];
// Swap the position of the last item in the productIndexes
// with the position of the productCode we want to delete
productIndexes[rowToDelete] = keyToMove;
products[keyToMove].index = rowToDelete;
// Now we delete the last item in the productIndexes which contains the productCode
productIndexes.pop();
// Remove the associated productCode stored in the corresponding storefront
// First, we get the storefrontUniqueId based on input productCode
bytes32 storeId = products[productCode].storefrontUniqueId;
// Get the index (uint256) of the productCode of the array productCodes in the storefront
// We name this index rowToDelete
// We will use this index later to swap position of the last item in the array
// with the item we want to delete (productCode)
rowToDelete = storefronts[storeId].productCodeIndexes[productCode];
// Get the index of the last item in the array productCodes of the storefront
// for the swapping mentioned above
uint256 lastIndex = storefronts[storeId].productCodes.length.sub(1);
// Get the content (a product code) of the last item in the array productCodes
// using the lastIndex we obtained above
keyToMove = storefronts[storeId].productCodes[lastIndex];
// Now we swap the content (product code) of the last item with the item we want to delete
storefronts[storeId].productCodes[rowToDelete] = keyToMove;
storefronts[storeId].productCodes[lastIndex] = productCode;
// We also need to update the productCodeIndexes in the storefront
// to reflect the swapping took place above
storefronts[storeId].productCodeIndexes[keyToMove] = rowToDelete;
storefronts[storeId].productCodeIndexes[productCode] = lastIndex;
// Now we can remove the last item of the productCodes array which contains the productCode
storefronts[storeId].productCodes.pop();
// Also remove the mapping of the productCodeIndexes
// Note that deleted mapping would still be referencable but the result would be zero
// So the zero result can mean index 0 or no mapping found, keep in mind
delete storefronts[storeId].productCodeIndexes[productCode];
// Remove the product from the mapping(bytes32=>ProductStruct) products
// We do it here at the end so that fetch the storefrontUniqueId, storeId above
delete products[productCode];
emit LogDeleteProduct(productCode);
}
/// @notice Get the total number of products of all storefronts
/// @return count The total number of products of all storefronts in uint256
function getProductsCount() public view returns (uint256 count) {
return productIndexes.length;
}
/// @notice Get product data by its productCode
/// @param productCode The product code of the product
/// @return productName The name of the product
/// @return price The unit price of the product
/// @return availQty The available quantity for the product
/// @return index The index for accessing this product via productIndexes
/// @return infoHash The IPFS hash for accesing the product information
/// @return imageHash The IPFS hash for accessing the product image
function getProduct(bytes32 productCode)
public
view
returns (
string memory productName,
uint256 price,
uint256 availQty,
uint256 index,
string memory infoHash,
string memory imageHash
)
{
require(productExists(productCode), "product does not exist!");
productName = products[productCode].name;
price = products[productCode].price;
availQty = products[productCode].availQty;
index = products[productCode].index;
infoHash = products[productCode].infoHash;
imageHash = products[productCode].imageHash;
return (productName, price, availQty, index, infoHash, imageHash);
}
/// @notice Get the product data by its index
/// @param index The index for accessing the product via productIndexes
/// @return productCode The product code of the product
/// @return productName The name of the product
/// @return price The unit price of the product
/// @return availQty The available quantity for the product
/// @return infoHash The IPFS hash for accesing the product information
/// @return imageHash The IPFS hash for accessing the product image
function getProductByIndex(uint256 index)
public
view
returns (
bytes32 productCode,
string memory productName,
uint256 price,
uint256 availQty,
string memory infoHash,
string memory imageHash
)
{
productCode = productIndexes[index];
return (
productCode,
products[productCode].name,
products[productCode].price,
products[productCode].availQty,
products[productCode].infoHash,
products[productCode].imageHash
);
}
/// @notice Get the storefront's product by product Index
/// @param storefrontUniqueId The storefront unique id or hash
/// @param index The index for accessing the product data via productCodes
/// @return productCode The product code of the product
/// @return productName The name of the product
/// @return price The unit price of the product
/// @return availQty The available quantity for the product
/// @return infoHash The IPFS hash for accesing the product information
/// @return imageHash The IPFS hash for accessing the product image
function getProductForStorefrontByIndex(bytes32 storefrontUniqueId, uint256 index)
public
view
returns (
bytes32 productCode,
string memory productName,
uint256 price,
uint256 availQty,
string memory infoHash,
string memory imageHash
)
{
require(storefrontExists(storefrontUniqueId), "storefront does not exist!");
require(storefronts[storefrontUniqueId].productCodes.length > index, "index out of range!");
productCode = storefronts[storefrontUniqueId].productCodes[index];
return (
productCode,
products[productCode].name,
products[productCode].price,
products[productCode].availQty,
products[productCode].infoHash,
products[productCode].imageHash
);
}
/// @notice Let shopper buy and pay for a product. If shopper pays more than the required amount,
/// the shopper would be refunded. If the shopper tries to pay below the amount required, this
/// function would reject it. If the buying quantity is more than the available quantity, this
/// function would reject it too.
/// @dev OpenZeppelin SafeMath is used here to prevent overflow or underflow
/// @param productCode The product code of the product that the shopper is buying or paying for
/// @param buyQty The quantity of the product the shopper wants to buy or pay for
function buyProduct(bytes32 productCode, uint256 buyQty) public payable whenNotPaused {
require(productExists(productCode), "Product does not exist!");
require(buyQty > 0, "Buy quantity must be more than zero!");
uint256 price = products[productCode].price;
uint256 availQty = products[productCode].availQty;
uint256 amountPayable = price.mul(buyQty);
uint256 refund = 0;
if (msg.value > amountPayable) {
refund = msg.value.sub(amountPayable);
}
require(buyQty <= availQty, "Buy quantity is more than the available quantity!");
require(msg.value >= amountPayable, "Insufficient funds to complete transaction!");
bytes32 uniqueId = products[productCode].storefrontUniqueId;
storefronts[uniqueId].balance = storefronts[uniqueId].balance.add(amountPayable);
/// Deduct the available quantity of the product
products[productCode].availQty = products[productCode].availQty.sub(buyQty);
emit LogBuyProduct(msg.sender, productCode);
/// If there's refund to be made, do it now
if (refund > 0) {
msg.sender.transfer(refund);
}
}
/// @notice Withdraw the balance from a storefront,
/// if the balance is more than zero. Only store owner of the storefront
/// can invoke this function
/// @param storefrontUniqueId The storefront unique id or hash
/// @return success The boolean result whether the withdrawal is successful
function withdrawBalanceFromStorefront(bytes32 storefrontUniqueId)
public
whenNotPaused
returns (bool success)
{
require(storefrontExists(storefrontUniqueId), "Storefront does not exist!");
require(
msg.sender == storefronts[storefrontUniqueId].storeOwner,
"Must be the owner to withdraw balance!"
);
uint256 balanceToWithdraw = storefronts[storefrontUniqueId].balance;
require(balanceToWithdraw > 0, "The balance must be more than zero to withdraw!");
storefronts[storefrontUniqueId].balance = (storefronts[storefrontUniqueId].balance).sub(
balanceToWithdraw
);
emit LogWithdrawBalanceFromStorefront(storefrontUniqueId);
msg.sender.transfer(balanceToWithdraw); // transfer balance back to store owner
return true;
}
/// Fallback function
function() external {
revert("");
}
}
|
Check if a product exists by its productCode productCode The productCode return doesExist The boolean result of whether the product exists
|
function productExists(bytes32 productCode) public view returns (bool doesExist) {
if (productIndexes.length == 0) return false;
return (productIndexes[products[productCode].index] == productCode);
}
| 14,112,207
|
pragma solidity ^0.5.8;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
uint airLineCount = 1;
uint flightCount = 1;
uint insuranceCount = 1;
uint constant flightStatusDefault = 0;
uint constant airlineApprovesMin = 4;
struct Airline {
uint id;
bool feePaid;
bool accepted;
uint[] votes;
}
struct Flight {
uint id;
bytes32 key;
address airline;
string flightCode;
uint departureTime;
uint status;
uint updatedTime;
}
enum InsuranceState {Valid, Expired, Refunded}
struct Insurance{
uint id;
bytes32 flightId;
uint amountPaid;
address passenger;
InsuranceState state;
}
mapping(address => Airline) airlines;
mapping(bytes32 => Flight) flights;
mapping(uint => Insurance) insurances;
mapping(address => uint[]) airlinesFlights;
mapping(bytes32 => uint[]) flightsInsurances;
mapping(address => uint[]) passengersInsurances;
mapping(address => uint) authorizedCallers;
mapping(address => uint) passengersFund;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event AirlineAdded(uint id, address airline);
event AirlineVote(address candidate, address voter);
event AirlinePaidFund(address airline, uint amount);
event FlightAdded(uint id, address airline, string flightCode);
event FlightCodeChanged(bytes32 key, uint status);
event FlightStatusUpdated(bytes32 key, uint status, uint time);
event InsuranceAdded(uint id, bytes32 flightId);
event InsuranceRefunded(uint id);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor() public {
contractOwner = msg.sender;
authorizedCallers[msg.sender] = 1;
_registerAirline(msg.sender, msg.sender);
airlines[msg.sender].feePaid = true;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(operational, "Contract is currently not operational");
_;
// All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireBeAnAirline(address airline) {
require(airlines[airline].id != 0, "You must be an airline");
_;
}
modifier requireAcceptedAirline(address airline) {
require(airlines[airline].accepted, "To vote you must be accepted first");
_;
}
modifier requirePaidAirline(address airline) {
require(airlines[airline].feePaid, "To participate you must pay");
_;
}
modifier requireAirlineOperable(address airline) {
require(airlines[airline].feePaid && airlines[airline].accepted, "Airline isn't operable");
_;
}
modifier requireAuthorized() {
require(authorizedCallers[msg.sender] == 1, "You don't have authorization");
_;
}
modifier didntVote(address candidate) {
uint[] memory votes = airlines[candidate].votes;
uint idApprover = airlines[msg.sender].id;
bool found = false;
for (uint i = 0; i < votes.length; i++) {
if(votes[i] == idApprover){
found = true;
break;
}
}
require (!found, "You already vote for this new Airline");
_;
}
modifier requireNotRegistered(string memory flightCode, uint departureTimestamp, address airlineAddress) {
bytes32 key = getFlightKey(airlineAddress, flightCode, departureTimestamp);
require(flights[key].id == 0, "The flight has already been created!");
_;
}
modifier requireFlight(bytes32 key) {
require(flights[key].id > 0, "Flight must exist");
_;
}
modifier requireInsurance(uint id) {
require(insurances[id].id > 0, "Insurance doesn't exists");
_;
}
modifier insuranceWithState(uint id, InsuranceState state) {
require(insurances[id].state == state, "Insurance isn't on this state");
_;
}
modifier isPassengerInsurance(uint id) {
require(insurances[id].passenger == msg.sender, "You are not the insurance owner");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() public view returns (bool) {
return operational;
}
function isAirlineRegistered(address airline) public view returns (bool) {
return airlines[airline].id > 0;
}
function isAirlineAccepted(address airline) public view returns (bool) {
return airlines[airline].accepted;
}
function isAirlineFunded(address airline) public view returns (bool) {
return airlines[airline].feePaid;
}
function isFlightRegistered(address airline, string memory flightCode, uint departureTime) public view returns (bool) {
bytes32 key = getFlightKey(airline, flightCode, departureTime);
return flights[key].id > 0;
}
function isPassengerInsured(address passenger, address airline, string memory flightCode, uint departureTime) public view returns (bool) {
bool insured = false;
bytes32 key = getFlightKey(airline, flightCode, departureTime);
uint [] memory passengerInsurances = passengersInsurances[passenger];
for (uint i = 0; i < passengerInsurances.length; i++) {
if (insurances[passengerInsurances[i]].flightId == key) {
insured = true;
break;
}
}
return insured;
}
function getOwner() external view requireContractOwner returns(address owner) {
return contractOwner;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(bool mode) external requireContractOwner {
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(address airline, address elector) external requireIsOperational requireAuthorized requireBeAnAirline(elector) requireAcceptedAirline(elector) requirePaidAirline(elector){
_registerAirline(airline, elector);
}
function _registerAirline(address airline, address elector) internal {
airlines[airline].id = airLineCount;
airlines[airline].feePaid = false;
airlines[airline].accepted = airLineCount <= airlineApprovesMin;
airlines[airline].votes.push(airlines[elector].id);
airLineCount++;
emit AirlineAdded(airlines[airline].id, airline);
}
function registerFlight(address airline, string calldata flightCode, uint departureTime) external requireIsOperational requireAuthorized requireAirlineOperable(airline) {
bytes32 key = getFlightKey(airline, flightCode, departureTime);
require(flights[key].id == 0, "must be a new Flight");
Flight memory newFlight = Flight(flightCount, key, airline, flightCode, departureTime, flightStatusDefault, departureTime);
flights[key] = newFlight;
flightCount++;
airlinesFlights[airline].push(newFlight.id);
emit FlightAdded(newFlight.id, newFlight.airline, newFlight.flightCode);
}
function setFlightCode(bytes32 key, uint status, uint updateTime) external requireIsOperational requireAuthorized requireFlight(key) {
flights[key].status = status;
flights[key].updatedTime = updateTime;
emit FlightCodeChanged(key, status);
}
function getFlight(string calldata _flightCode, uint departureTime, address airline) external view requireIsOperational requireAuthorized returns (bytes32 key, address airlineAddress, string memory flightCode, uint departureStatusCode, uint departureTimestamp, uint updatedTimestamp){
bytes32 _key = getFlightKey(airline, _flightCode, departureTime);
Flight memory flight = flights[_key];
return (flight.key, flight.airline, flight.flightCode, flight.status, flight.departureTime, flight.updatedTime);
}
function getFlight(bytes32 _key) external view requireIsOperational requireAuthorized returns (bytes32 key, address airlineAddress, string memory flightCode, uint departureStatusCode, uint departureTimestamp, uint updatedTimestamp){
Flight memory flight = flights[_key];
return (flight.key, flight.airline, flight.flightCode, flight.status, flight.departureTime, flight.updatedTime);
}
function setFlightDepartureStatus(bytes32 key, uint departureStatus, uint updateTime) external requireIsOperational requireAuthorized requireFlight(key) {
flights[key].status = departureStatus;
flights[key].updatedTime = updateTime;
emit FlightStatusUpdated(key, departureStatus, updateTime);
}
function buyInsurance(bytes32 flightId, address passenger) external payable requireIsOperational requireAuthorized requireFlight(flightId) {
Insurance memory insurance = Insurance(insuranceCount, flightId, msg.value, passenger, InsuranceState.Valid);
insurances[insuranceCount] = insurance;
passengersInsurances[passenger].push(insurance.id);
flightsInsurances[flightId].push(insurance.id);
insuranceCount++;
emit InsuranceAdded(insurance.id, insurance.flightId);
}
function getInsurance(uint id) external view requireIsOperational requireAuthorized returns (address passenger, uint amountPaid, uint insuranceState) {
Insurance memory insurance = insurances[id];
return (insurance.passenger, insurance.amountPaid, uint(insurance.state));
}
function getInsurancesFromFlight(bytes32 flightId) external view requireIsOperational requireAuthorized returns (uint[] memory _insurances) {
return flightsInsurances[flightId];
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(uint id, uint multiplier) external requireIsOperational requireAuthorized insuranceWithState(id, InsuranceState.Valid) {
Insurance memory insurance = insurances[id];
insurances[id].state = InsuranceState.Refunded;
uint amountPaid = insurance.amountPaid;
passengersFund[insurance.passenger] = passengersFund[insurance.passenger].add(multiplier.mul(amountPaid));
emit InsuranceRefunded(id);
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(address payable passenger) external payable requireIsOperational requireAuthorized {
require(passengersFund[passenger] > 0, "Passenger doesn't have funds");
uint toRefund = passengersFund[passenger];
passengersFund[passenger] = passengersFund[passenger].sub(toRefund);
passenger.transfer(toRefund);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund(address airline) public payable requireIsOperational requireAuthorized requireBeAnAirline(airline) {
require(msg.value >= 10 ether, "You didn't pay enough");
airlines[airline].feePaid = true;
emit AirlinePaidFund(airline, msg.value);
}
function getFlightKey(address airline, string memory flight, uint256 timestamp) pure internal returns (bytes32){
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
function voteAirline(address airline, address elector, uint minimum) public requireIsOperational requireAuthorized requireBeAnAirline(elector) requireAcceptedAirline(elector) requirePaidAirline(elector) didntVote(elector) {
airlines[airline].votes.push(airlines[elector].id);
airlines[airline].accepted = airlines[airline].votes.length > minimum;
emit AirlineVote(airline, elector);
}
function authorizeContract(address addressToAuth) external requireIsOperational requireContractOwner {
authorizedCallers[addressToAuth] = 1;
}
function deauthorizeContract(address dataContract) external requireIsOperational requireContractOwner {
delete authorizedCallers[dataContract];
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function() external payable {
fund(msg.sender);
}
}
|
Transfers eligible payout funds to insuree/
|
function pay(address payable passenger) external payable requireIsOperational requireAuthorized {
require(passengersFund[passenger] > 0, "Passenger doesn't have funds");
uint toRefund = passengersFund[passenger];
passengersFund[passenger] = passengersFund[passenger].sub(toRefund);
passenger.transfer(toRefund);
}
| 15,788,532
|
./partial_match/3/0x9A28784E4eb2d2Fb1C8E74094DFC1536B54C62aF/sources/PrizeDistribution.sol
|
Returns the prize distribution for a given competition/
|
function getPrizeDistribution(
uint256 _competitionId
) public competitionExists(_competitionId) view returns(uint256[] memory) {
Competition storage competition = competitions[_competitionId];
return competition.prizeDistribution;
}
| 5,101,472
|
pragma solidity ^0.4.18;
contract ERC20 {
function totalSupply() constant public returns (uint supply);
function balanceOf( address who ) constant public returns (uint value);
function allowance( address owner, address spender ) constant public returns (uint _allowance);
function transfer( address to, uint value) public returns (bool ok);
function transferFrom( address from, address to, uint value) public returns (bool ok);
function approve( address spender, uint value ) public returns (bool ok);
event Transfer( address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) constant public returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_) public
auth
{
require(owner_ != address(0));
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_) public
auth
{
authority = authority_;
emit LogSetAuthority(authority);
}
modifier auth {
assert(isAuthorized(msg.sender, msg.sig));
_;
}
modifier authorized(bytes4 sig) {
assert(isAuthorized(msg.sender, sig));
_;
}
function isAuthorized(address src, bytes4 sig) view internal returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract DSStop is DSAuth, DSNote {
bool public stopped;
modifier stoppable {
assert (!stopped);
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
contract DSMath {
/*
standard uint256 functions
*/
function add(uint256 x, uint256 y) pure internal returns (uint256 z) {
assert((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) pure internal returns (uint256 z) {
assert((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) pure internal returns (uint256 z) {
assert((z = x * y) >= x);
}
function div(uint256 x, uint256 y) pure internal returns (uint256 z) {
z = x / y;
}
function min(uint256 x, uint256 y) pure internal returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) pure internal returns (uint256 z) {
return x >= y ? x : y;
}
/*
uint128 functions (h is for half)
*/
function hadd(uint128 x, uint128 y) pure internal returns (uint128 z) {
assert((z = x + y) >= x);
}
function hsub(uint128 x, uint128 y) pure internal returns (uint128 z) {
assert((z = x - y) <= x);
}
function hmul(uint128 x, uint128 y) pure internal returns (uint128 z) {
assert((z = x * y) >= x);
}
function hdiv(uint128 x, uint128 y) pure internal returns (uint128 z) {
z = x / y;
}
function hmin(uint128 x, uint128 y) pure internal returns (uint128 z) {
return x <= y ? x : y;
}
function hmax(uint128 x, uint128 y) pure internal returns (uint128 z) {
return x >= y ? x : y;
}
/*
int256 functions
*/
function imin(int256 x, int256 y) pure internal returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) pure internal returns (int256 z) {
return x >= y ? x : y;
}
/*
WAD math
*/
uint128 constant WAD = 10 ** 18;
function wadd(uint128 x, uint128 y) pure internal returns (uint128) {
return hadd(x, y);
}
function wsub(uint128 x, uint128 y) pure internal returns (uint128) {
return hsub(x, y);
}
function wmul(uint128 x, uint128 y) pure internal returns (uint128 z) {
z = cast((uint256(x) * y + WAD / 2) / WAD);
}
function wdiv(uint128 x, uint128 y) pure internal returns (uint128 z) {
z = cast((uint256(x) * WAD + y / 2) / y);
}
function wmin(uint128 x, uint128 y) pure internal returns (uint128) {
return hmin(x, y);
}
function wmax(uint128 x, uint128 y) pure internal returns (uint128) {
return hmax(x, y);
}
/*
RAY math
*/
uint128 constant RAY = 10 ** 27;
function radd(uint128 x, uint128 y) pure internal returns (uint128) {
return hadd(x, y);
}
function rsub(uint128 x, uint128 y) pure internal returns (uint128) {
return hsub(x, y);
}
function rmul(uint128 x, uint128 y) pure internal returns (uint128 z) {
z = cast((uint256(x) * y + RAY / 2) / RAY);
}
function rdiv(uint128 x, uint128 y) pure internal returns (uint128 z) {
z = cast((uint256(x) * RAY + y / 2) / y);
}
function rpow(uint128 x, uint64 n) pure internal returns (uint128 z) {
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
function rmin(uint128 x, uint128 y) pure internal returns (uint128) {
return hmin(x, y);
}
function rmax(uint128 x, uint128 y) pure internal returns (uint128) {
return hmax(x, y);
}
function cast(uint256 x) pure internal returns (uint128 z) {
assert((z = uint128(x)) == x);
}
}
contract DSTokenBase is ERC20, DSMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
constructor(uint256 supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() public constant returns (uint256) {
return _supply;
}
function balanceOf(address src) public constant returns (uint256) {
return _balances[src];
}
function allowance(address src, address guy) public constant returns (uint256) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) public returns (bool) {
assert(_balances[msg.sender] >= wad);
_balances[msg.sender] = sub(_balances[msg.sender], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(msg.sender, dst, wad);
return true;
}
function transferFrom(address src, address dst, uint wad) public returns (bool) {
assert(_balances[src] >= wad);
assert(_approvals[src][msg.sender] >= wad);
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function approve(address guy, uint256 wad) public returns (bool) {
_approvals[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
}
contract DSToken is DSTokenBase(0), DSStop {
string public name = "ERC20 CES";
string public symbol = "CES"; // token name
uint8 public decimals = 0; // standard token precision
function transfer(address dst, uint wad) public stoppable note returns (bool) {
return super.transfer(dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public stoppable note returns (bool) {
return super.transferFrom(src, dst, wad);
}
function approve(address guy, uint wad) public stoppable note returns (bool) {
return super.approve(guy, wad);
}
function push(address dst, uint128 wad) public returns (bool) {
return transfer(dst, wad);
}
function pull(address src, uint128 wad) public returns (bool) {
return transferFrom(src, msg.sender, wad);
}
function mint(uint128 wad) public auth stoppable note {
_balances[msg.sender] = add(_balances[msg.sender], wad);
_supply = add(_supply, wad);
}
function burn(uint128 wad) public auth stoppable note {
_balances[msg.sender] = sub(_balances[msg.sender], wad);
_supply = sub(_supply, wad);
}
/*
function setName(string name_, string symbol_) public auth {
name = name_;
symbol = symbol_;
}
*/
}
contract CESVendue is DSAuth, DSMath {
DSToken public CES;
uint public totalETH; // total ETH was got by vendue
uint public price; // vendue Reserve price
uint32 public iaSupply; // total initialize account for vendue
uint32 public iaLeft; // how many initialize account was left
struct accountInfo {
// vendue ETH
uint ethVendue;
// The account name used at CES block chain ecocsystem
string accountName;
// The public key used for your account
string publicKey;
// The pinblock used for your account calc by your password
string pinblock;
}
struct elfInfo {
// whether get the elf
bool bGetElf;
// The elf sex
uint8 elfSex;
// The elf type
uint16 elfType;
}
mapping (address => elfInfo) public elfInfos;
mapping (address => accountInfo) public initAccInfos; // init account
mapping (address => string) public commonAccs; // common account
address public godOwner;// the owner who got the god after vendue was closed
uint16 public godID; // god owner select his god
bool public vendueClose = false;
bool public tokenFreeze = false;
address[] public addrLists;
uint startLine;
event LogFund(address backer, uint amount, bool isContribution, uint gift);
event LogFreeze();
event LogElf(address user, uint8 elfSex, uint16 elfType);
event LogGod(address owner, uint16 godID);
event LogInitAcc(address user, string account, string key, string pin);
event LogRegister(address user, string key, uint token);
constructor() public {
iaSupply = 20000;
iaLeft = iaSupply;
startLine = now;
price = 5 ether;
}
function initialize(DSToken tokenReward) public auth {
assert(address(CES) == address(0));
assert(tokenReward.owner() == address(this));
assert(tokenReward.authority() == DSAuthority(0));
assert(tokenReward.totalSupply() == 0);
uint128 totalIssue = 1000000000; // 1 billion coin total issue
uint128 coinDisable = 600000000; // 0.6 billion coin for disable
uint128 coinContribute = 200000000; // 0.2 billion coin for contribute
//uint128 coinGiftA = 100000000; // 0.1 billion coin gift for vendue
uint128 coinGiftB = 100000000; // 0.1 billion coin for chain, APP, airdrops
startLine = now;
CES = tokenReward;
CES.mint(totalIssue);
CES.push(0x00, hadd(coinDisable, coinContribute));
CES.push(msg.sender, coinGiftB);
}
function setPrice(uint price_) external auth {
require(!vendueClose);
price = price_;
}
function balanceToken() public view returns (uint256) {
assert(address(CES) != address(0));
return CES.balanceOf(this);
}
function todayDays() public view returns (uint) {
return (div(sub(now, startLine), 1 days) + 1);
}
function () public payable {
require(!vendueClose);
require(iaLeft > 0);
require(msg.value >= price);
require(initAccInfos[msg.sender].ethVendue == 0);
uint money = msg.value;
initAccInfos[msg.sender].ethVendue = money;
totalETH = add(totalETH, money);
iaLeft--;
// release period is 7 day
// elf gift at first month
uint dayNow = todayDays();
if(dayNow <= (30 + 7)) {
elfInfos[msg.sender].bGetElf = true;
}
uint coinNeed;
uint giftLeft = balanceToken();
// coin gift by initialize account
if(dayNow <= (90 + 7)) {
if(giftLeft >= 3500) {
coinNeed = 3500;
}
}
else {
if(giftLeft >= 2000) {
coinNeed = 2000;
}
}
// coin gift by overflow ETH
if(money > price) {
uint multiple = div(sub(money, price), 1 ether);
uint moreGift = mul(multiple, 800);
if(moreGift > 0 && (sub(giftLeft, coinNeed) >= moreGift)) {
coinNeed = add(coinNeed, moreGift);
}
}
if(coinNeed > 0) {
CES.transfer(msg.sender, coinNeed);
}
pushAddr(msg.sender);
emit LogFund(msg.sender, money, true, coinNeed);
}
function withdrawal() external auth {
uint takeNow = sub(address(this).balance, 1 finney);
if(takeNow > 0) {
if (msg.sender.send(takeNow)) {
emit LogFund(msg.sender, takeNow, false, 0);
}
}
}
function vendueClosed() external auth {
vendueClose = true;
distillGodOwner();
}
function freezeToken() external auth {
require(vendueClose);
tokenFreeze = true;
CES.stop();
emit LogFreeze();
}
function distillGodOwner() public auth {
require(vendueClose);
uint ethHighest = 0;
address addrHighest = address(0);
address addr;
for(uint i = 0; i < addrLists.length; i++) {
addr = addrLists[i];
if(address(addr) == address(0)) {
continue;
}
if(initAccInfos[addr].ethVendue > ethHighest) {
ethHighest = initAccInfos[addr].ethVendue;
addrHighest = addr;
}
}
godOwner = addrHighest;
}
function pushAddr(address dst) internal {
bool bExist = false;
address addr;
for(uint i = 0; i < addrLists.length; i++) {
addr = addrLists[i];
if(address(addr) == address(dst)) {
bExist = true;
break;
}
}
if(!bExist)
{
addrLists.push(dst);
}
}
// Do this after we provide elf type to you select
function selectElf(uint8 elfSex, uint16 elfType) external {
require(elfInfos[msg.sender].bGetElf);
elfInfos[msg.sender].elfSex = elfSex;
elfInfos[msg.sender].elfType = elfType;
emit LogElf(msg.sender, elfSex, elfType);
}
// Do this after we provide god to you select
function selectGod(uint16 godID_) external {
require(vendueClose);
require(msg.sender == godOwner);
godID = godID_;
emit LogGod(godOwner, godID);
}
// Do this after we provide tool to produce public key and encrypt your password
function regInitAccount(string account, string publicKey, string pinblock) external {
require(initAccInfos[msg.sender].ethVendue > 0);
assert(bytes(account).length <= 10 && bytes(account).length >= 2);
assert(bytes(publicKey).length <= 128); //maybe public key is 64 bytes
assert(bytes(pinblock).length == 16 || bytes(pinblock).length == 32);
initAccInfos[msg.sender].accountName = account;
initAccInfos[msg.sender].publicKey = publicKey;
initAccInfos[msg.sender].pinblock = pinblock;
emit LogInitAcc(msg.sender, account, publicKey, pinblock);
}
// register your account then tell me your public key for transform token to coin
// init account don't need to do this
function register(string publicKey) external {
require(tokenFreeze);
assert(bytes(publicKey).length <= 128); //maybe public key is 64 bytes
commonAccs[msg.sender] = publicKey;
uint token = CES.balanceOf(msg.sender);
emit LogRegister(msg.sender, publicKey, token);
}
}
|
uint128 coinGiftA = 100000000; 0.1 billion coin gift for vendue
|
function initialize(DSToken tokenReward) public auth {
assert(address(CES) == address(0));
assert(tokenReward.owner() == address(this));
assert(tokenReward.authority() == DSAuthority(0));
assert(tokenReward.totalSupply() == 0);
startLine = now;
CES = tokenReward;
CES.mint(totalIssue);
CES.push(0x00, hadd(coinDisable, coinContribute));
CES.push(msg.sender, coinGiftB);
}
| 12,546,205
|
// @author Unstoppable Domains, Inc.
// @date June 16th, 2021
pragma solidity ^0.8.0;
import '@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol';
import '@chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol';
import '../cns/IResolver.sol';
import '../utils/ERC677Receiver.sol';
import '../roles/WhitelistedRole.sol';
import '../roles/CapperRole.sol';
import '../IUNSRegistry.sol';
contract TwitterValidationOperator is WhitelistedRole, CapperRole, ERC677Receiver {
using SafeMathUpgradeable for uint256;
string public constant NAME = 'UNS: Chainlink Twitter Validation Operator';
string public constant VERSION = '0.1.0';
event Validation(uint256 indexed tokenId, uint256 requestId, uint256 paymentAmount);
event ValidationRequest(uint256 indexed tokenId, address indexed owner, uint256 requestId, string code);
event PaymentSet(uint256 operatorPaymentPerValidation, uint256 userPaymentPerValidation);
uint256 public operatorPaymentPerValidation;
uint256 public userPaymentPerValidation;
uint256 public withdrawableTokens;
uint256 private _frozenTokens;
uint256 private _lastRequestId = 1;
mapping(uint256 => uint256) private _userRequests;
IUNSRegistry private _unsRegistry;
IUNSRegistry private _cnsRegistry;
LinkTokenInterface private _linkToken;
/**
* @notice Deploy with the address of the LINK token, domains registry and payment amount in LINK for one valiation
* @dev Sets the LinkToken address, Registry address and payment in LINK tokens for one validation
* @param unsRegistry The address of the UNS Registry
* @param cnsRegistry The address of the CNS Registry
* @param linkToken The address of the LINK token
* @param paymentCappers Addresses allowed to update payment amount per validation
*/
constructor(
IUNSRegistry unsRegistry,
IUNSRegistry cnsRegistry,
LinkTokenInterface linkToken,
address[] memory paymentCappers
) {
require(address(unsRegistry) != address(0), 'TwitterValidationOperator: UNS_REGISTRY_IS_EMPTY');
require(address(cnsRegistry) != address(0), 'TwitterValidationOperator: CNS_REGISTRY_IS_EMPTY');
require(address(linkToken) != address(0), 'TwitterValidationOperator: INVALID_LINK_TOKEN_ADDRESS');
require(paymentCappers.length > 0, 'TwitterValidationOperator: NO_CAPPERS_PROVIDED');
_unsRegistry = unsRegistry;
_cnsRegistry = cnsRegistry;
_linkToken = linkToken;
__WhitelistedRole_init_unchained();
for (uint256 i = 0; i < paymentCappers.length; i++) {
_addCapper(paymentCappers[i]);
}
}
/**
* @dev Reverts if amount requested is greater than withdrawable balance
* @param amount The given amount to compare to `withdrawableTokens`
*/
modifier hasAvailableFunds(uint256 amount) {
require(withdrawableTokens >= amount, 'TwitterValidationOperator: TOO_MANY_TOKENS_REQUESTED');
_;
}
/**
* @dev Reverts if contract doesn not have enough LINK tokens to fulfil validation
*/
modifier hasAvailableBalance() {
require(
availableBalance() >= withdrawableTokens.add(operatorPaymentPerValidation),
'TwitterValidationOperator: NOT_ENOUGH_TOKENS_ON_CONTRACT_BALANCE'
);
_;
}
/**
* @dev Reverts if method called not from LINK token contract
*/
modifier linkTokenOnly() {
require(_msgSender() == address(_linkToken), 'TwitterValidationOperator: CAN_CALL_FROM_LINK_TOKEN_ONLY');
_;
}
/**
* @dev Reverts if user sent incorrect amount of LINK tokens
*/
modifier correctTokensAmount(uint256 value) {
require(value == userPaymentPerValidation, 'TwitterValidationOperator: INCORRECT_TOKENS_AMOUNT');
_;
}
/**
* @notice Method will be called by Chainlink node in the end of the job. Provides user twitter name and validation signature
* @dev Sets twitter username and signature to .crypto domain records
* @param username Twitter username
* @param signature Signed twitter username. Ensures the validity of twitter username
* @param tokenId Domain token ID
* @param requestId Request id for validations were requested from Smart Contract. If validation was requested from operator `_requestId` should be equals to zero.
*/
function setValidation(
string calldata username,
string calldata signature,
uint256 tokenId,
uint256 requestId
) external onlyWhitelisted hasAvailableBalance {
uint256 payment = _calculatePaymentForValidation(requestId);
withdrawableTokens = withdrawableTokens.add(payment);
IUNSRegistry registry = _getRegistry(tokenId);
IResolver resolver = IResolver(registry.resolverOf(tokenId));
require(address(resolver) != address(0), 'TwitterValidationOperator: RESOLVER_IS_EMPTY');
resolver.set('social.twitter.username', username, tokenId);
resolver.set('validation.social.twitter.username', signature, tokenId);
emit Validation(tokenId, requestId, payment);
}
/**
* @notice Method returns true if Node Operator able to set validation
* @dev Returns true or error
*/
function canSetValidation() external view onlyWhitelisted hasAvailableBalance returns (bool) {
return true;
}
/**
* @notice Method allows to update payments per one validation in LINK tokens
* @dev Sets operatorPaymentPerValidation and userPaymentPerValidation variables
* @param operatorPaymentPerValidation_ Payment amount in LINK tokens when verification initiated via Operator
* @param userPaymentPerValidation_ Payment amount in LINK tokens when verification initiated directly by user via Smart Contract call
*/
function setPaymentPerValidation(uint256 operatorPaymentPerValidation_, uint256 userPaymentPerValidation_)
external
onlyCapper
{
operatorPaymentPerValidation = operatorPaymentPerValidation_;
userPaymentPerValidation = userPaymentPerValidation_;
emit PaymentSet(operatorPaymentPerValidation, userPaymentPerValidation);
}
/**
* @notice Allows the node operator to withdraw earned LINK to a given address
* @dev The owner of the contract can be another wallet and does not have to be a Chainlink node
* @param recipient The address to send the LINK token to
* @param amount The amount to send (specified in wei)
*/
function withdraw(address recipient, uint256 amount) external onlyWhitelistAdmin hasAvailableFunds(amount) {
withdrawableTokens = withdrawableTokens.sub(amount);
assert(_linkToken.transfer(recipient, amount));
}
/**
* @notice Initiate Twitter validation
* @dev Method invoked when LINK tokens transferred via transferAndCall method. Requires additional encoded data
* @param sender Original token sender
* @param value Tokens amount
* @param data Encoded additional data needed to initiate domain verification: `abi.encode(uint256 tokenId, string code)`
*/
function onTokenTransfer(
address sender,
uint256 value,
bytes calldata data
) external override linkTokenOnly correctTokensAmount(value) {
(uint256 tokenId, string memory code) = abi.decode(data, (uint256, string));
IUNSRegistry registry = _getRegistry(tokenId);
require(
registry.isApprovedOrOwner(sender, tokenId),
'TwitterValidationOperator: SENDER_DOES_NOT_HAVE_ACCESS_TO_DOMAIN'
);
require(bytes(code).length > 0, 'TwitterValidationOperator: CODE_IS_EMPTY');
require(
registry.isApprovedOrOwner(address(this), tokenId),
'TwitterValidationOperator: OPERATOR_SHOULD_BE_APPROVED'
);
_frozenTokens = _frozenTokens.add(value);
_userRequests[_lastRequestId] = value;
emit ValidationRequest(tokenId, registry.ownerOf(tokenId), _lastRequestId, code);
_lastRequestId = _lastRequestId.add(1);
}
/**
* @notice Method returns available LINK tokens balance minus held tokens
* @dev Returns tokens amount
*/
function availableBalance() public view returns (uint256) {
return _linkToken.balanceOf(address(this)).sub(_frozenTokens);
}
function _calculatePaymentForValidation(uint256 requestId) private returns (uint256 paymentPerValidation) {
if (requestId > 0) {
// Validation was requested from Smart Contract. We need to search for price in mapping
paymentPerValidation = _userRequests[requestId];
_frozenTokens = _frozenTokens.sub(paymentPerValidation);
delete _userRequests[requestId];
} else {
paymentPerValidation = operatorPaymentPerValidation;
}
}
function _getRegistry(uint256 tokenId) private view returns (IUNSRegistry) {
if (_unsRegistry.exists(tokenId)) {
return _unsRegistry;
} else if (_cnsOwnerOf(tokenId) != address(0x0)) {
return _cnsRegistry;
}
revert('TwitterValidationOperator: TOKEN_NOT_FOUND');
}
function _cnsOwnerOf(uint256 tokenId) private view returns (address) {
try _cnsRegistry.ownerOf(tokenId) returns (address owner) {
return owner;
} catch {
return address(0x0);
}
}
}
|
Validation was requested from Smart Contract. We need to search for price in mapping
|
function _calculatePaymentForValidation(uint256 requestId) private returns (uint256 paymentPerValidation) {
if (requestId > 0) {
paymentPerValidation = _userRequests[requestId];
_frozenTokens = _frozenTokens.sub(paymentPerValidation);
delete _userRequests[requestId];
paymentPerValidation = operatorPaymentPerValidation;
}
}
| 6,437,565
|
// Sources flattened with hardhat v2.0.11 https://hardhat.org
// SPDX-License-Identifier: MIT
// File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.1.0
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/tacoswapv2/interfaces/ITacoswapV2Pair.sol
pragma solidity >=0.5.0;
interface ITacoswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File contracts/tacoswapv2/interfaces/ITacoswapV2Factory.sol
pragma solidity >=0.5.0;
interface ITacoswapV2Factory {
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setMigrator(address) external;
}
// File contracts/interfaces/IMasterChef.sol
pragma solidity 0.8.0;
interface IMasterChef {
function deposit(uint256, uint256) external;
function harvest(uint256) external;
function poolLength() external returns (uint256);
function userInfo(uint256, address) external returns(uint256, uint256);
function totalAllocPoint() external view returns(uint256);
function poolInfo(uint256) external returns(address, uint256, uint256, uint256);
function setMigrator(address) external;
function migrate(uint256) external;
function massUpdatePools() external;
}
// File contracts/interfaces/IETacoChef.sol
pragma solidity 0.8.0;
interface IETacoChef {
function poolLength() external view returns (uint256);
function startBlock() external view returns (uint256);
function approveDummies(address) external;
function getrewardForBlock(uint256) external view returns (uint256);
function getReward(uint256, uint256) external view returns (uint256);
function poolInfo(uint256)
external
view
returns (
address,
uint256,
uint256,
uint256
);
function userInfo(uint256, uint256)
external
view
returns (uint256, uint256);
function pendingeTaco(uint256, address) external view returns (uint256);
function speedStake(
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
) external payable returns (uint256);
function totalAllocPoint() external view returns (uint256);
function deposit(uint256, uint256) external;
function setPool(
uint256,
address,
uint256,
uint256,
uint256
) external;
function setUser(
uint256,
address,
uint256,
uint256
) external;
}
// File @openzeppelin/contracts/utils/Context.sol@v4.1.0
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/Ownable.sol@v4.1.0
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol@v4.1.0
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File @openzeppelin/contracts/token/ERC20/ERC20.sol@v4.1.0
pragma solidity ^0.8.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, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `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 += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File hardhat/console.sol@v2.0.11
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// File contracts/DummyToken.sol
pragma solidity ^0.8.0;
/**
*@title DummyToken contract
* @dev It is deployed only when the Migrate function is called.
* Owner of DummyToken contract is MIgrator contract.
**/
contract DummyToken is ERC20("Dummy.Token", "DMT"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
// File contracts/MigratorDummy.sol
pragma solidity 0.8.0;
/**
*@title Migrator contract
* - Users can:
* #Migrate` migrates LP tokens from TacoChef to eTacoChef
* #migrateUserInfo
* - only owner can
* #MigratePools
**/
contract MigratorDummy is Ownable {
IMasterChef public oldChef;
IETacoChef public newChef;
uint256 public desiredLiquidity = type(uint256).max;
mapping(address => address) public lpTokenToDummyToken;
mapping(address => bool) public isMigrated;
/**
* @param _oldChef The address of TacoChef contract.
* @param _newChef The address of eTacoChef.
**/
constructor(
address _oldChef,
address _newChef
) {
require(_oldChef != address(0x0), "Migrator::set zero address");
require(_newChef != address(0x0), "Migrator::set zero address");
oldChef = IMasterChef(_oldChef);
newChef = IETacoChef(_newChef);
}
/**
* @dev Migrates pools which pids are given in array(pools).
* Can be called one time, when eTacoChef poolInfo is empty.
* @param oldPools Array which contains old master pids that must be migrated.
* @param newPools Array which contains new master pids that must be migrated.
**/
function migratePools(uint256[] memory oldPools, uint256[] memory newPools) external onlyOwner {
uint256 poolsLength = oldPools.length;
for (uint256 i = 0; i < poolsLength; i++) {
(address lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 accTacoPerShare) =
oldChef.poolInfo(oldPools[i]);
ITacoswapV2Pair lp = ITacoswapV2Pair(lpToken);
DummyToken dummyToken = new DummyToken();
dummyToken.mint(address(newChef), lp.balanceOf(address(oldChef)));
dummyToken.mint(msg.sender, 1e21);
lpTokenToDummyToken[lpToken] = address(dummyToken);
newChef.setPool(
newPools[i],
address(dummyToken),
allocPoint,
lastRewardBlock,
accTacoPerShare
);
}
}
/**
* @dev Migrates UserInfo from TacoChef to eTacoChef
* Can be called by user one time and required to call deposit function
* with amount = 0, for all pools where the user have some amount before migration.
**/
function migrateUserInfo() external onlyOwner {
require(!isMigrated[msg.sender], "Migrator: Already migrated");
for (uint256 i = 0; i < 17; i++) {
(uint256 amount, uint256 rewardDebt) = oldChef.userInfo(i, msg.sender);
if (amount == 0) continue;
newChef.setUser(i, msg.sender, amount, rewardDebt);
}
isMigrated[msg.sender] = true;
}
/**
* @dev Migrates LP tokens from TacoChef to eTacoChef.
* Deploy DummyToken. Mint DummyToken with the same amount of LP tokens.
* DummyToken is neaded to pass require in TacoChef contracts migrate function.
**/
function migrate(ITacoswapV2Pair orig) public onlyOwner returns (IERC20) {
// Transfer all LP tokens from oldMaster to newMaster
// Deploy dummy token
// Mint same amount of dummy token for oldMaster
require(
msg.sender == address(oldChef),
"Migrator: not from old master chef"
);
DummyToken dummyToken = new DummyToken();
uint256 lp = orig.balanceOf(msg.sender);
if (lp == 0) return dummyToken;
desiredLiquidity = lp;
orig.transferFrom(msg.sender, address(newChef), lp);
dummyToken.mint(msg.sender, lp);
desiredLiquidity = type(uint256).max;
return dummyToken;
}
}
// File contracts/MigratorFull.sol
pragma solidity 0.8.0;
/**
*@title MigratorFull contract
* - Users can:
* #Migrate` migrates LP tokens from TacoChef to eTacoChef
* #migrateUserInfo
* - only owner can
* #MigratePools
**/
contract MigratorFull {
IMasterChef public oldChef;
IETacoChef public newChef;
MigratorDummy public dummyMigrator;
address public uniFactory;
address public sushiFactory;
ITacoswapV2Factory public factory;
IERC20 private _taco;
IERC20 private _etaco;
mapping(address => bool) public isMigrated;
/**
* @param _oldChef The address of TacoChef contract.
* @param _newChef The address of eTacoChef.
* @param _dummyMigrator The address of MigratorDummy.
* @param _uniFactory The address of UniSwapV2Factory.
* @param _sushiFactory The address of SushiSwapFactory.
* @param _factory The address of TacoSwapFactory.
* @param tacoToken_ The address of TacoToken
* @param etaco_ The address of eTacoToken
**/
constructor(
address _oldChef,
address _newChef,
address _dummyMigrator,
address _uniFactory,
address _sushiFactory,
address _factory,
address tacoToken_,
address etaco_
) {
require(_oldChef != address(0x0), "Migrator::set zero address");
require(_dummyMigrator != address(0x0), "Migrator::set zero address");
require(_newChef != address(0x0), "Migrator::set zero address");
require(_uniFactory != address(0x0), "Migrator::set zero address");
require(_sushiFactory != address(0x0), "Migrator::set zero address");
require(tacoToken_ != address(0x0), "TacoToETaco::set zero address");
require(etaco_ != address(0x0), "TacoToETaco::set zero address");
_taco = IERC20(tacoToken_);
_etaco = IERC20(etaco_);
uniFactory = _uniFactory;
sushiFactory = _sushiFactory;
oldChef = IMasterChef(_oldChef);
newChef = IETacoChef(_newChef);
dummyMigrator = MigratorDummy(_dummyMigrator);
factory = ITacoswapV2Factory(_factory);
}
/**
* @dev Migrates LP tokens from TacoChef to eTacoChef.
* DummyToken is neaded to pass require in TacoChef contracts migrate function.
**/
function migrate(ITacoswapV2Pair orig) public returns (IERC20) {
require(
msg.sender == address(oldChef),
"Migrator: not from old master chef"
);
uint256 lp = orig.balanceOf(msg.sender);
IERC20 dummyToken = IERC20(dummyMigrator.lpTokenToDummyToken(address(orig)));
newChef.approveDummies(address(dummyToken));
orig.transferFrom(msg.sender, address(newChef), lp);
dummyToken.transferFrom(address(newChef), address(oldChef), lp);
return dummyToken;
}
function migrateLP(ITacoswapV2Pair orig) public returns (ITacoswapV2Pair) {
require(msg.sender == address(newChef), "not from master chef");
require(
orig.factory() == uniFactory || orig.factory() == sushiFactory,
"Migrator: not from old factory"
);
address token0 = orig.token0();
address token1 = orig.token1();
ITacoswapV2Pair pair = ITacoswapV2Pair(factory.getPair(token0, token1));
if (pair == ITacoswapV2Pair(address(0))) {
pair = ITacoswapV2Pair(factory.createPair(token0, token1));
}
uint256 lp = orig.balanceOf(msg.sender);
if (lp == 0) return pair;
orig.transferFrom(msg.sender, address(orig), lp);
orig.burn(address(pair));
pair.mint(msg.sender);
return pair;
}
/**
* @dev Migrates UserInfo from TacoChef to eTacoChef.
* Can be called by user one time only.
**/
function migrateUserInfo() external {
require(!isMigrated[msg.sender], "Migrator: Already migrated");
uint256 oldPoolLength = oldChef.poolLength();
for (uint256 i = 0; i < oldPoolLength; i++) {
(uint256 amount, uint256 rewardDebt) = oldChef.userInfo(i, msg.sender);
if (amount == 0) continue;
newChef.setUser(i, msg.sender, amount, rewardDebt);
}
swap();
isMigrated[msg.sender] = true;
}
/**
* @dev Migrates UserInfo from TacoChef to eTacoChef.
* Can be called by user one time and required to call deposit function.
**/
function swap() public {
uint256 _amount = _taco.balanceOf(msg.sender);
_taco.transferFrom(msg.sender, address(this), _amount);
_etaco.transfer(msg.sender, _amount);
}
}
|
Migrates UserInfo from TacoChef to eTacoChef. Can be called by user one time and required to call deposit function./
|
function swap() public {
uint256 _amount = _taco.balanceOf(msg.sender);
_taco.transferFrom(msg.sender, address(this), _amount);
_etaco.transfer(msg.sender, _amount);
}
| 5,511,346
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../interfaces/IFlashloan.sol";
import "../dodo/IDODO.sol";
import "../libraries/RouteUtils.sol";
contract DodoBase is IFlashloan {
//Note: CallBack function executed by DODOV2(DVM) flashLoan pool
function DVMFlashLoanCall(
address sender,
uint256 baseAmount,
uint256 quoteAmount,
bytes calldata data
) external {
_flashLoanCallBack(sender, baseAmount, quoteAmount, data);
}
//Note: CallBack function executed by DODOV2(DPP) flashLoan pool
function DPPFlashLoanCall(
address sender,
uint256 baseAmount,
uint256 quoteAmount,
bytes calldata data
) external {
_flashLoanCallBack(sender, baseAmount, quoteAmount, data);
}
//Note: CallBack function executed by DODOV2(DSP) flashLoan pool
function DSPFlashLoanCall(
address sender,
uint256 baseAmount,
uint256 quoteAmount,
bytes calldata data
) external {
_flashLoanCallBack(sender, baseAmount, quoteAmount, data);
}
function _flashLoanCallBack(
address,
uint256,
uint256,
bytes calldata data
) internal virtual {}
modifier checkParams(FlashParams memory params) {
address loanToken = RouteUtils.getInitialToken(params.routes[0]);
bool loanEqBase = loanToken ==
IDODO(params.flashLoanPool)._BASE_TOKEN_();
bool loanEqQuote = loanToken ==
IDODO(params.flashLoanPool)._QUOTE_TOKEN_();
require(loanEqBase || loanEqQuote, "Wrong flashloan pool address");
_;
}
}
|
Note: CallBack function executed by DODOV2(DSP) flashLoan pool
|
function DSPFlashLoanCall(
address sender,
uint256 baseAmount,
uint256 quoteAmount,
bytes calldata data
) external {
_flashLoanCallBack(sender, baseAmount, quoteAmount, data);
}
| 2,523,749
|
pragma solidity 0.6.12;
import "./libs/SafeMath.sol";
import "./interfaces/IBEP20.sol";
import "./libs/Address.sol";
import "./libs/SafeBEP20.sol";
/**
* @title SafeBEP20
* @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
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 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 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 SmartChef is Ownable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
// Info of each pool.
struct PoolInfo {
IBEP20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. BSWs to distribute per block.
uint256 lastRewardBlock; // Last block number that BSWs distribution occurs.
uint256 accBSWPerShare; // Accumulated BSWs per share, times PRECISION_FACTOR. See below.
}
// The BSW TOKEN!
IBEP20 public biswap;
IBEP20 public rewardToken;
// BSW tokens created per block.
uint256 public rewardPerBlock;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (address => UserInfo) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when BSW mining starts.
uint256 public startBlock;
// The block number when BSW mining ends.
uint256 public bonusEndBlock;
// limit 100 BSW
uint256 public limitAmount = 100000000000000000000;
// The precision factor
uint256 public PRECISION_FACTOR;
event Deposit(address indexed user, uint256 amount);
event Withdraw(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event RefPercentChanged(uint256 currentPercent);
constructor(
IBEP20 _bsw,
IBEP20 _rewardToken,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
biswap = _bsw;
rewardToken = _rewardToken;
rewardPerBlock = _rewardPerBlock;
startBlock = _startBlock;
bonusEndBlock = _bonusEndBlock;
uint256 decimalsRewardToken = uint256(rewardToken.decimals());
require(decimalsRewardToken < 30, "Must be inferior to 30");
PRECISION_FACTOR = uint256(10**(uint256(30).sub(decimalsRewardToken)));
// staking pool
poolInfo.push(PoolInfo({
lpToken: _bsw,
allocPoint: 1000,
lastRewardBlock: startBlock,
accBSWPerShare: 0
}));
totalAllocPoint = 1000;
}
// Set the limit amount.
function setLimitAmount(uint256 _amount) public onlyOwner {
limitAmount = _amount;
}
// Return remaining limit amount
function remainingLimitAmount() public view returns(uint256) {
if (userInfo[msg.sender].amount >= limitAmount){
return 0;
}
return limitAmount.sub(userInfo[msg.sender].amount);
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from);
} else if (_from >= bonusEndBlock) {
return 0;
} else {
return bonusEndBlock.sub(_from);
}
}
// View function to see pending Reward on frontend.
function pendingReward(address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[_user];
uint256 accBSWPerShare = pool.accBSWPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 BSWReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accBSWPerShare = accBSWPerShare.add(BSWReward.mul(PRECISION_FACTOR).div(lpSupply));
}
return user.amount.mul(accBSWPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 BSWReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accBSWPerShare = pool.accBSWPerShare.add(BSWReward.mul(PRECISION_FACTOR).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// 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);
}
}
// Stake biswap tokens to SmartChef
function deposit(uint256 _amount) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[msg.sender];
require(user.amount.add(_amount) <= limitAmount, 'Exceed limit amount');
updatePool(0);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accBSWPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt);
if(pending > 0) {
rewardToken.safeTransfer(address(msg.sender), pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accBSWPerShare).div(PRECISION_FACTOR);
emit Deposit(msg.sender, _amount);
}
// Withdraw biswap tokens from STAKING.
function withdraw(uint256 _amount) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(0);
uint256 pending = user.amount.mul(pool.accBSWPerShare).div(PRECISION_FACTOR).sub(user.rewardDebt);
if(pending > 0) {
rewardToken.safeTransfer(address(msg.sender), pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accBSWPerShare).div(PRECISION_FACTOR);
emit Withdraw(msg.sender, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw() public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[msg.sender];
uint256 amountToTransfer = user.amount;
user.amount = 0;
user.rewardDebt = 0;
if (amountToTransfer > 0){
pool.lpToken.safeTransfer(address(msg.sender), amountToTransfer);
}
emit EmergencyWithdraw(msg.sender, amountToTransfer);
}
// Withdraw reward. EMERGENCY ONLY.
function emergencyRewardWithdraw(uint256 _amount) public onlyOwner {
require(_amount <= rewardToken.balanceOf(address(this)), 'not enough token');
rewardToken.safeTransfer(address(msg.sender), _amount);
}
}
|
Withdraw without caring about rewards. EMERGENCY ONLY.
|
function emergencyWithdraw() public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[msg.sender];
uint256 amountToTransfer = user.amount;
user.amount = 0;
user.rewardDebt = 0;
if (amountToTransfer > 0){
pool.lpToken.safeTransfer(address(msg.sender), amountToTransfer);
}
emit EmergencyWithdraw(msg.sender, amountToTransfer);
}
| 5,436,926
|
pragma solidity ^0.7.4;
//"SPDX-License-Identifier: UNLICENSED"
import "./Vote.sol";
contract VoteFactory{
// Representation of an instance of Group
struct groupStruct {
string name;
string description;
address[] members;
// uint groupID;
}
// Representation of an instance of User
struct userStruct {
address userAddress;
string name;
string email;
uint256 studentID;
string password;
uint32[] groups;
bool isAdmin;
bool isLogin;
}
mapping(uint => groupStruct) public groupInfo; // KEY: groupID Value: group
uint32 groupCount;
address[] public deployedVotes;
mapping(address => userStruct) userInfo;
uint32 defaultGroupID = 0; // Use the getGroup(uint id) to access the default group
uint32[] public existingGroups; // Access all groups in the UI
// GROUP
// UPDATED Creates an instance of group and Updates the groupInfo mapping
// The Group ID is based on the number of existing groups (generated)
function createGroup(string memory name, string memory description) public {
userStruct storage u = userInfo[msg.sender];
groupStruct storage g = groupInfo[groupCount];
require(!compareStrings(groupInfo[0].name, ""));
g.name = name;
g.description = description;
existingGroups.push(groupCount);
// Add Current User to the Group
u.groups.push(groupCount++);
g.members.push(u.userAddress);
}
// UPDATED Adds the groupID to the user's array of groups and Adds the user's address to the group's array of members
function registerGroup(uint32 groupID) public {
userStruct storage u = userInfo[msg.sender];
groupStruct storage g = groupInfo[groupID];
require(groupID != 0);
require(!compareStrings(g.name, "")); // Validates the group's existence
// require(!isUserGroup(u.userAddress, groupID));
// Update User
u.groups.push(groupID);
// Update Group
g.members.push(u.userAddress);
}
// Removes the groupID in the user's groups array and Removes the address in the group's member array
// using the Swap & Delete method (swaps the last element)
// Resources https://stackoverflow.com/questions/49051856/is-there-a-pop-functionality-for-solidity-arrays
// The inputs are very specific to prevent large computations (TO CHANGE DEPENDING ON PROJECT MANAGER'S CHOICE)
function leaveGroup(uint32 indexGroup, uint32 indexMember, uint32 groupID) public {
userStruct storage u = userInfo[msg.sender];
groupStruct storage g = groupInfo[groupID];
// Remove the group from user
u.groups[indexGroup] = u.groups[u.groups.length - 1];
delete u.groups[u.groups.length - 1];
u.groups.pop();
// Remove user from the group
g.members[indexMember] = g.members[g.members.length - 1];
delete g.members[g.members.length - 1];
g.members.pop();
}
// USER
// UPDATED Registers the user and add the user to the default group
function registerUser(string memory name, string memory email, uint256 studentID, string memory password) public {
userStruct storage u = userInfo[msg.sender]; //innitialize
groupStruct storage studentGroup = groupInfo[defaultGroupID];
if (!isGroup(0)) {
studentGroup.name = "Student";
studentGroup.description = "Default Group";
existingGroups.push(groupCount++);
}
require(compareStrings(u.name, ""));
//require(!compareStrings(groupInfo[0].name, ""));
u.name = name;
u.email = email;
u.studentID = studentID;
u.password = password;
u.userAddress = msg.sender;
u.isAdmin = true;
u.isLogin = false;
// Join the default group
u.groups.push(defaultGroupID);
studentGroup.members.push(u.userAddress);
}
// UPDATED Logins the user
function loginUser(uint256 studentID, string memory password) public returns (string memory, string memory, uint32[] memory, bool) { // add username
userStruct storage u = userInfo[msg.sender];
require(studentID == u.studentID);
require(compareStrings(password, u.password)); // NEW implemented the helper method
require(!u.isLogin);
u.isLogin = true;
return(u.name, u.email, u.groups, u.isAdmin);
}
// NEW logout the user from the system
function logoutUser() public {
userStruct storage u = userInfo[msg.sender];
require(u.isLogin);
u.isLogin = false;
}
// Creates a new Vote
function createVote(uint typeOf) public{
address newVote = address(new Vote(msg.sender, typeOf));
deployedVotes.push(newVote);
}
/**
* OTHER METHODS
*/
// Verify that the user is logged in
function isUserLoggedIn(address currentUser) public view returns (bool) {
userStruct storage u = userInfo[currentUser];
return u.isLogin;
}
// Verify if the user is part of the group
function isUserGroup(address currentUser, uint32 groupID) public view returns (bool) {
bool isStatus = false;
userStruct storage u = userInfo[currentUser];
for (uint i = 0; i < u.groups.length; i++) {
if (u.groups[i] == groupID) {
isStatus = true;
break;
}
}
return isStatus;
}
// Verify that the group exists in the mapping
function isGroup(uint32 groupID) public view returns (bool) {
groupStruct storage g = groupInfo[groupID];
bool isExist = !(compareStrings(g.name, ""));
return isExist;
}
// Returns a specific group of the user
function getUserGroup(address currentUser, uint32 index) public view returns (uint32) {
userStruct storage u = userInfo[currentUser];
return u.groups[index];
}
// Returns the user's array of groups
function getUserAllGroups(address currentUser) public view returns (uint32[] memory) {
userStruct storage u = userInfo[currentUser];
return u.groups;
}
// Returns a specific group of the website
function getGroup(uint8 id) public view returns(string memory aName, string memory aDescription, address[] memory aMembers, uint aMembersLength) {
groupStruct storage g = groupInfo[id];
return (g.name, g.description, g.members, g.members.length); // remove members length
}
function getExistingGroups() public view returns(uint32[] memory) {
return existingGroups;
}
//NEED TO BE FIX (u.groups) FOLLOW VOTE.SOL SYNTAX
function getUser(address currentUser) public view returns (string memory aName, string memory aEmail, uint256 aStudentID, uint32[] memory aGroups, bool aIsAdmin, bool aIsLogin) {
userStruct storage u = userInfo[currentUser];
return(u.name,
u.email,
u.studentID,
u.groups,
u.isAdmin,
u.isLogin);
}
function getDeployedVotes() public view returns (address[] memory) {
return deployedVotes;
}
// Returns a boolean value of the comparison (HELPER METHOD)
// Based on https://ethereum.stackexchange.com/questions/30912/how-to-compare-strings-in-solidity/82739
function compareStrings(string memory a, string memory b) public pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
}
|
Returns a specific group of the website
|
function getGroup(uint8 id) public view returns(string memory aName, string memory aDescription, address[] memory aMembers, uint aMembersLength) {
groupStruct storage g = groupInfo[id];
}
| 12,610,061
|
./full_match/9001/0x110DD7887321f24477BF4A135a1E5eB7Bf31691a/sources/contracts/StreamingBoundHedgeys.sol
|
Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't need to send a transaction, and thus is not required to hold Ether at all./ solhint-disable-next-line func-name-mixedcase
|
interface IERC20Permit {
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
function DOMAIN_SEPARATOR() external view returns (bytes32);
pragma solidity 0.8.17;
}
| 11,531,650
|
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
// Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below).
contract LiquidationWithdrawer {
function withdrawLiquidation(
address financialContractAddress,
uint256 liquidationId,
address sponsor
) public returns (FixedPoint.Unsigned memory) {
return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor);
}
}
interface IFinancialContract {
function withdrawLiquidation(uint256 liquidationId, address sponsor)
external
returns (FixedPoint.Unsigned memory amountWithdrawn);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
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;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/VotingInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data.
abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./Timer.sol";
/**
* @title Base class that provides time overrides, but only if being run in test mode.
*/
abstract contract Testable {
// If the contract is being run on the test network, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) internal {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "./VotingAncillaryInterface.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingInterface {
struct PendingRequest {
bytes32 identifier;
uint256 time;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct Commitment {
bytes32 identifier;
uint256 time;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct Reveal {
bytes32 identifier;
uint256 time;
int256 price;
int256 salt;
}
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(Commitment[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(Reveal[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
virtual
returns (VotingAncillaryInterface.PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Universal store of current contract time for testing environments.
*/
contract Timer {
uint256 private currentTime;
constructor() public {
currentTime = now; // solhint-disable-line not-rely-on-time
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingAncillaryInterface {
struct PendingRequestAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct CommitmentAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct RevealAncillary {
bytes32 identifier;
uint256 time;
int256 price;
bytes ancillaryData;
int256 salt;
}
// Note: the phases must be in order. Meaning the first enum value must be the first phase, etc.
// `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last.
enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER }
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "./Registry.sol";
import "./ResultComputation.sol";
import "./VoteTiming.sol";
import "./VotingToken.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
/**
* @title Voting system for Oracle.
* @dev Handles receiving and resolving price requests via a commit-reveal voting scheme.
*/
contract Voting is
Testable,
Ownable,
OracleInterface,
OracleAncillaryInterface, // Interface to support ancillary data with price requests.
VotingInterface,
VotingAncillaryInterface // Interface to support ancillary data with voting rounds.
{
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using VoteTiming for VoteTiming.Data;
using ResultComputation for ResultComputation.Data;
/****************************************
* VOTING DATA STRUCTURES *
****************************************/
// Identifies a unique price request for which the Oracle will always return the same value.
// Tracks ongoing votes as well as the result of the vote.
struct PriceRequest {
bytes32 identifier;
uint256 time;
// A map containing all votes for this price in various rounds.
mapping(uint256 => VoteInstance) voteInstances;
// If in the past, this was the voting round where this price was resolved. If current or the upcoming round,
// this is the voting round where this price will be voted on, but not necessarily resolved.
uint256 lastVotingRound;
// The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that
// this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`.
uint256 index;
bytes ancillaryData;
}
struct VoteInstance {
// Maps (voterAddress) to their submission.
mapping(address => VoteSubmission) voteSubmissions;
// The data structure containing the computed voting results.
ResultComputation.Data resultComputation;
}
struct VoteSubmission {
// A bytes32 of `0` indicates no commit or a commit that was already revealed.
bytes32 commit;
// The hash of the value that was revealed.
// Note: this is only used for computation of rewards.
bytes32 revealHash;
}
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
/****************************************
* INTERNAL TRACKING *
****************************************/
// Maps round numbers to the rounds.
mapping(uint256 => Round) public rounds;
// Maps price request IDs to the PriceRequest struct.
mapping(bytes32 => PriceRequest) private priceRequests;
// Price request ids for price requests that haven't yet been marked as resolved.
// These requests may be for future rounds.
bytes32[] internal pendingPriceRequests;
VoteTiming.Data public voteTiming;
// Percentage of the total token supply that must be used in a vote to
// create a valid price resolution. 1 == 100%.
FixedPoint.Unsigned public gatPercentage;
// Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that
// should be split among the correct voters.
// Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%.
FixedPoint.Unsigned public inflationRate;
// Time in seconds from the end of the round in which a price request is
// resolved that voters can still claim their rewards.
uint256 public rewardsExpirationTimeout;
// Reference to the voting token.
VotingToken public votingToken;
// Reference to the Finder.
FinderInterface private finder;
// If non-zero, this contract has been migrated to this address. All voters and
// financial contracts should query the new address only.
address public migratedAddress;
// Max value of an unsigned integer.
uint256 private constant UINT_MAX = ~uint256(0);
// Max length in bytes of ancillary data that can be appended to a price request.
// As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily
// comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to
// storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function
// well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here:
// - https://etherscan.io/chart/gaslimit
// - https://github.com/djrtwo/evm-opcode-gas-costs
uint256 public constant ancillaryBytesLimit = 8192;
bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot")));
/***************************************
* EVENTS *
****************************************/
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
/**
* @notice Construct the Voting contract.
* @param _phaseLength length of the commit and reveal phases in seconds.
* @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution.
* @param _inflationRate percentage inflation per round used to increase token supply of correct voters.
* @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed.
* @param _votingToken address of the UMA token contract used to commit votes.
* @param _finder keeps track of all contracts within the system based on their interfaceName.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
) public Testable(_timerAddress) {
voteTiming.init(_phaseLength);
require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%");
gatPercentage = _gatPercentage;
inflationRate = _inflationRate;
votingToken = VotingToken(_votingToken);
finder = FinderInterface(_finder);
rewardsExpirationTimeout = _rewardsExpirationTimeout;
}
/***************************************
MODIFIERS
****************************************/
modifier onlyRegisteredContract() {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Caller must be migrated address");
} else {
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
require(registry.isContractRegistered(msg.sender), "Called must be registered");
}
_;
}
modifier onlyIfNotMigrated() {
require(migratedAddress == address(0), "Only call this if not migrated");
_;
}
/****************************************
* PRICE REQUEST AND ACCESS FUNCTIONS *
****************************************/
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported. The length of the ancillary data
* is limited such that this method abides by the EVM transaction gas limit.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override onlyRegisteredContract() {
uint256 blockTime = getCurrentTime();
require(time <= blockTime, "Can only request in past");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData);
PriceRequest storage priceRequest = priceRequests[priceRequestId];
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.NotRequested) {
// Price has never been requested.
// Price requests always go in the next round, so add 1 to the computed current round.
uint256 nextRoundId = currentRoundId.add(1);
priceRequests[priceRequestId] = PriceRequest({
identifier: identifier,
time: time,
lastVotingRound: nextRoundId,
index: pendingPriceRequests.length,
ancillaryData: ancillaryData
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, identifier, time);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function requestPrice(bytes32 identifier, uint256 time) public override {
requestPrice(identifier, time, "");
}
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (bool) {
(bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData);
return _hasPrice;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
return hasPrice(identifier, time, "");
}
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (int256) {
(bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData);
// If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
return getPrice(identifier, time, "");
}
/**
* @notice Gets the status of a list of price requests, identified by their identifier and time.
* @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0.
* @param requests array of type PendingRequest which includes an identifier and timestamp for each request.
* @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests.
*/
function getPriceRequestStatuses(PendingRequestAncillary[] memory requests)
public
view
returns (RequestState[] memory)
{
RequestState[] memory requestStates = new RequestState[](requests.length);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
for (uint256 i = 0; i < requests.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData);
RequestStatus status = _getRequestStatus(priceRequest, currentRoundId);
// If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated.
if (status == RequestStatus.Active) {
requestStates[i].lastVotingRound = currentRoundId;
} else {
requestStates[i].lastVotingRound = priceRequest.lastVotingRound;
}
requestStates[i].status = status;
}
return requestStates;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) {
PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length);
for (uint256 i = 0; i < requests.length; i++) {
requestsAncillary[i].identifier = requests[i].identifier;
requestsAncillary[i].time = requests[i].time;
requestsAncillary[i].ancillaryData = "";
}
return getPriceRequestStatuses(requestsAncillary);
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public override onlyIfNotMigrated() {
require(hash != bytes32(0), "Invalid provided hash");
// Current time is required for all vote timing queries.
uint256 blockTime = getCurrentTime();
require(
voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit,
"Cannot commit in reveal phase"
);
// At this point, the computed and last updated round ID should be equal.
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
require(
_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active,
"Cannot commit inactive request"
);
priceRequest.lastVotingRound = currentRoundId;
VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
voteInstance.voteSubmissions[msg.sender].commit = hash;
emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) public override onlyIfNotMigrated() {
commitVote(identifier, time, "", hash);
}
/**
* @notice Snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times, but only the first call per round into this function or `revealVote`
* will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature)
external
override(VotingInterface, VotingAncillaryInterface)
onlyIfNotMigrated()
{
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase");
// Require public snapshot require signature to ensure caller is an EOA.
require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender");
uint256 roundId = voteTiming.computeCurrentRoundId(blockTime);
_freezeRoundVariables(roundId);
}
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price voted on during the commit phase.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public override onlyIfNotMigrated() {
require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase");
// Note: computing the current round is required to disallow people from revealing an old commit after the round is over.
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// Scoping to get rid of a stack too deep error.
{
// 0 hashes are disallowed in the commit phase, so they indicate a different error.
// Cannot reveal an uncommitted or previously revealed hash
require(voteSubmission.commit != bytes32(0), "Invalid hash reveal");
require(
keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) ==
voteSubmission.commit,
"Revealed data != commit hash"
);
// To protect against flash loans, we require snapshot be validated as EOA.
require(rounds[roundId].snapshotId != 0, "Round has no snapshot");
}
// Get the frozen snapshotId
uint256 snapshotId = rounds[roundId].snapshotId;
delete voteSubmission.commit;
// Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId));
// Set the voter's submission.
voteSubmission.revealHash = keccak256(abi.encode(price));
// Add vote to the results.
voteInstance.resultComputation.addVote(price, balance);
emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public override {
revealVote(identifier, time, price, "", salt);
}
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, ancillaryData, hash);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, "", hash);
commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote);
}
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public override {
for (uint256 i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash);
} else {
commitAndEmitEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].ancillaryData,
commits[i].hash,
commits[i].encryptedVote
);
}
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchCommit(Commitment[] memory commits) public override {
CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length);
for (uint256 i = 0; i < commits.length; i++) {
commitsAncillary[i].identifier = commits[i].identifier;
commitsAncillary[i].time = commits[i].time;
commitsAncillary[i].ancillaryData = "";
commitsAncillary[i].hash = commits[i].hash;
commitsAncillary[i].encryptedVote = commits[i].encryptedVote;
}
batchCommit(commitsAncillary);
}
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more info on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public override {
for (uint256 i = 0; i < reveals.length; i++) {
revealVote(
reveals[i].identifier,
reveals[i].time,
reveals[i].price,
reveals[i].ancillaryData,
reveals[i].salt
);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchReveal(Reveal[] memory reveals) public override {
RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length);
for (uint256 i = 0; i < reveals.length; i++) {
revealsAncillary[i].identifier = reveals[i].identifier;
revealsAncillary[i].time = reveals[i].time;
revealsAncillary[i].price = reveals[i].price;
revealsAncillary[i].ancillaryData = "";
revealsAncillary[i].salt = reveals[i].salt;
}
batchReveal(revealsAncillary);
}
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold
* (not expired). Note that a named return value is used here to avoid a stack to deep error.
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return totalRewardToIssue total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Can only call from migrated");
}
require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId");
Round storage round = rounds[roundId];
bool isExpired = getCurrentTime() > round.rewardsExpirationTime;
FixedPoint.Unsigned memory snapshotBalance =
FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId));
// Compute the total amount of reward that will be issued for each of the votes in the round.
FixedPoint.Unsigned memory snapshotTotalSupply =
FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId));
FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply);
// Keep track of the voter's accumulated token reward.
totalRewardToIssue = FixedPoint.Unsigned(0);
for (uint256 i = 0; i < toRetrieve.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
// Only retrieve rewards for votes resolved in same round
require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round");
_resolvePriceRequest(priceRequest, voteInstance);
if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) {
continue;
} else if (isExpired) {
// Emit a 0 token retrieval on expired rewards.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
} else if (
voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)
) {
// The price was successfully resolved during the voter's last voting round, the voter revealed
// and was correct, so they are eligible for a reward.
// Compute the reward and add to the cumulative reward.
FixedPoint.Unsigned memory reward =
snapshotBalance.mul(totalRewardPerVote).div(
voteInstance.resultComputation.getTotalCorrectlyVotedTokens()
);
totalRewardToIssue = totalRewardToIssue.add(reward);
// Emit reward retrieval for this vote.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
reward.rawValue
);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
}
// Delete the submission to capture any refund and clean up storage.
delete voteInstance.voteSubmissions[voterAddress].revealHash;
}
// Issue any accumulated rewards.
if (totalRewardToIssue.isGreaterThan(0)) {
require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed");
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory) {
PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length);
for (uint256 i = 0; i < toRetrieve.length; i++) {
toRetrieveAncillary[i].identifier = toRetrieve[i].identifier;
toRetrieveAncillary[i].time = toRetrieve[i].time;
toRetrieveAncillary[i].ancillaryData = "";
}
return retrieveRewards(voterAddress, roundId, toRetrieveAncillary);
}
/****************************************
* VOTING GETTER FUNCTIONS *
****************************************/
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests array containing identifiers of type `PendingRequest`.
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
override(VotingInterface, VotingAncillaryInterface)
returns (PendingRequestAncillary[] memory)
{
uint256 blockTime = getCurrentTime();
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter
// `pendingPriceRequests` only to those requests that have an Active RequestStatus.
PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length);
uint256 numUnresolved = 0;
for (uint256 i = 0; i < pendingPriceRequests.length; i++) {
PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]];
if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) {
unresolved[numUnresolved] = PendingRequestAncillary({
identifier: priceRequest.identifier,
time: priceRequest.time,
ancillaryData: priceRequest.ancillaryData
});
numUnresolved++;
}
}
PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved);
for (uint256 i = 0; i < numUnresolved; i++) {
pendingRequests[i] = unresolved[i];
}
return pendingRequests;
}
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) {
return voteTiming.computeCurrentPhase(getCurrentTime());
}
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) {
return voteTiming.computeCurrentRoundId(getCurrentTime());
}
/****************************************
* OWNER ADMIN FUNCTIONS *
****************************************/
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress)
external
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
migratedAddress = newVotingAddress;
}
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
inflationRate = newInflationRate;
}
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%");
gatPercentage = newGatPercentage;
}
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
rewardsExpirationTimeout = NewRewardsExpirationTimeout;
}
/****************************************
* PRIVATE AND INTERNAL FUNCTIONS *
****************************************/
// Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent
// the resolved price and a string which is filled with an error message, if there was an error or "".
function _getPriceOrError(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
)
private
view
returns (
bool,
int256,
string memory
)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return (false, 0, "Current voting round not ended");
} else if (requestStatus == RequestStatus.Resolved) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return (true, resolvedPrice, "");
} else if (requestStatus == RequestStatus.Future) {
return (false, 0, "Price is still to be voted on");
} else {
return (false, 0, "Price was never requested");
}
}
function _getPriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)];
}
function _encodePriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time, ancillaryData));
}
function _freezeRoundVariables(uint256 roundId) private {
Round storage round = rounds[roundId];
// Only on the first reveal should the snapshot be captured for that round.
if (round.snapshotId == 0) {
// There is no snapshot ID set, so create one.
round.snapshotId = votingToken.snapshot();
// Set the round inflation rate to the current global inflation rate.
rounds[roundId].inflationRate = inflationRate;
// Set the round gat percentage to the current global gat rate.
rounds[roundId].gatPercentage = gatPercentage;
// Set the rewards expiration time based on end of time of this round and the current global timeout.
rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add(
rewardsExpirationTimeout
);
}
}
function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private {
if (priceRequest.index == UINT_MAX) {
return;
}
(bool isResolved, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
require(isResolved, "Can't resolve unresolved request");
// Delete the resolved price request from pendingPriceRequests.
uint256 lastIndex = pendingPriceRequests.length - 1;
PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]];
lastPriceRequest.index = priceRequest.index;
pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex];
pendingPriceRequests.pop();
priceRequest.index = UINT_MAX;
emit PriceResolved(
priceRequest.lastVotingRound,
priceRequest.identifier,
priceRequest.time,
resolvedPrice,
priceRequest.ancillaryData
);
}
function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) {
uint256 snapshotId = rounds[roundId].snapshotId;
if (snapshotId == 0) {
// No snapshot - return max value to err on the side of caution.
return FixedPoint.Unsigned(UINT_MAX);
}
// Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId));
// Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens.
return snapshottedSupply.mul(rounds[roundId].gatPercentage);
}
function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId)
private
view
returns (RequestStatus)
{
if (priceRequest.lastVotingRound == 0) {
return RequestStatus.NotRequested;
} else if (priceRequest.lastVotingRound < currentRoundId) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(bool isResolved, ) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return isResolved ? RequestStatus.Resolved : RequestStatus.Active;
} else if (priceRequest.lastVotingRound == currentRoundId) {
return RequestStatus.Active;
} else {
// Means than priceRequest.lastVotingRound > currentRoundId
return RequestStatus.Future;
}
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples are the Oracle or Store interfaces.
*/
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleAncillaryInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param time unix timestamp for the price request.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for whitelists of supported identifiers that the oracle can provide prices for.
*/
interface IdentifierWhitelistInterface {
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../interfaces/RegistryInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title Registry for financial contracts and approved financial contract creators.
* @dev Maintains a whitelist of financial contract creators that are allowed
* to register new financial contracts and stores party members of a financial contract.
*/
contract Registry is RegistryInterface, MultiRole {
using SafeMath for uint256;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // The owner manages the set of ContractCreators.
ContractCreator // Can register financial contracts.
}
// This enum is required because a `WasValid` state is required
// to ensure that financial contracts cannot be re-registered.
enum Validity { Invalid, Valid }
// Local information about a contract.
struct FinancialContract {
Validity valid;
uint128 index;
}
struct Party {
address[] contracts; // Each financial contract address is stored in this array.
// The address of each financial contract is mapped to its index for constant time look up and deletion.
mapping(address => uint256) contractIndex;
}
// Array of all contracts that are approved to use the UMA Oracle.
address[] public registeredContracts;
// Map of financial contract contracts to the associated FinancialContract struct.
mapping(address => FinancialContract) public contractMap;
// Map each party member to their their associated Party struct.
mapping(address => Party) private partyMap;
/****************************************
* EVENTS *
****************************************/
event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties);
event PartyAdded(address indexed contractAddress, address indexed party);
event PartyRemoved(address indexed contractAddress, address indexed party);
/**
* @notice Construct the Registry contract.
*/
constructor() public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
// Start with no contract creators registered.
_createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0));
}
/****************************************
* REGISTRATION FUNCTIONS *
****************************************/
/**
* @notice Registers a new financial contract.
* @dev Only authorized contract creators can call this method.
* @param parties array of addresses who become parties in the contract.
* @param contractAddress address of the contract against which the parties are registered.
*/
function registerContract(address[] calldata parties, address contractAddress)
external
override
onlyRoleHolder(uint256(Roles.ContractCreator))
{
FinancialContract storage financialContract = contractMap[contractAddress];
require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once");
// Store contract address as a registered contract.
registeredContracts.push(contractAddress);
// No length check necessary because we should never hit (2^127 - 1) contracts.
financialContract.index = uint128(registeredContracts.length.sub(1));
// For all parties in the array add them to the contract's parties.
financialContract.valid = Validity.Valid;
for (uint256 i = 0; i < parties.length; i = i.add(1)) {
_addPartyToContract(parties[i], contractAddress);
}
emit NewContractRegistered(contractAddress, msg.sender, parties);
}
/**
* @notice Adds a party member to the calling contract.
* @dev msg.sender will be used to determine the contract that this party is added to.
* @param party new party for the calling contract.
*/
function addPartyToContract(address party) external override {
address contractAddress = msg.sender;
require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract");
_addPartyToContract(party, contractAddress);
}
/**
* @notice Removes a party member from the calling contract.
* @dev msg.sender will be used to determine the contract that this party is removed from.
* @param partyAddress address to be removed from the calling contract.
*/
function removePartyFromContract(address partyAddress) external override {
address contractAddress = msg.sender;
Party storage party = partyMap[partyAddress];
uint256 numberOfContracts = party.contracts.length;
require(numberOfContracts != 0, "Party has no contracts");
require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract");
require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party");
// Index of the current location of the contract to remove.
uint256 deleteIndex = party.contractIndex[contractAddress];
// Store the last contract's address to update the lookup map.
address lastContractAddress = party.contracts[numberOfContracts - 1];
// Swap the contract to be removed with the last contract.
party.contracts[deleteIndex] = lastContractAddress;
// Update the lookup index with the new location.
party.contractIndex[lastContractAddress] = deleteIndex;
// Pop the last contract from the array and update the lookup map.
party.contracts.pop();
delete party.contractIndex[contractAddress];
emit PartyRemoved(contractAddress, partyAddress);
}
/****************************************
* REGISTRY STATE GETTERS *
****************************************/
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the financial contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view override returns (bool) {
return contractMap[contractAddress].valid == Validity.Valid;
}
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view override returns (address[] memory) {
return partyMap[party].contracts;
}
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view override returns (address[] memory) {
return registeredContracts;
}
/**
* @notice checks if an address is a party of a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) {
uint256 index = partyMap[party].contractIndex[contractAddress];
return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _addPartyToContract(address party, address contractAddress) internal {
require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once");
uint256 contractIndex = partyMap[party].contracts.length;
partyMap[party].contracts.push(contractAddress);
partyMap[party].contractIndex[contractAddress] = contractIndex;
emit PartyAdded(contractAddress, party);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Computes vote results.
* @dev The result is the mode of the added votes. Otherwise, the vote is unresolved.
*/
library ResultComputation {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL LIBRARY DATA STRUCTURE *
****************************************/
struct Data {
// Maps price to number of tokens that voted for that price.
mapping(int256 => FixedPoint.Unsigned) voteFrequency;
// The total votes that have been added.
FixedPoint.Unsigned totalVotes;
// The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`.
int256 currentMode;
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Adds a new vote to be used when computing the result.
* @param data contains information to which the vote is applied.
* @param votePrice value specified in the vote for the given `numberTokens`.
* @param numberTokens number of tokens that voted on the `votePrice`.
*/
function addVote(
Data storage data,
int256 votePrice,
FixedPoint.Unsigned memory numberTokens
) internal {
data.totalVotes = data.totalVotes.add(numberTokens);
data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens);
if (
votePrice != data.currentMode &&
data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])
) {
data.currentMode = votePrice;
}
}
/****************************************
* VOTING STATE GETTERS *
****************************************/
/**
* @notice Returns whether the result is resolved, and if so, what value it resolved to.
* @dev `price` should be ignored if `isResolved` is false.
* @param data contains information against which the `minVoteThreshold` is applied.
* @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be
* used to enforce a minimum voter participation rate, regardless of how the votes are distributed.
* @return isResolved indicates if the price has been resolved correctly.
* @return price the price that the dvm resolved to.
*/
function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold)
internal
view
returns (bool isResolved, int256 price)
{
FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100);
if (
data.totalVotes.isGreaterThan(minVoteThreshold) &&
data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)
) {
// `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price.
isResolved = true;
price = data.currentMode;
} else {
isResolved = false;
}
}
/**
* @notice Checks whether a `voteHash` is considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains information against which the `voteHash` is checked.
* @param voteHash committed hash submitted by the voter.
* @return bool true if the vote was correct.
*/
function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) {
return voteHash == keccak256(abi.encode(data.currentMode));
}
/**
* @notice Gets the total number of tokens whose votes are considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains all votes against which the correctly voted tokens are counted.
* @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens.
*/
function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) {
return data.voteFrequency[data.currentMode];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/VotingInterface.sol";
/**
* @title Library to compute rounds and phases for an equal length commit-reveal voting cycle.
*/
library VoteTiming {
using SafeMath for uint256;
struct Data {
uint256 phaseLength;
}
/**
* @notice Initializes the data object. Sets the phase length based on the input.
*/
function init(Data storage data, uint256 phaseLength) internal {
// This should have a require message but this results in an internal Solidity error.
require(phaseLength > 0);
data.phaseLength = phaseLength;
}
/**
* @notice Computes the roundID based off the current time as floor(timestamp/roundLength).
* @dev The round ID depends on the global timestamp but not on the lifetime of the system.
* The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return roundId defined as a function of the currentTime and `phaseLength` from `data`.
*/
function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return currentTime.div(roundLength);
}
/**
* @notice compute the round end time as a function of the round Id.
* @param data input data object.
* @param roundId uniquely identifies the current round.
* @return timestamp unix time of when the current round will end.
*/
function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return roundLength.mul(roundId.add(1));
}
/**
* @notice Computes the current phase based only on the current time.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return current voting phase based on current time and vote phases configuration.
*/
function computeCurrentPhase(Data storage data, uint256 currentTime)
internal
view
returns (VotingAncillaryInterface.Phase)
{
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return
VotingAncillaryInterface.Phase(
currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol";
/**
* @title Ownership of this token allows a voter to respond to price requests.
* @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards.
*/
contract VotingToken is ExpandedERC20, ERC20Snapshot {
/**
* @notice Constructs the VotingToken.
*/
constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {}
/**
* @notice Creates a new snapshot ID.
* @return uint256 Thew new snapshot ID.
*/
function snapshot() external returns (uint256) {
return _snapshot();
}
// _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot,
// therefore the compiler will complain that VotingToken must override these methods
// because the two base classes (ERC20 and ERC20Snapshot) both define the same functions
function _transfer(
address from,
address to,
uint256 value
) internal override(ERC20, ERC20Snapshot) {
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._mint(account, value);
}
function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._burn(account, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Stores common interface names used throughout the DVM by registration in the Finder.
*/
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
bytes32 public constant CollateralWhitelist = "CollateralWhitelist";
bytes32 public constant OptimisticOracle = "OptimisticOracle";
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember) internal {
require(newMember != address(0x0), "Cannot set an exclusive role to 0x0");
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership) internal view returns (address) {
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember) internal {
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd) internal {
require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role");
roleMembership.members[memberToAdd] = true;
}
function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal {
roleMembership.members[memberToRemove] = false;
}
function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal {
for (uint256 i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
/**
* @title Base class to manage permissions for the derived class.
*/
abstract contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType { Invalid, Exclusive, Shared }
struct Role {
uint256 managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint256 => Role) private roles;
event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager);
/**
* @notice Reverts unless the caller is a member of the specified roleId.
*/
modifier onlyRoleHolder(uint256 roleId) {
require(holdsRole(roleId, msg.sender), "Sender does not hold required role");
_;
}
/**
* @notice Reverts unless the caller is a member of the manager role for the specified roleId.
*/
modifier onlyRoleManager(uint256 roleId) {
require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, exclusive roleId.
*/
modifier onlyExclusive(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, shared roleId.
*/
modifier onlyShared(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role");
_;
}
/**
* @notice Whether `memberToCheck` is a member of roleId.
* @dev Reverts if roleId does not correspond to an initialized role.
* @param roleId the Role to check.
* @param memberToCheck the address to check.
* @return True if `memberToCheck` is a member of `roleId`.
*/
function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert("Invalid roleId");
}
/**
* @notice Changes the exclusive role holder of `roleId` to `newMember`.
* @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an
* initialized, ExclusiveRole.
* @param roleId the ExclusiveRole membership to modify.
* @param newMember the new ExclusiveRole member.
*/
function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) {
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
emit ResetExclusiveMember(roleId, newMember, msg.sender);
}
/**
* @notice Gets the current holder of the exclusive role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, exclusive role.
* @param roleId the ExclusiveRole membership to check.
* @return the address of the current ExclusiveRole member.
*/
function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) {
return roles[roleId].exclusiveRoleMembership.getMember();
}
/**
* @notice Adds `newMember` to the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param newMember the new SharedRole member.
*/
function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.addMember(newMember);
emit AddedSharedMember(roleId, newMember, msg.sender);
}
/**
* @notice Removes `memberToRemove` from the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param memberToRemove the current SharedRole member to remove.
*/
function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
/**
* @notice Removes caller from the role, `roleId`.
* @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an
* initialized, SharedRole.
* @param roleId the SharedRole membership to modify.
*/
function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) {
roles[roleId].sharedRoleMembership.removeMember(msg.sender);
emit RemovedSharedMember(roleId, msg.sender, msg.sender);
}
/**
* @notice Reverts if `roleId` is not initialized.
*/
modifier onlyValidRole(uint256 roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
/**
* @notice Reverts if `roleId` is initialized.
*/
modifier onlyInvalidRole(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role");
_;
}
/**
* @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] memory initialMembers
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role"
);
}
/**
* @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`.
* `initialMember` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage an exclusive role"
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for a registry of contracts and contract creators.
*/
interface RegistryInterface {
/**
* @notice Registers a new contract.
* @dev Only authorized contract creators can call this method.
* @param parties an array of addresses who become parties in the contract.
* @param contractAddress defines the address of the deployed contract.
*/
function registerContract(address[] calldata parties, address contractAddress) external;
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view returns (bool);
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view returns (address[] memory);
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view returns (address[] memory);
/**
* @notice Adds a party to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be added to the contract.
*/
function addPartyToContract(address party) external;
/**
* @notice Removes a party member to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be removed from the contract.
*/
function removePartyFromContract(address party) external;
/**
* @notice checks if an address is a party in a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./MultiRole.sol";
import "../interfaces/ExpandedIERC20.sol";
/**
* @title An ERC20 with permissioned burning and minting. The contract deployer will initially
* be the owner who is capable of adding new roles.
*/
contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole {
enum Roles {
// Can set the minter and burner.
Owner,
// Addresses that can mint new tokens.
Minter,
// Addresses that can burn tokens that address owns.
Burner
}
/**
* @notice Constructs the ExpandedERC20.
* @param _tokenName The name which describes the new token.
* @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public ERC20(_tokenName, _tokenSymbol) {
_setupDecimals(_tokenDecimals);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0));
_createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0));
}
/**
* @dev Mints `value` tokens to `recipient`, returning true on success.
* @param recipient address to mint to.
* @param value amount of tokens to mint.
* @return True if the mint succeeded, or False.
*/
function mint(address recipient, uint256 value)
external
override
onlyRoleHolder(uint256(Roles.Minter))
returns (bool)
{
_mint(recipient, value);
return true;
}
/**
* @dev Burns `value` tokens owned by `msg.sender`.
* @param value amount of tokens to burn.
*/
function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) {
_burn(msg.sender, value);
}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external virtual override {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external virtual override {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external virtual override {
resetMember(uint256(Roles.Owner), account);
}
}
pragma solidity ^0.6.0;
import "../../math/SafeMath.sol";
import "../../utils/Arrays.sol";
import "../../utils/Counters.sol";
import "./ERC20.sol";
/**
* @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
* total supply at the time are recorded for later access.
*
* This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
* In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
* accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
* used to create an efficient ERC20 forking mechanism.
*
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
* snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
* id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
* and the account address.
*
* ==== Gas Costs
*
* Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
* n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
* smaller since identical balances in subsequent snapshots are stored as a single entry.
*
* There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
* only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
* transfers will have normal cost until the next snapshot, and so on.
*/
abstract contract ERC20Snapshot is ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(address from, address to, uint256 value) internal virtual override {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes burn and mint methods.
*/
abstract contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint256 value) external virtual;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external virtual returns (bool);
function addMinter(address account) external virtual;
function addBurner(address account) external virtual;
function resetOwner(address account) external virtual;
}
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
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;
}
}
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);
}
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;
import "../math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
pragma solidity ^0.6.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the
* upgrade process for Voting.sol.
* @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only
* the ones that need to be performed atomically.
*/
contract VotingUpgrader {
// Existing governor is the only one who can initiate the upgrade.
address public governor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public newVoting;
// Address to call setMigrated on the old voting contract.
address public setMigratedAddress;
/**
* @notice Removes an address from the whitelist.
* @param _governor the Governor contract address.
* @param _existingVoting the current/existing Voting contract address.
* @param _newVoting the new Voting deployment address.
* @param _finder the Finder contract address.
* @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to
* old voting contract (used to claim rewards on others' behalf). Note: this address
* can always be changed by the voters.
*/
constructor(
address _governor,
address _existingVoting,
address _newVoting,
address _finder,
address _setMigratedAddress
) public {
governor = _governor;
existingVoting = Voting(_existingVoting);
newVoting = _newVoting;
finder = Finder(_finder);
setMigratedAddress = _setMigratedAddress;
}
/**
* @notice Performs the atomic portion of the upgrade process.
* @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and
* returns ownership of the existing Voting contract and Finder back to the Governor.
*/
function upgrade() external {
require(msg.sender == governor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting);
// Set the preset "migrated" address to allow this address to claim rewards on voters' behalf.
// This also effectively shuts down the existing voting contract so new votes cannot be triggered.
existingVoting.setMigrated(setMigratedAddress);
// Transfer back ownership of old voting contract and the finder to the governor.
existingVoting.transferOwnership(governor);
finder.transferOwnership(governor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/FinderInterface.sol";
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces.
*/
contract Finder is FinderInterface, Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 of the interface name that is either changed or registered.
* @param implementationAddress address of the implementation contract.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
override
onlyOwner
{
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the defined interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view override returns (address) {
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "Implementation not found");
return implementationAddress;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract Umip3Upgrader {
// Existing governor is the only one who can initiate the upgrade.
address public existingGovernor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
address public newGovernor;
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public voting;
address public identifierWhitelist;
address public store;
address public financialContractsAdmin;
address public registry;
constructor(
address _existingGovernor,
address _existingVoting,
address _finder,
address _voting,
address _identifierWhitelist,
address _store,
address _financialContractsAdmin,
address _registry,
address _newGovernor
) public {
existingGovernor = _existingGovernor;
existingVoting = Voting(_existingVoting);
finder = Finder(_finder);
voting = _voting;
identifierWhitelist = _identifierWhitelist;
store = _store;
financialContractsAdmin = _financialContractsAdmin;
registry = _registry;
newGovernor = _newGovernor;
}
function upgrade() external {
require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, voting);
finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist);
finder.changeImplementationAddress(OracleInterfaces.Store, store);
finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin);
finder.changeImplementationAddress(OracleInterfaces.Registry, registry);
// Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated.
finder.transferOwnership(newGovernor);
// Inform the existing Voting contract of the address of the new Voting contract and transfer its
// ownership to the new governor to allow for any future changes to the migrated contract.
existingVoting.setMigrated(voting);
existingVoting.transferOwnership(newGovernor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracleAncillary is OracleAncillaryInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices;
QueryPoint[] private requestedPrices;
event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData);
event PushedPrice(
address indexed pusher,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
int256 price
);
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time, ancillaryData));
emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData);
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
int256 price
) external {
verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time][ancillaryData];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
emit PushedPrice(msg.sender, identifier, time, ancillaryData, price);
}
// Checks whether a price has been resolved.
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracle is OracleInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices;
QueryPoint[] private requestedPrices;
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(bytes32 identifier, uint256 time) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time));
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
int256 price
) external {
verifiedPrices[identifier][time] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
}
// Checks whether a price has been resolved.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OracleInterface.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Takes proposals for certain governance actions and allows UMA token holders to vote on them.
*/
contract Governor is MultiRole, Testable {
using SafeMath for uint256;
using Address for address;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the proposer.
Proposer // Address that can make proposals.
}
struct Transaction {
address to;
uint256 value;
bytes data;
}
struct Proposal {
Transaction[] transactions;
uint256 requestTime;
}
FinderInterface private finder;
Proposal[] public proposals;
/****************************************
* EVENTS *
****************************************/
// Emitted when a new proposal is created.
event NewProposal(uint256 indexed id, Transaction[] transactions);
// Emitted when an existing proposal is executed.
event ProposalExecuted(uint256 indexed id, uint256 transactionIndex);
/**
* @notice Construct the Governor contract.
* @param _finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param _startingId the initial proposal id that the contract will begin incrementing from.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _finderAddress,
uint256 _startingId,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender);
// Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite
// other storage slots in the contract.
uint256 maxStartingId = 10**18;
require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18");
// This just sets the initial length of the array to the startingId since modifying length directly has been
// disallowed in solidity 0.6.
assembly {
sstore(proposals_slot, _startingId)
}
}
/****************************************
* PROPOSAL ACTIONS *
****************************************/
/**
* @notice Proposes a new governance action. Can only be called by the holder of the Proposer role.
* @param transactions list of transactions that are being proposed.
* @dev You can create the data portion of each transaction by doing the following:
* ```
* const truffleContractInstance = await TruffleContract.deployed()
* const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI()
* ```
* Note: this method must be public because of a solidity limitation that
* disallows structs arrays to be passed to external functions.
*/
function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) {
uint256 id = proposals.length;
uint256 time = getCurrentTime();
// Note: doing all of this array manipulation manually is necessary because directly setting an array of
// structs in storage to an an array of structs in memory is currently not implemented in solidity :/.
// Add a zero-initialized element to the proposals array.
proposals.push();
// Initialize the new proposal.
Proposal storage proposal = proposals[id];
proposal.requestTime = time;
// Initialize the transaction array.
for (uint256 i = 0; i < transactions.length; i++) {
require(transactions[i].to != address(0), "The `to` address cannot be 0x0");
// If the transaction has any data with it the recipient must be a contract, not an EOA.
if (transactions[i].data.length > 0) {
require(transactions[i].to.isContract(), "EOA can't accept tx with data");
}
proposal.transactions.push(transactions[i]);
}
bytes32 identifier = _constructIdentifier(id);
// Request a vote on this proposal in the DVM.
OracleInterface oracle = _getOracle();
IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist();
supportedIdentifiers.addSupportedIdentifier(identifier);
oracle.requestPrice(identifier, time);
supportedIdentifiers.removeSupportedIdentifier(identifier);
emit NewProposal(id, transactions);
}
/**
* @notice Executes a proposed governance action that has been approved by voters.
* @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions.
* @param id unique id for the executed proposal.
* @param transactionIndex unique transaction index for the executed proposal.
*/
function executeProposal(uint256 id, uint256 transactionIndex) external payable {
Proposal storage proposal = proposals[id];
int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime);
Transaction memory transaction = proposal.transactions[transactionIndex];
require(
transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0),
"Previous tx not yet executed"
);
require(transaction.to != address(0), "Tx already executed");
require(price != 0, "Proposal was rejected");
require(msg.value == transaction.value, "Must send exact amount of ETH");
// Delete the transaction before execution to avoid any potential re-entrancy issues.
delete proposal.transactions[transactionIndex];
require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed");
emit ProposalExecuted(id, transactionIndex);
}
/****************************************
* GOVERNOR STATE GETTERS *
****************************************/
/**
* @notice Gets the total number of proposals (includes executed and non-executed).
* @return uint256 representing the current number of proposals.
*/
function numProposals() external view returns (uint256) {
return proposals.length;
}
/**
* @notice Gets the proposal data for a particular id.
* @dev after a proposal is executed, its data will be zeroed out, except for the request time.
* @param id uniquely identify the identity of the proposal.
* @return proposal struct containing transactions[] and requestTime.
*/
function getProposal(uint256 id) external view returns (Proposal memory) {
return proposals[id];
}
/****************************************
* PRIVATE GETTERS AND FUNCTIONS *
****************************************/
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool) {
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
bool success;
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
return success;
}
function _getOracle() private view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Returns a UTF-8 identifier representing a particular admin proposal.
// The identifier is of the form "Admin n", where n is the proposal id provided.
function _constructIdentifier(uint256 id) internal pure returns (bytes32) {
bytes32 bytesId = _uintToUtf8(id);
return _addPrefix(bytesId, "Admin ", 6);
}
// This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type.
// If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits.
// This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801.
function _uintToUtf8(uint256 v) internal pure returns (bytes32) {
bytes32 ret;
if (v == 0) {
// Handle 0 case explicitly.
ret = "0";
} else {
// Constants.
uint256 bitsPerByte = 8;
uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10.
uint256 utf8NumberOffset = 48;
while (v > 0) {
// Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which
// translates to the beginning of the UTF-8 representation.
ret = ret >> bitsPerByte;
// Separate the last digit that remains in v by modding by the base of desired output representation.
uint256 leastSignificantDigit = v % base;
// Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character.
bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset);
// The top byte of ret has already been cleared to make room for the new digit.
// Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched.
ret |= utf8Digit << (31 * bitsPerByte);
// Divide v by the base to remove the digit that was just added.
v /= base;
}
}
return ret;
}
// This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other.
// `input` is the UTF-8 that should have the prefix prepended.
// `prefix` is the UTF-8 that should be prepended onto input.
// `prefixLength` is number of UTF-8 characters represented by `prefix`.
// Notes:
// 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented
// by the bytes32 output.
// 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result.
function _addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) internal pure returns (bytes32) {
// Downshift `input` to open space at the "front" of the bytes32
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Governor.sol";
// GovernorTest exposes internal methods in the Governor for testing.
contract GovernorTest is Governor {
constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {}
function addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) external pure returns (bytes32) {
return _addPrefix(input, prefix, prefixLength);
}
function uintToUtf8(uint256 v) external pure returns (bytes32 ret) {
return _uintToUtf8(v);
}
function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) {
return _constructIdentifier(id);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/StoreInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OptimisticOracleInterface.sol";
import "./Constants.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/AddressWhitelist.sol";
/**
* @title Optimistic Requester.
* @notice Optional interface that requesters can implement to receive callbacks.
* @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
interface OptimisticRequester {
/**
* @notice Callback for proposals.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
*/
function priceProposed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external;
/**
* @notice Callback for disputes.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param refund refund received in the case that refundOnDispute was enabled.
*/
function priceDisputed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 refund
) external;
/**
* @notice Callback for settlement.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param price price that was resolved by the escalation process.
*/
function priceSettled(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 price
) external;
}
/**
* @title Optimistic Oracle.
* @notice Pre-DVM escalation contract that allows faster settlement.
*/
contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
event RequestPrice(
address indexed requester,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
address currency,
uint256 reward,
uint256 finalFee
);
event ProposePrice(
address indexed requester,
address indexed proposer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice,
uint256 expirationTimestamp,
address currency
);
event DisputePrice(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice
);
event Settle(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 price,
uint256 payout
);
mapping(bytes32 => Request) public requests;
// Finder to provide addresses for DVM contracts.
FinderInterface public finder;
// Default liveness value for all price requests.
uint256 public defaultLiveness;
/**
* @notice Constructor.
* @param _liveness default liveness applied to each price request.
* @param _finderAddress finder to use to get addresses of DVM contracts.
* @param _timerAddress address of the timer contract. Should be 0x0 in prod.
*/
constructor(
uint256 _liveness,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_validateLiveness(_liveness);
defaultLiveness = _liveness;
}
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier");
require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency");
require(timestamp <= getCurrentTime(), "Timestamp in future");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue;
requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({
proposer: address(0),
disputer: address(0),
currency: currency,
settled: false,
refundOnDispute: false,
proposedPrice: 0,
resolvedPrice: 0,
expirationTime: 0,
reward: reward,
finalFee: finalFee,
bond: finalFee,
customLiveness: 0
});
if (reward > 0) {
currency.safeTransferFrom(msg.sender, address(this), reward);
}
emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee);
// This function returns the initial proposal bond for this request, which can be customized by calling
// setBond() with the same identifier and timestamp.
return finalFee.mul(2);
}
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested");
Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData);
request.bond = bond;
// Total bond is the final fee + the newly set bond.
return bond.add(request.finalFee);
}
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setRefundOnDispute: Requested"
);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true;
}
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setCustomLiveness: Requested"
);
_validateLiveness(customLiveness);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness;
}
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public override nonReentrant() returns (uint256 totalBond) {
require(proposer != address(0), "proposer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Requested,
"proposePriceFor: Requested"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.proposer = proposer;
request.proposedPrice = proposedPrice;
// If a custom liveness has been set, use it instead of the default.
request.expirationTime = getCurrentTime().add(
request.customLiveness != 0 ? request.customLiveness : defaultLiveness
);
totalBond = request.bond.add(request.finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
emit ProposePrice(
requester,
proposer,
identifier,
timestamp,
ancillaryData,
proposedPrice,
request.expirationTime,
address(request.currency)
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {}
}
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice);
}
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public override nonReentrant() returns (uint256 totalBond) {
require(disputer != address(0), "disputer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Proposed,
"disputePriceFor: Proposed"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.disputer = disputer;
uint256 finalFee = request.finalFee;
uint256 bond = request.bond;
totalBond = bond.add(finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
StoreInterface store = _getStore();
// Avoids stack too deep compilation error.
{
// Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it
// proportionally more expensive to delay the resolution even if the proposer and disputer are the same
// party.
uint256 burnedBond = _computeBurnedBond(request);
// The total fee is the burned bond and the final fee added together.
uint256 totalFee = finalFee.add(burnedBond);
if (totalFee > 0) {
request.currency.safeIncreaseAllowance(address(store), totalFee);
_getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee));
}
}
_getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester));
// Compute refund.
uint256 refund = 0;
if (request.reward > 0 && request.refundOnDispute) {
refund = request.reward;
request.reward = 0;
request.currency.safeTransfer(requester, refund);
}
emit DisputePrice(
requester,
request.proposer,
disputer,
identifier,
timestamp,
ancillaryData,
request.proposedPrice
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {}
}
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (int256) {
if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) {
_settle(msg.sender, identifier, timestamp, ancillaryData);
}
return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice;
}
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (uint256 payout) {
return _settle(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (Request memory) {
return _getRequest(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Computes the current state of a price request. See the State enum for more details.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (State) {
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
if (address(request.currency) == address(0)) {
return State.Invalid;
}
if (request.proposer == address(0)) {
return State.Requested;
}
if (request.settled) {
return State.Settled;
}
if (request.disputer == address(0)) {
return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed;
}
return
_getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester))
? State.Resolved
: State.Disputed;
}
/**
* @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return boolean indicating true if price exists and false if not.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (bool) {
State state = getState(requester, identifier, timestamp, ancillaryData);
return state == State.Settled || state == State.Resolved || state == State.Expired;
}
/**
* @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute.
* @param ancillaryData ancillary data of the price being requested.
* @param requester sender of the initial price request.
* @return the stampped ancillary bytes.
*/
function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) {
return _stampAncillaryData(ancillaryData, requester);
}
function _getId(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData));
}
function _settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private returns (uint256 payout) {
State state = getState(requester, identifier, timestamp, ancillaryData);
// Set it to settled so this function can never be entered again.
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.settled = true;
if (state == State.Expired) {
// In the expiry case, just pay back the proposer's bond and final fee along with the reward.
request.resolvedPrice = request.proposedPrice;
payout = request.bond.add(request.finalFee).add(request.reward);
request.currency.safeTransfer(request.proposer, payout);
} else if (state == State.Resolved) {
// In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward).
request.resolvedPrice = _getOracle().getPrice(
identifier,
timestamp,
_stampAncillaryData(ancillaryData, requester)
);
bool disputeSuccess = request.resolvedPrice != request.proposedPrice;
uint256 bond = request.bond;
// Unburned portion of the loser's bond = 1 - burned bond.
uint256 unburnedBond = bond.sub(_computeBurnedBond(request));
// Winner gets:
// - Their bond back.
// - The unburned portion of the loser's bond.
// - Their final fee back.
// - The request reward (if not already refunded -- if refunded, it will be set to 0).
payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward);
request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout);
} else {
revert("_settle: not settleable");
}
emit Settle(
requester,
request.proposer,
request.disputer,
identifier,
timestamp,
ancillaryData,
request.resolvedPrice,
payout
);
// Callback.
if (address(requester).isContract())
try
OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice)
{} catch {}
}
function _getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private view returns (Request storage) {
return requests[_getId(requester, identifier, timestamp, ancillaryData)];
}
function _computeBurnedBond(Request storage request) private view returns (uint256) {
// burnedBond = floor(bond / 2)
return request.bond.div(2);
}
function _validateLiveness(uint256 _liveness) private pure {
require(_liveness < 5200 weeks, "Liveness too large");
require(_liveness > 0, "Liveness cannot be 0");
}
function _getOracle() internal view returns (OracleAncillaryInterface) {
return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getCollateralWhitelist() internal view returns (AddressWhitelist) {
return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
}
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it.
function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) {
return abi.encodePacked(ancillaryData, "OptimisticOracle", requester);
}
}
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that allows financial contracts to pay oracle fees for their use of the system.
*/
interface StoreInterface {
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable;
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external;
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty);
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due.
*/
function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OptimisticOracleInterface {
// Struct representing the state of a price request.
enum State {
Invalid, // Never requested.
Requested, // Requested, no other actions taken.
Proposed, // Proposed, but not expired or disputed yet.
Expired, // Proposed, not disputed, past liveness.
Disputed, // Disputed, but no DVM price returned yet.
Resolved, // Disputed and DVM price is available.
Settled // Final price has been set in the contract (can get here from Expired or Resolved).
}
// Struct representing a price request.
struct Request {
address proposer; // Address of the proposer.
address disputer; // Address of the disputer.
IERC20 currency; // ERC20 token used to pay rewards and fees.
bool settled; // True if the request is settled.
bool refundOnDispute; // True if the requester should be refunded their reward on dispute.
int256 proposedPrice; // Price that the proposer submitted.
int256 resolvedPrice; // Price resolved once the request is settled.
uint256 expirationTime; // Time at which the request auto-settles without a dispute.
uint256 reward; // Amount of the currency to pay to the proposer on settlement.
uint256 finalFee; // Final fee to pay to the Store upon request to the DVM.
uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee.
uint256 customLiveness; // Custom liveness value set by the requester.
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses
// to accept a price request made with ancillary data length of a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external virtual returns (uint256 totalBond);
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external virtual returns (uint256 totalBond);
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual;
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external virtual;
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was value (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public virtual returns (uint256 totalBond);
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 totalBond);
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (int256);
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 payout);
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (Request memory);
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (State);
/**
* @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract
* is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol.
*/
contract Lockable {
bool private _notEntered;
constructor() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered.
// Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Lockable.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract AddressWhitelist is Ownable, Lockable {
enum Status { None, In, Out }
mapping(address => Status) public whitelist;
address[] public whitelistIndices;
event AddedToWhitelist(address indexed addedAddress);
event RemovedFromWhitelist(address indexed removedAddress);
/**
* @notice Adds an address to the whitelist.
* @param newElement the new address to add.
*/
function addToWhitelist(address newElement) external nonReentrant() onlyOwner {
// Ignore if address is already included
if (whitelist[newElement] == Status.In) {
return;
}
// Only append new addresses to the array, never a duplicate
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddedToWhitelist(newElement);
}
/**
* @notice Removes an address from the whitelist.
* @param elementToRemove the existing address to remove.
*/
function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner {
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemovedFromWhitelist(elementToRemove);
}
}
/**
* @notice Checks whether an address is on the whitelist.
* @param elementToCheck the address to check.
* @return True if `elementToCheck` is on the whitelist, or False.
*/
function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) {
return whitelist[elementToCheck] == Status.In;
}
/**
* @notice Gets all addresses that are currently included in the whitelist.
* @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out
* of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we
* can modify the implementation so that when addresses are removed, the last addresses in the array is moved to
* the empty index.
* @return activeWhitelist the list of addresses on the whitelist.
*/
function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) {
// Determine size of whitelist first
uint256 activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
// Populate whitelist
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../OptimisticOracle.sol";
// This is just a test contract to make requests to the optimistic oracle.
contract OptimisticRequesterTest is OptimisticRequester {
OptimisticOracle optimisticOracle;
bool public shouldRevert = false;
// State variables to track incoming calls.
bytes32 public identifier;
uint256 public timestamp;
bytes public ancillaryData;
uint256 public refund;
int256 public price;
// Implement collateralCurrency so that this contract simulates a financial contract whose collateral
// token can be fetched by off-chain clients.
IERC20 public collateralCurrency;
// Manually set an expiration timestamp to simulate expiry price requests
uint256 public expirationTimestamp;
constructor(OptimisticOracle _optimisticOracle) public {
optimisticOracle = _optimisticOracle;
}
function requestPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
IERC20 currency,
uint256 reward
) external {
// Set collateral currency to last requested currency:
collateralCurrency = currency;
currency.approve(address(optimisticOracle), reward);
optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward);
}
function settleAndGetPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external returns (int256) {
return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData);
}
function setBond(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 bond
) external {
optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond);
}
function setRefundOnDispute(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external {
optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData);
}
function setCustomLiveness(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 customLiveness
) external {
optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness);
}
function setRevert(bool _shouldRevert) external {
shouldRevert = _shouldRevert;
}
function setExpirationTimestamp(uint256 _expirationTimestamp) external {
expirationTimestamp = _expirationTimestamp;
}
function clearState() external {
delete identifier;
delete timestamp;
delete refund;
delete price;
}
function priceProposed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
}
function priceDisputed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 _refund
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
refund = _refund;
}
function priceSettled(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
int256 _price
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
price = _price;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/StoreInterface.sol";
/**
* @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token.
*/
contract Store is StoreInterface, Withdrawable, Testable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeERC20 for IERC20;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles { Owner, Withdrawer }
FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee.
FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee.
mapping(address => FixedPoint.Unsigned) public finalFees;
uint256 public constant SECONDS_PER_WEEK = 604800;
/****************************************
* EVENTS *
****************************************/
event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee);
event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc);
event NewFinalFee(FixedPoint.Unsigned newFinalFee);
/**
* @notice Construct the Store contract.
*/
constructor(
FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc,
FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc,
address _timerAddress
) public Testable(_timerAddress) {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender);
setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc);
setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc);
}
/****************************************
* ORACLE FEE CALCULATION AND PAYMENT *
****************************************/
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable override {
require(msg.value > 0, "Value sent can't be zero");
}
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override {
IERC20 erc20 = IERC20(erc20Address);
require(amount.isGreaterThan(0), "Amount sent can't be zero");
erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue);
}
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @dev The late penalty is similar to the regular fee in that is is charged per second over the period between
* startTime and endTime.
*
* The late penalty percentage increases over time as follows:
*
* - 0-1 week since startTime: no late penalty
*
* - 1-2 weeks since startTime: 1x late penalty percentage is applied
*
* - 2-3 weeks since startTime: 2x late penalty percentage is applied
*
* - ...
*
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty penalty percentage, if any, for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) {
uint256 timeDiff = endTime.sub(startTime);
// Multiply by the unscaled `timeDiff` first, to get more accurate results.
regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc);
// Compute how long ago the start time was to compute the delay penalty.
uint256 paymentDelay = getCurrentTime().sub(startTime);
// Compute the additional percentage (per second) that will be charged because of the penalty.
// Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to
// 0, causing no penalty to be charged.
FixedPoint.Unsigned memory penaltyPercentagePerSecond =
weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK));
// Apply the penaltyPercentagePerSecond to the payment period.
latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond);
}
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due denominated in units of `currency`.
*/
function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) {
return finalFees[currency];
}
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Sets a new oracle fee per second.
* @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle.
*/
function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
// Oracle fees at or over 100% don't make sense.
require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second.");
fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc;
emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc);
}
/**
* @notice Sets a new weekly delay fee.
* @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment.
*/
function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%");
weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc;
emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc);
}
/**
* @notice Sets a new final fee for a particular currency.
* @param currency defines the token currency used to pay the final fee.
* @param newFinalFee final fee amount.
*/
function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee)
public
onlyRoleHolder(uint256(Roles.Owner))
{
finalFees[currency] = newFinalFee;
emit NewFinalFee(newFinalFee);
}
}
/**
* Withdrawable contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./MultiRole.sol";
/**
* @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds.
*/
abstract contract Withdrawable is MultiRole {
using SafeERC20 for IERC20;
uint256 private roleId;
/**
* @notice Withdraws ETH from the contract.
*/
function withdraw(uint256 amount) external onlyRoleHolder(roleId) {
Address.sendValue(msg.sender, amount);
}
/**
* @notice Withdraws ERC20 tokens from the contract.
* @param erc20Address ERC20 token to withdraw.
* @param amount amount of tokens to withdraw.
*/
function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) {
IERC20 erc20 = IERC20(erc20Address);
erc20.safeTransfer(msg.sender, amount);
}
/**
* @notice Internal method that allows derived contracts to create a role for withdrawal.
* @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function
* properly.
* @param newRoleId ID corresponding to role whose members can withdraw.
* @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership.
* @param withdrawerAddress new manager of withdrawable role.
*/
function _createWithdrawRole(
uint256 newRoleId,
uint256 managingRoleId,
address withdrawerAddress
) internal {
roleId = newRoleId;
_createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress);
}
/**
* @notice Internal method that allows derived contracts to choose the role for withdrawal.
* @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be
* called by the derived class for this contract to function properly.
* @param setRoleId ID corresponding to role whose members can withdraw.
*/
function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) {
roleId = setRoleId;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/interfaces/StoreInterface.sol";
import "../../oracle/interfaces/FinderInterface.sol";
import "../../oracle/interfaces/AdministrateeInterface.sol";
import "../../oracle/implementation/Constants.sol";
/**
* @title FeePayer contract.
* @notice Provides fee payment functionality for the ExpiringMultiParty contract.
* contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`.
*/
abstract contract FeePayer is AdministrateeInterface, Testable, Lockable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
/****************************************
* FEE PAYER DATA STRUCTURES *
****************************************/
// The collateral currency used to back the positions in this contract.
IERC20 public collateralCurrency;
// Finder contract used to look up addresses for UMA system contracts.
FinderInterface public finder;
// Tracks the last block time when the fees were paid.
uint256 private lastPaymentTime;
// Tracks the cumulative fees that have been paid by the contract for use by derived contracts.
// The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee).
// Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ...
// For example:
// The cumulativeFeeMultiplier should start at 1.
// If a 1% fee is charged, the multiplier should update to .99.
// If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801).
FixedPoint.Unsigned public cumulativeFeeMultiplier;
/****************************************
* EVENTS *
****************************************/
event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee);
event FinalFeesPaid(uint256 indexed amount);
/****************************************
* MODIFIERS *
****************************************/
// modifier that calls payRegularFees().
modifier fees virtual {
// Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the
// regular fee applied linearly since the last update. This implies that the compounding rate depends on the
// frequency of update transactions that have this modifier, and it never reaches the ideal of continuous
// compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the
// complexity of compounding data on-chain.
payRegularFees();
_;
}
/**
* @notice Constructs the FeePayer contract. Called by child contracts.
* @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
collateralCurrency = IERC20(_collateralAddress);
finder = FinderInterface(_finderAddress);
lastPaymentTime = getCurrentTime();
cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1);
}
/****************************************
* FEE PAYMENT FUNCTIONS *
****************************************/
/**
* @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract.
* @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee
* in a week or more then a late penalty is applied which is sent to the caller. If the amount of
* fees owed are greater than the pfc, then this will pay as much as possible from the available collateral.
* An event is only fired if the fees charged are greater than 0.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
* This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
*/
function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) {
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract.
(
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
) = getOutstandingRegularFees(time);
lastPaymentTime = time;
// If there are no fees to pay then exit early.
if (totalPaid.isEqual(0)) {
return totalPaid;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
_adjustCumulativeFeeMultiplier(totalPaid, collateralPool);
if (regularFee.isGreaterThan(0)) {
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), regularFee);
}
if (latePenalty.isGreaterThan(0)) {
collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue);
}
return totalPaid;
}
/**
* @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more
* than the total collateral within the contract then the totalPaid returned is full contract collateral amount.
* @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
* @return regularFee outstanding unpaid regular fee.
* @return latePenalty outstanding unpaid late fee for being late in previous fee payments.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
*/
function getOutstandingRegularFees(uint256 time)
public
view
returns (
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
)
{
StoreInterface store = _getStore();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Exit early if there is no collateral or if fees were already paid during this block.
if (collateralPool.isEqual(0) || lastPaymentTime == time) {
return (regularFee, latePenalty, totalPaid);
}
(regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool);
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return (regularFee, latePenalty, totalPaid);
}
// If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay
// as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the
// regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining.
if (totalPaid.isGreaterThan(collateralPool)) {
FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool);
FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit);
latePenalty = latePenalty.sub(latePenaltyReduction);
deficit = deficit.sub(latePenaltyReduction);
regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit));
totalPaid = collateralPool;
}
}
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _pfc();
}
/**
* @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors.
* @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively
* pays all sponsors a pro-rata portion of the excess collateral.
* @dev This will revert if PfC is 0 and this contract's collateral balance > 0.
*/
function gulp() external nonReentrant() {
_gulp();
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee
// charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not
// the contract, pulls in `amount` of collateral currency.
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal {
if (amount.isEqual(0)) {
return;
}
if (payer != address(this)) {
// If the payer is not the contract pull the collateral from the payer.
collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue);
} else {
// If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate.
FixedPoint.Unsigned memory collateralPool = _pfc();
// The final fee must be < available collateral or the fee will be larger than 100%.
// Note: revert reason removed to save bytecode.
require(collateralPool.isGreaterThan(amount));
_adjustCumulativeFeeMultiplier(amount, collateralPool);
}
emit FinalFeesPaid(amount.rawValue);
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), amount);
}
function _gulp() internal {
FixedPoint.Unsigned memory currentPfc = _pfc();
FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
if (currentPfc.isLessThan(currentBalance)) {
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc));
}
}
function _pfc() internal view virtual returns (FixedPoint.Unsigned memory);
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) {
StoreInterface store = _getStore();
return store.computeFinalFee(address(collateralCurrency));
}
// Returns the user's collateral minus any fees that have been subtracted since it was originally
// deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw
// value should be larger than the returned value.
function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory collateral)
{
return rawCollateral.mul(cumulativeFeeMultiplier);
}
// Returns the user's collateral minus any pending fees that have yet to be subtracted.
function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory)
{
(, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) =
getOutstandingRegularFees(getCurrentTime());
if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral;
// Calculate the total outstanding regular fee as a fraction of the total contract PFC.
FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc());
// Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee.
return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee));
}
// Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees
// have been taken from this contract in the past, then the raw value will be larger than the user-readable value.
function _convertToRawCollateral(FixedPoint.Unsigned memory collateral)
internal
view
returns (FixedPoint.Unsigned memory rawCollateral)
{
return collateral.div(cumulativeFeeMultiplier);
}
// Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an
// actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is
// decreased by so that the caller can minimize error between collateral removed and rawCollateral debited.
function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove)
internal
returns (FixedPoint.Unsigned memory removedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove);
rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue;
removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral));
}
// Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an
// actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is
// increased by so that the caller can minimize error between collateral added and rawCollateral credited.
// NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it
// because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral.
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd)
internal
returns (FixedPoint.Unsigned memory addedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd);
rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue;
addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance);
}
// Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral.
function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc)
internal
{
FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc);
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that all financial contracts expose to the admin.
*/
interface AdministrateeInterface {
/**
* @notice Initiates the shutdown process, in case of an emergency.
*/
function emergencyShutdown() external;
/**
* @notice A core contract method called independently or as a part of other financial contract transactions.
* @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract.
*/
function remargin() external;
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FeePayer.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PricelessPositionManager is FeePayer {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
using Address for address;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement.
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
ContractState public contractState;
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
// Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`.
uint256 transferPositionRequestPassTimestamp;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs.
uint256 public expirationTimestamp;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// The expiry price pulled from the DVM.
FixedPoint.Unsigned public expiryPrice;
// Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend
// the functionality of the EMP to support a wider range of financial products.
FinancialProductLibrary public financialProductLibrary;
/****************************************
* EVENTS *
****************************************/
event RequestTransferPosition(address indexed oldSponsor);
event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor);
event RequestTransferPositionCanceled(address indexed oldSponsor);
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event ContractExpired(address indexed caller);
event SettleExpiredPosition(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyPreExpiration() {
_onlyPreExpiration();
_;
}
modifier onlyPostExpiration() {
_onlyPostExpiration();
_;
}
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
// Check that the current state of the pricelessPositionManager is Open.
// This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration.
modifier onlyOpenState() {
_onlyOpenState();
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PricelessPositionManager
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _expirationTimestamp unix timestamp of when the contract will expire.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
* @param _financialProductLibraryAddress Contract providing contract state transformations.
*/
constructor(
uint256 _expirationTimestamp,
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _timerAddress,
address _financialProductLibraryAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() {
require(_expirationTimestamp > getCurrentTime());
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
expirationTimestamp = _expirationTimestamp;
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
// Initialize the financialProductLibrary at the provided address.
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Requests to transfer ownership of the caller's current position to a new sponsor address.
* Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor.
* @dev The liveness length is the same as the withdrawal liveness.
*/
function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
/**
* @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting
* `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`.
* @dev Transferring positions can only occur if the recipient does not already have a position.
* @param newSponsorAddress is the address to which the position will be transferred.
*/
function transferPositionPassedRequest(address newSponsorAddress)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
require(
_getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual(
FixedPoint.fromUnscaledUint(0)
)
);
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.transferPositionRequestPassTimestamp != 0 &&
positionData.transferPositionRequestPassTimestamp <= getCurrentTime()
);
// Reset transfer request.
positionData.transferPositionRequestPassTimestamp = 0;
positions[newSponsorAddress] = positionData;
delete positions[msg.sender];
emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress);
emit NewSponsor(newSponsorAddress);
emit EndedSponsorPosition(msg.sender);
}
/**
* @notice Cancels a pending transfer position request.
*/
function cancelTransferPosition() external onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp != 0);
emit RequestTransferPositionCanceled(msg.sender);
// Reset withdrawal request.
positionData.transferPositionRequestPassTimestamp = 0;
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = requestPassTime;
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
onlyPreExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(!numTokens.isGreaterThan(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the
* prevailing price defined by the DVM from the `expire` function.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleExpired()
external
onlyPostExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired position");
// Get the current settlement price and store it. If it is not resolved will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePriceExpiration(expirationTimestamp);
contractState = ContractState.ExpiredPriceReceived;
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying.
FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Locks contract state in expired and requests oracle price.
* @dev this function can only be called once the contract is expired and can't be re-called.
*/
function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() {
contractState = ContractState.ExpiredPriceRequested;
// Final fees do not need to be paid when sending a request to the optimistic oracle.
_requestOraclePriceExpiration(expirationTimestamp);
emit ContractExpired(msg.sender);
}
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested`
* which prevents re-entry into this function or the `expire` function. No fees are paid when calling
* `emergencyShutdown` as the governor who would call the function would also receive the fees.
*/
function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() {
require(msg.sender == _getFinancialContractsAdminAddress());
contractState = ContractState.ExpiredPriceRequested;
// Expiratory time now becomes the current time (emergency shutdown time).
// Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp.
uint256 oldExpirationTimestamp = expirationTimestamp;
expirationTimestamp = getCurrentTime();
_requestOraclePriceExpiration(expirationTimestamp);
emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override onlyPreExpiration() nonReentrant() {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PricelessPositionManager.
* @return totalCollateral amount of all collateral within the Expiring Multi Party Contract.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
*/
function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
/**
* @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract
* deployment. If no library was provided then no modification to the price is done.
* @param price input price to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformPrice(price, requestTime);
}
/**
* @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified
* at contract deployment. If no library was provided then no modification to the identifier is done.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) {
return _transformPriceIdentifier(requestTime);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral;
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceExpiration(uint256 requestedTime) internal {
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Increase token allowance to enable the optimistic oracle reward transfer.
FixedPoint.Unsigned memory reward = _computeFinalFees();
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue);
optimisticOracle.requestPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData(),
collateralCurrency,
reward.rawValue // Reward is equal to the final fee
);
// Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee.
_adjustCumulativeFeeMultiplier(reward, _pfc());
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
require(
optimisticOracle.hasPrice(
address(this),
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
)
);
int256 optimisticOraclePrice =
optimisticOracle.settleAndGetPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
);
// For now we don't want to deal with negative prices in positions.
if (optimisticOraclePrice < 0) {
optimisticOraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceLiquidation(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyOpenState() internal view {
require(contractState == ContractState.Open, "Contract state is not OPEN");
}
function _onlyPreExpiration() internal view {
require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
}
function _onlyPostExpiration() internal view {
require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
}
function _onlyCollateralizedPosition(address sponsor) internal view {
require(
_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0),
"Position has no collateral"
);
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
if (!numTokens.isGreaterThan(0)) {
return FixedPoint.fromUnscaledUint(0);
} else {
return collateral.div(numTokens);
}
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) {
if (!address(financialProductLibrary).isContract()) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(address(tokenCurrency));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes the decimals read only method.
*/
interface IERC20Standard is IERC20 {
/**
* @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() external view returns (uint8);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../../common/implementation/FixedPoint.sol";
interface ExpiringContractInterface {
function expirationTimestamp() external view returns (uint256);
}
/**
* @title Financial product library contract
* @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom
* Financial product library implementations.
*/
abstract contract FinancialProductLibrary {
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Transforms a given oracle price using the financial product libraries transformation logic.
* @param oraclePrice input price returned by the DVM to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedOraclePrice input oraclePrice with the transformation function applied.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
virtual
returns (FixedPoint.Unsigned memory)
{
return oraclePrice;
}
/**
* @notice Transforms a given collateral requirement using the financial product libraries transformation logic.
* @param oraclePrice input price returned by DVM used to transform the collateral requirement.
* @param collateralRequirement input collateral requirement to be transformed.
* @return transformedCollateralRequirement input collateral requirement with the transformation function applied.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view virtual returns (FixedPoint.Unsigned memory) {
return collateralRequirement;
}
/**
* @notice Transforms a given price identifier using the financial product libraries transformation logic.
* @param priceIdentifier input price identifier defined for the financial contract.
* @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier.
* @return transformedPriceIdentifier input price identifier with the transformation function applied.
*/
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
virtual
returns (bytes32)
{
return priceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
// Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations.
contract FinancialProductLibraryTest is FinancialProductLibrary {
FixedPoint.Unsigned public priceTransformationScalar;
FixedPoint.Unsigned public collateralRequirementTransformationScalar;
bytes32 public transformedPriceIdentifier;
bool public shouldRevert;
constructor(
FixedPoint.Unsigned memory _priceTransformationScalar,
FixedPoint.Unsigned memory _collateralRequirementTransformationScalar,
bytes32 _transformedPriceIdentifier
) public {
priceTransformationScalar = _priceTransformationScalar;
collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar;
transformedPriceIdentifier = _transformedPriceIdentifier;
}
// Set the mocked methods to revert to test failed library computation.
function setShouldRevert(bool _shouldRevert) public {
shouldRevert = _shouldRevert;
}
// Create a simple price transformation function that scales the input price by the scalar for testing.
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
returns (FixedPoint.Unsigned memory)
{
require(!shouldRevert, "set to always reverts");
return oraclePrice.mul(priceTransformationScalar);
}
// Create a simple collateral requirement transformation that doubles the input collateralRequirement.
function transformCollateralRequirement(
FixedPoint.Unsigned memory price,
FixedPoint.Unsigned memory collateralRequirement
) public view override returns (FixedPoint.Unsigned memory) {
require(!shouldRevert, "set to always reverts");
return collateralRequirement.mul(collateralRequirementTransformationScalar);
}
// Create a simple transformPriceIdentifier function that returns the transformed price identifier.
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
override
returns (bytes32)
{
require(!shouldRevert, "set to always reverts");
return transformedPriceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
contract ExpiringMultiPartyMock is Testable {
using FixedPoint for FixedPoint.Unsigned;
FinancialProductLibrary public financialProductLibrary;
uint256 public expirationTimestamp;
FixedPoint.Unsigned public collateralRequirement;
bytes32 public priceIdentifier;
constructor(
address _financialProductLibraryAddress,
uint256 _expirationTimestamp,
FixedPoint.Unsigned memory _collateralRequirement,
bytes32 _priceIdentifier,
address _timerAddress
) public Testable(_timerAddress) {
expirationTimestamp = _expirationTimestamp;
collateralRequirement = _collateralRequirement;
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
priceIdentifier = _priceIdentifier;
}
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) {
if (address(financialProductLibrary) == address(0)) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data.
abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "./Constants.sol";
/**
* @title Proxy to allow voting from another address.
* @dev Allows a UMA token holder to designate another address to vote on their behalf.
* Each voter must deploy their own instance of this contract.
*/
contract DesignatedVoting is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the Voter role. Is also permanently permissioned as the minter role.
Voter // Can vote through this contract.
}
// Reference to the UMA Finder contract, allowing Voting upgrades to be performed
// without requiring any calls to this contract.
FinderInterface private finder;
/**
* @notice Construct the DesignatedVoting contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param ownerAddress address of the owner of the DesignatedVoting contract.
* @param voterAddress address to which the owner has delegated their voting power.
*/
constructor(
address finderAddress,
address ownerAddress,
address voterAddress
) public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress);
_createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress);
_setWithdrawRole(uint256(Roles.Owner));
finder = FinderInterface(finderAddress);
}
/****************************************
* VOTING AND REWARD FUNCTIONALITY *
****************************************/
/**
* @notice Forwards a commit to Voting.
* @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param hash the keccak256 hash of the price you want to vote for and a random integer salt value.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, ancillaryData, hash);
}
/**
* @notice Forwards a batch commit to Voting.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchCommit(commits);
}
/**
* @notice Forwards a reveal to Voting.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price used along with the `salt` to produce the `hash` during the commit phase.
* @param salt used along with the `price` to produce the `hash` during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt);
}
/**
* @notice Forwards a batch reveal to Voting.
* @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchReveal(reveals);
}
/**
* @notice Forwards a reward retrieval to Voting.
* @dev Rewards are added to the tokens already held by this contract.
* @param roundId defines the round from which voting rewards will be retrieved from.
* @param toRetrieve an array of PendingRequests which rewards are retrieved from.
* @return amount of rewards that the user should receive.
*/
function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve)
public
onlyRoleHolder(uint256(Roles.Voter))
returns (FixedPoint.Unsigned memory)
{
return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve);
}
function _getVotingAddress() private view returns (VotingAncillaryInterface) {
return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Withdrawable.sol";
import "./DesignatedVoting.sol";
/**
* @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances.
* @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract.
*/
contract DesignatedVotingFactory is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract.
}
address private finder;
mapping(address => DesignatedVoting) public designatedVotingContracts;
/**
* @notice Construct the DesignatedVotingFactory contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
*/
constructor(address finderAddress) public {
finder = finderAddress;
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender);
}
/**
* @notice Deploys a new `DesignatedVoting` contract.
* @param ownerAddress defines who will own the deployed instance of the designatedVoting contract.
* @return designatedVoting a new DesignatedVoting contract.
*/
function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) {
DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender);
designatedVotingContracts[msg.sender] = designatedVoting;
return designatedVoting;
}
/**
* @notice Associates a `DesignatedVoting` instance with `msg.sender`.
* @param designatedVotingAddress address to designate voting to.
* @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter`
* address and wants that reflected here.
*/
function setDesignatedVoting(address designatedVotingAddress) external {
designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Withdrawable.sol";
// WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes.
contract WithdrawableTest is Withdrawable {
enum Roles { Governance, Withdraw }
// solhint-disable-next-line no-empty-blocks
constructor() public {
_createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender);
_createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender);
}
function pay() external payable {
require(msg.value > 0);
}
function setInternalWithdrawRole(uint256 setRoleId) public {
_setWithdrawRole(setRoleId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI)
* @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note:
* this token should never be used to store real value since it allows permissionless minting.
*/
contract TestnetERC20 is ERC20 {
/**
* @notice Constructs the TestnetERC20.
* @param _name The name which describes the new token.
* @param _symbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _decimals The number of decimals to define token precision.
*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
}
// Sample token information.
/**
* @notice Mints value tokens to the owner address.
* @param ownerAddress the address to mint to.
* @param value the amount of tokens to mint.
*/
function allocateTo(address ownerAddress, uint256 value) external {
_mint(ownerAddress, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/IdentifierWhitelistInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Stores a whitelist of supported identifiers that the oracle can provide prices for.
*/
contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
mapping(bytes32 => bool) private supportedIdentifiers;
/****************************************
* EVENTS *
****************************************/
event SupportedIdentifierAdded(bytes32 indexed identifier);
event SupportedIdentifierRemoved(bytes32 indexed identifier);
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (!supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = true;
emit SupportedIdentifierAdded(identifier);
}
}
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = false;
emit SupportedIdentifierRemoved(identifier);
}
}
/****************************************
* WHITELIST GETTERS FUNCTIONS *
****************************************/
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view override returns (bool) {
return supportedIdentifiers[identifier];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/AdministrateeInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Admin for financial contracts in the UMA system.
* @dev Allows appropriately permissioned admin roles to interact with financial contracts.
*/
contract FinancialContractsAdmin is Ownable {
/**
* @notice Calls emergency shutdown on the provided financial contract.
* @param financialContract address of the FinancialContract to be shut down.
*/
function callEmergencyShutdown(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.emergencyShutdown();
}
/**
* @notice Calls remargin on the provided financial contract.
* @param financialContract address of the FinancialContract to be remargined.
*/
function callRemargin(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.remargin();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/AdministrateeInterface.sol";
// A mock implementation of AdministrateeInterface, taking the place of a financial contract.
contract MockAdministratee is AdministrateeInterface {
uint256 public timesRemargined;
uint256 public timesEmergencyShutdown;
function remargin() external override {
timesRemargined++;
}
function emergencyShutdown() external override {
timesEmergencyShutdown++;
}
function pfc() external view override returns (FixedPoint.Unsigned memory) {
return FixedPoint.fromUnscaledUint(0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* Inspired by:
* - https://github.com/pie-dao/vested-token-migration-app
* - https://github.com/Uniswap/merkle-distributor
* - https://github.com/balancer-labs/erc20-redeemable
*
* @title MerkleDistributor contract.
* @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify
* multiple Merkle roots distributions with customized reward currencies.
* @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly.
*/
contract MerkleDistributor is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// A Window maps a Merkle root to a reward token address.
struct Window {
// Merkle root describing the distribution.
bytes32 merkleRoot;
// Currency in which reward is processed.
IERC20 rewardToken;
// IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical
// data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code>
// <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier
// for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply
// go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>.
string ipfsHash;
}
// Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`.
struct Claim {
uint256 windowIndex;
uint256 amount;
uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim.
address account;
bytes32[] merkleProof;
}
// Windows are mapped to arbitrary indices.
mapping(uint256 => Window) public merkleWindows;
// Index of next created Merkle root.
uint256 public nextCreatedIndex;
// Track which accounts have claimed for each window index.
// Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract.
mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap;
/****************************************
* EVENTS
****************************************/
event Claimed(
address indexed caller,
uint256 windowIndex,
address indexed account,
uint256 accountIndex,
uint256 amount,
address indexed rewardToken
);
event CreatedWindow(
uint256 indexed windowIndex,
uint256 rewardsDeposited,
address indexed rewardToken,
address owner
);
event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency);
event DeleteWindow(uint256 indexed windowIndex, address owner);
/****************************
* ADMIN FUNCTIONS
****************************/
/**
* @notice Set merkle root for the next available window index and seed allocations.
* @notice Callable only by owner of this contract. Caller must have approved this contract to transfer
* `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the
* owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all
* claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur
* because we do not segregate reward balances by window, for code simplicity purposes.
* (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must
* subsequently transfer in rewards or the following situation can occur).
* Example race situation:
* - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and
* claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101.
* - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner
* correctly set `rewardsToDeposit` this time.
* - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence:
* (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens.
* (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens.
* (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens.
* - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would
* succeed and the second claim would fail, even though both claimants would expect their claims to succeed.
* @param rewardsToDeposit amount of rewards to deposit to seed this allocation.
* @param rewardToken ERC20 reward token.
* @param merkleRoot merkle root describing allocation.
* @param ipfsHash hash of IPFS object, conveniently stored for clients
*/
function setWindow(
uint256 rewardsToDeposit,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) external onlyOwner {
uint256 indexToSet = nextCreatedIndex;
nextCreatedIndex = indexToSet.add(1);
_setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash);
}
/**
* @notice Delete merkle root at window index.
* @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state.
* @param windowIndex merkle root index to delete.
*/
function deleteWindow(uint256 windowIndex) external onlyOwner {
delete merkleWindows[windowIndex];
emit DeleteWindow(windowIndex, msg.sender);
}
/**
* @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly.
* @dev Callable only by owner.
* @param rewardCurrency rewards to withdraw from contract.
* @param amount amount of rewards to withdraw.
*/
function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner {
IERC20(rewardCurrency).safeTransfer(msg.sender, amount);
emit WithdrawRewards(msg.sender, amount, rewardCurrency);
}
/****************************
* NON-ADMIN FUNCTIONS
****************************/
/**
* @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail
* if any individual claims within the batch would fail.
* @dev Optimistically tries to batch together consecutive claims for the same account and same
* reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method
* is to pass in an array of claims sorted by account and reward currency.
* @param claims array of claims to claim.
*/
function claimMulti(Claim[] memory claims) external {
uint256 batchedAmount = 0;
uint256 claimCount = claims.length;
for (uint256 i = 0; i < claimCount; i++) {
Claim memory _claim = claims[i];
_verifyAndMarkClaimed(_claim);
batchedAmount = batchedAmount.add(_claim.amount);
// If the next claim is NOT the same account or the same token (or this claim is the last one),
// then disburse the `batchedAmount` to the current claim's account for the current claim's reward token.
uint256 nextI = i + 1;
address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken);
if (
nextI == claimCount ||
// This claim is last claim.
claims[nextI].account != _claim.account ||
// Next claim account is different than current one.
address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken
// Next claim reward token is different than current one.
) {
IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount);
batchedAmount = 0;
}
}
}
/**
* @notice Claim amount of reward tokens for account, as described by Claim input object.
* @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the
* values stored in the merkle root for the `_claim`'s `windowIndex` this method
* will revert.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
*/
function claim(Claim memory _claim) public {
_verifyAndMarkClaimed(_claim);
merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount);
}
/**
* @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at
* `windowIndex`.
* @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`.
* The onus is on the Owner of this contract to submit only valid Merkle roots.
* @param windowIndex merkle root to check.
* @param accountIndex account index to check within window index.
* @return True if claim has been executed already, False otherwise.
*/
function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
/**
* @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given
* window index.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
* @return valid True if leaf exists.
*/
function verifyClaim(Claim memory _claim) public view returns (bool valid) {
bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex));
return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf);
}
/****************************
* PRIVATE FUNCTIONS
****************************/
// Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`.
function _setClaimed(uint256 windowIndex, uint256 accountIndex) private {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
claimedBitMap[windowIndex][claimedWordIndex] =
claimedBitMap[windowIndex][claimedWordIndex] |
(1 << claimedBitIndex);
}
// Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root.
function _setWindow(
uint256 windowIndex,
uint256 rewardsDeposited,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) private {
Window storage window = merkleWindows[windowIndex];
window.merkleRoot = merkleRoot;
window.rewardToken = IERC20(rewardToken);
window.ipfsHash = ipfsHash;
emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender);
window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited);
}
// Verify claim is valid and mark it as completed in this contract.
function _verifyAndMarkClaimed(Claim memory _claim) private {
// Check claimed proof against merkle window at given index.
require(verifyClaim(_claim), "Incorrect merkle proof");
// Check the account has not yet claimed for this window.
require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window");
// Proof is correct and claim has not occurred yet, mark claimed complete.
_setClaimed(_claim.windowIndex, _claim.accountIndex);
emit Claimed(
msg.sender,
_claim.windowIndex,
_claim.account,
_claim.accountIndex,
_claim.amount,
address(merkleWindows[_claim.windowIndex].rewardToken)
);
}
}
pragma solidity ^0.6.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FundingRateApplier.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PerpetualPositionManager is FundingRateApplier {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// Expiry price pulled from the DVM in the case of an emergency shutdown.
FixedPoint.Unsigned public emergencyShutdownPrice;
/****************************************
* EVENTS *
****************************************/
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp);
event SettleEmergencyShutdown(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PerpetualPositionManager.
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production.
*/
constructor(
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
bytes32 _fundingRateIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
// No pending withdrawal require message removed to save bytecode.
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount
* ` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0);
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens));
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
// Note: revert reason removed to save bytecode.
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or
* remaining collateral for underlying at the prevailing price defined by a DVM vote.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this
* function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleEmergencyShutdown()
external
isEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert.
if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) {
emergencyShutdownPrice = _getOracleEmergencyShutdownPrice();
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral =
_getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with
// the funding rate applied to the outstanding token debt.
FixedPoint.Unsigned memory tokenDebtValueInCollateral =
_getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the `settleEmergencyShutdown` function.
*/
function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() {
// Note: revert reason removed to save bytecode.
require(msg.sender == _getFinancialContractsAdminAddress());
emergencyShutdownTimestamp = getCurrentTime();
_requestOraclePrice(emergencyShutdownTimestamp);
emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PerpetualPositionManager.
* @return totalCollateral amount of all collateral within the position manager.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFundingRateAppliedTokenDebt(rawTokenDebt);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove);
require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens));
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
_getOracle().requestPrice(priceIdentifier, requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) {
return _getOraclePrice(emergencyShutdownTimestamp);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyCollateralizedPosition(address sponsor) internal view {
require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0));
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0);
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens);
}
function _getTokenAddress() internal view override returns (address) {
return address(tokenCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/implementation/Constants.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../perpetual-multiparty/ConfigStoreInterface.sol";
import "./EmergencyShutdownable.sol";
import "./FeePayer.sol";
/**
* @title FundingRateApplier contract.
* @notice Provides funding rate payment functionality for the Perpetual contract.
*/
abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
using SafeERC20 for IERC20;
using SafeMath for uint256;
/****************************************
* FUNDING RATE APPLIER DATA STRUCTURES *
****************************************/
struct FundingRate {
// Current funding rate value.
FixedPoint.Signed rate;
// Identifier to retrieve the funding rate.
bytes32 identifier;
// Tracks the cumulative funding payments that have been paid to the sponsors.
// The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment).
// Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ...
// For example:
// The cumulativeFundingRateMultiplier should start at 1.
// If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01.
// If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201).
FixedPoint.Unsigned cumulativeMultiplier;
// Most recent time that the funding rate was updated.
uint256 updateTime;
// Most recent time that the funding rate was applied and changed the cumulative multiplier.
uint256 applicationTime;
// The time for the active (if it exists) funding rate proposal. 0 otherwise.
uint256 proposalTime;
}
FundingRate public fundingRate;
// Remote config store managed an owner.
ConfigStoreInterface public configStore;
/****************************************
* EVENTS *
****************************************/
event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward);
/****************************************
* MODIFIERS *
****************************************/
// This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate.
modifier fees override {
// Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the
// rate applied linearly since the last update. This implies that the compounding rate depends on the frequency
// of update transactions that have this modifier, and it never reaches the ideal of continuous compounding.
// This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of
// compounding data on-chain.
applyFundingRate();
_;
}
// Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees.
modifier paysRegularFees {
payRegularFees();
_;
}
/**
* @notice Constructs the FundingRateApplier contract. Called by child contracts.
* @param _fundingRateIdentifier identifier that tracks the funding rate of this contract.
* @param _collateralAddress address of the collateral token.
* @param _finderAddress Finder used to discover financial-product-related contracts.
* @param _configStoreAddress address of the remote configuration store managed by an external owner.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress address of the timer contract in test envs, otherwise 0x0.
*/
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() {
uint256 currentTime = getCurrentTime();
fundingRate.updateTime = currentTime;
fundingRate.applicationTime = currentTime;
// Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are
// applied over time.
fundingRate.cumulativeMultiplier = _tokenScaling;
fundingRate.identifier = _fundingRateIdentifier;
configStore = ConfigStoreInterface(_configStoreAddress);
}
/**
* @notice This method takes 3 distinct actions:
* 1. Pays out regular fees.
* 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards.
* 3. Applies the prevailing funding rate over the most recent period.
*/
function applyFundingRate() public paysRegularFees() nonReentrant() {
_applyEffectiveFundingRate();
}
/**
* @notice Proposes a new funding rate. Proposer receives a reward if correct.
* @param rate funding rate being proposed.
* @param timestamp time at which the funding rate was computed.
*/
function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp)
external
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalBond)
{
require(fundingRate.proposalTime == 0, "Proposal in progress");
_validateFundingRate(rate);
// Timestamp must be after the last funding rate update time, within the last 30 minutes.
uint256 currentTime = getCurrentTime();
uint256 updateTime = fundingRate.updateTime;
require(
timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit),
"Invalid proposal time"
);
// Set the proposal time in order to allow this contract to track this request.
fundingRate.proposalTime = timestamp;
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Set up optimistic oracle.
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Note: requestPrice will revert if `timestamp` is less than the current block timestamp.
optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0);
totalBond = FixedPoint.Unsigned(
optimisticOracle.setBond(
identifier,
timestamp,
ancillaryData,
_pfc().mul(_getConfig().proposerBondPercentage).rawValue
)
);
// Pull bond from caller and send to optimistic oracle.
if (totalBond.isGreaterThan(0)) {
collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue);
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue);
}
optimisticOracle.proposePriceFor(
msg.sender,
address(this),
identifier,
timestamp,
ancillaryData,
rate.rawValue
);
}
// Returns a token amount scaled by the current funding rate multiplier.
// Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value.
function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
internal
view
returns (FixedPoint.Unsigned memory tokenDebt)
{
return rawTokenDebt.mul(fundingRate.cumulativeMultiplier);
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) {
return configStore.updateAndGetCurrentConfig();
}
function _updateFundingRate() internal {
uint256 proposalTime = fundingRate.proposalTime;
// If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate.
if (proposalTime != 0) {
// Attempt to update the funding rate.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Try to get the price from the optimistic oracle. This call will revert if the request has not resolved
// yet. If the request has not resolved yet, then we need to do additional checks to see if we should
// "forget" the pending proposal and allow new proposals to update the funding rate.
try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) {
// If successful, determine if the funding rate state needs to be updated.
// If the request is more recent than the last update then we should update it.
uint256 lastUpdateTime = fundingRate.updateTime;
if (proposalTime >= lastUpdateTime) {
// Update funding rates
fundingRate.rate = FixedPoint.Signed(price);
fundingRate.updateTime = proposalTime;
// If there was no dispute, send a reward.
FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0);
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer == address(0)) {
reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime));
if (reward.isGreaterThan(0)) {
_adjustCumulativeFeeMultiplier(reward, _pfc());
collateralCurrency.safeTransfer(request.proposer, reward.rawValue);
}
}
// This event will only be emitted after the fundingRate struct's "updateTime" has been set
// to the latest proposal's proposalTime, indicating that the proposal has been published.
// So, it suffices to just emit fundingRate.updateTime here.
emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue);
}
// Set proposal time to 0 since this proposal has now been resolved.
fundingRate.proposalTime = 0;
} catch {
// Stop tracking and allow other proposals to come in if:
// - The requester address is empty, indicating that the Oracle does not know about this funding rate
// request. This is possible if the Oracle is replaced while the price request is still pending.
// - The request has been disputed.
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer != address(0) || request.proposer == address(0)) {
fundingRate.proposalTime = 0;
}
}
}
}
// Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the
// perpetual's security. For example, let's examine the case where the max and min funding rates
// are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a
// proposer who can deter honest proposers for 74 hours:
// 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%.
// How would attack work? Imagine that the market is very volatile currently and that the "true" funding
// rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500%
// (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding
// rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value.
function _validateFundingRate(FixedPoint.Signed memory rate) internal {
require(
rate.isLessThanOrEqual(_getConfig().maxFundingRate) &&
rate.isGreaterThanOrEqual(_getConfig().minFundingRate)
);
}
// Fetches a funding rate from the Store, determines the period over which to compute an effective fee,
// and multiplies the current multiplier by the effective fee.
// A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier.
// Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat
// values < 1 as "negative".
function _applyEffectiveFundingRate() internal {
// If contract is emergency shutdown, then the funding rate multiplier should no longer change.
if (emergencyShutdownTimestamp != 0) {
return;
}
uint256 currentTime = getCurrentTime();
uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime);
_updateFundingRate(); // Update the funding rate if there is a resolved proposal.
fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate(
paymentPeriod,
fundingRate.rate,
fundingRate.cumulativeMultiplier
);
fundingRate.applicationTime = currentTime;
}
function _calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) {
// Note: this method uses named return variables to save a little bytecode.
// The overall formula that this function is performing:
// newCumulativeFundingRateMultiplier =
// (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier.
FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1);
// Multiply the per-second rate over the number of seconds that have elapsed to get the period rate.
FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds));
// Add one to create the multiplier to scale the existing fee multiplier.
FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate);
// Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned.
FixedPoint.Unsigned memory unsignedPeriodMultiplier =
FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0)));
// Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new
// cumulative funding rate multiplier.
newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier);
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(_getTokenAddress());
}
function _getTokenAddress() internal view virtual returns (address);
}
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);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
interface ConfigStoreInterface {
// All of the configuration settings available for querying by a perpetual.
struct ConfigSettings {
// Liveness period (in seconds) for an update to currentConfig to become official.
uint256 timelockLiveness;
// Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%.
FixedPoint.Unsigned rewardRatePerSecond;
// Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%.
FixedPoint.Unsigned proposerBondPercentage;
// Maximum funding rate % per second that can be proposed.
FixedPoint.Signed maxFundingRate;
// Minimum funding rate % per second that can be proposed.
FixedPoint.Signed minFundingRate;
// Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest
// update time.
uint256 proposalTimePastLimit;
}
function updateAndGetCurrentConfig() external returns (ConfigSettings memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title EmergencyShutdownable contract.
* @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable.
* This contract provides modifiers that can be used by children contracts to determine if the contract is
* in the shutdown state. The child contract is expected to implement the logic that happens
* once a shutdown occurs.
*/
abstract contract EmergencyShutdownable {
using SafeMath for uint256;
/****************************************
* EMERGENCY SHUTDOWN DATA STRUCTURES *
****************************************/
// Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered.
uint256 public emergencyShutdownTimestamp;
/****************************************
* MODIFIERS *
****************************************/
modifier notEmergencyShutdown() {
_notEmergencyShutdown();
_;
}
modifier isEmergencyShutdown() {
_isEmergencyShutdown();
_;
}
/****************************************
* EXTERNAL FUNCTIONS *
****************************************/
constructor() public {
emergencyShutdownTimestamp = 0;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _notEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp == 0);
}
function _isEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp != 0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/FundingRateApplier.sol";
import "../../common/implementation/FixedPoint.sol";
// Implements FundingRateApplier internal methods to enable unit testing.
contract FundingRateApplierTest is FundingRateApplier {
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{}
function calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) public pure returns (FixedPoint.Unsigned memory) {
return
_calculateEffectiveFundingRate(
paymentPeriodSeconds,
fundingRatePerSecond,
currentCumulativeFundingRateMultiplier
);
}
// Required overrides.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) {
return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
}
function emergencyShutdown() external override {}
function remargin() external override {}
function _getTokenAddress() internal view override returns (address) {
return address(collateralCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ConfigStoreInterface.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it
* to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded
* by a privileged account and the upgraded changes are timelocked.
*/
contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* STORE DATA STRUCTURES *
****************************************/
// Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig
// if its liveness has expired.
ConfigStoreInterface.ConfigSettings private currentConfig;
// Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config.
ConfigStoreInterface.ConfigSettings public pendingConfig;
uint256 public pendingPassedTimestamp;
/****************************************
* EVENTS *
****************************************/
event ProposedNewConfigSettings(
address indexed proposer,
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit,
uint256 proposalPassedTimestamp
);
event ChangedConfigSettings(
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit
);
/****************************************
* MODIFIERS *
****************************************/
// Update config settings if possible.
modifier updateConfig() {
_updateConfig();
_;
}
/**
* @notice Construct the Config Store. An initial configuration is provided and set on construction.
* @param _initialConfig Configuration settings to initialize `currentConfig` with.
* @param _timerAddress Address of testable Timer contract.
*/
constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) {
_validateConfig(_initialConfig);
currentConfig = _initialConfig;
}
/**
* @notice Returns current config or pending config if pending liveness has expired.
* @return ConfigSettings config settings that calling financial contract should view as "live".
*/
function updateAndGetCurrentConfig()
external
override
updateConfig()
nonReentrant()
returns (ConfigStoreInterface.ConfigSettings memory)
{
return currentConfig;
}
/**
* @notice Propose new configuration settings. New settings go into effect after a liveness period passes.
* @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now.
* @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal.
*/
function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() {
_validateConfig(newConfig);
// Warning: This overwrites a pending proposal!
pendingConfig = newConfig;
// Use current config's liveness period to timelock this proposal.
pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness);
emit ProposedNewConfigSettings(
msg.sender,
newConfig.rewardRatePerSecond.rawValue,
newConfig.proposerBondPercentage.rawValue,
newConfig.timelockLiveness,
newConfig.maxFundingRate.rawValue,
newConfig.minFundingRate.rawValue,
newConfig.proposalTimePastLimit,
pendingPassedTimestamp
);
}
/**
* @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness.
*/
function publishPendingConfig() external nonReentrant() updateConfig() {}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Check if pending proposal can overwrite the current config.
function _updateConfig() internal {
// If liveness has passed, publish proposed configuration settings.
if (_pendingProposalPassed()) {
currentConfig = pendingConfig;
_deletePendingConfig();
emit ChangedConfigSettings(
currentConfig.rewardRatePerSecond.rawValue,
currentConfig.proposerBondPercentage.rawValue,
currentConfig.timelockLiveness,
currentConfig.maxFundingRate.rawValue,
currentConfig.minFundingRate.rawValue,
currentConfig.proposalTimePastLimit
);
}
}
function _deletePendingConfig() internal {
delete pendingConfig;
pendingPassedTimestamp = 0;
}
function _pendingProposalPassed() internal view returns (bool) {
return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime());
}
// Use this method to constrain values with which you can set ConfigSettings.
function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure {
// We don't set limits on proposal timestamps because there are already natural limits:
// - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints.
// - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30
// mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time.
// Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself
// before a vulnerability drains its collateral.
require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness");
// The reward rate should be modified as needed to incentivize honest proposers appropriately.
// Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs
// = 0.0000033
FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7);
require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond");
// We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer
// were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer
// could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest
// proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their
// PfC for each proposal liveness window. The downside of not limiting this is that the config store owner
// can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the
// proposal bond based on the configuration's funding rate range like in this discussion:
// https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383
// We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude
// funding rates in extraordinarily volatile market situations. Note, that even though we do not bound
// the max/min, we still recommend that the deployer of this contract set the funding rate max/min values
// to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year].
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./PerpetualLib.sol";
import "./ConfigStore.sol";
/**
* @title Perpetual Contract creator.
* @notice Factory contract to create and register new instances of perpetual contracts.
* Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints
* that are applied to newly created contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract PerpetualCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* PERP CREATOR DATA STRUCTURES *
****************************************/
// Immutable params for perpetual contract.
struct Params {
address collateralAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress);
event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress);
/**
* @notice Constructs the Perpetual contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of perpetual and registers it within the registry.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed contract.
*/
function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings)
public
nonReentrant()
returns (address)
{
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
// Create new config settings store for this contract and reset ownership to the deployer.
ConfigStore configStore = new ConfigStore(configSettings, timerAddress);
configStore.transferOwnership(msg.sender);
emit CreatedConfigStore(address(configStore), configStore.owner());
// Create a new synthetic token using the params.
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method,
// then a default precision of 18 will be applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore)));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedPerpetual(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createPerpetual params to Perpetual constructor params.
function _convertParams(
Params memory params,
ExpandedIERC20 newTokenCurrency,
address configStore
) private view returns (Perpetual.ConstructorParams memory constructorParams) {
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want perpetual deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the perpetual unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// To avoid precision loss or overflows, prevent the token scaling from being too large or too small.
FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10
FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10
require(
params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling),
"Invalid tokenScaling"
);
// Input from function call.
constructorParams.configStoreAddress = configStore;
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.fundingRateIdentifier = params.fundingRateIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.tokenScaling = params.tokenScaling;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/FinderInterface.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "./Registry.sol";
import "./Constants.sol";
/**
* @title Base contract for all financial contract creators
*/
abstract contract ContractCreator {
address internal finderAddress;
constructor(address _finderAddress) public {
finderAddress = _finderAddress;
}
function _requireWhitelistedCollateral(address collateralAddress) internal view {
FinderInterface finder = FinderInterface(finderAddress);
AddressWhitelist collateralWhitelist =
AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted");
}
function _registerContract(address[] memory parties, address contractToRegister) internal {
FinderInterface finder = FinderInterface(finderAddress);
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
registry.registerContract(parties, contractToRegister);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./SyntheticToken.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Factory for creating new mintable and burnable tokens.
*/
contract TokenFactory is Lockable {
/**
* @notice Create a new token and return it to the caller.
* @dev The caller will become the only minter and burner and the new owner capable of assigning the roles.
* @param tokenName used to describe the new token.
* @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals used to define the precision used in the token's numerical representation.
* @return newToken an instance of the newly created token interface.
*/
function createToken(
string calldata tokenName,
string calldata tokenSymbol,
uint8 tokenDecimals
) external nonReentrant() returns (ExpandedIERC20 newToken) {
SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals);
mintableToken.addMinter(msg.sender);
mintableToken.addBurner(msg.sender);
mintableToken.resetOwner(msg.sender);
newToken = ExpandedIERC20(address(mintableToken));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Burnable and mintable ERC20.
* @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles.
*/
contract SyntheticToken is ExpandedERC20, Lockable {
/**
* @notice Constructs the SyntheticToken.
* @param tokenName The name which describes the new token.
* @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals
) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external override nonReentrant() {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Remove Minter role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Minter role is removed.
*/
function removeMinter(address account) external nonReentrant() {
removeMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external override nonReentrant() {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Removes Burner role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Burner role is removed.
*/
function removeBurner(address account) external nonReentrant() {
removeMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external override nonReentrant() {
resetMember(uint256(Roles.Owner), account);
}
/**
* @notice Checks if a given account holds the Minter role.
* @param account The address which is checked for the Minter role.
* @return bool True if the provided account is a Minter.
*/
function isMinter(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Minter), account);
}
/**
* @notice Checks if a given account holds the Burner role.
* @param account The address which is checked for the Burner role.
* @return bool True if the provided account is a Burner.
*/
function isBurner(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Burner), account);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Perpetual.sol";
/**
* @title Provides convenient Perpetual Multi Party contract utilities.
* @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode.
*/
library PerpetualLib {
/**
* @notice Returns address of new Perpetual deployed with given `params` configuration.
* @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed Perpetual contract
*/
function deploy(Perpetual.ConstructorParams memory params) public returns (address) {
Perpetual derivative = new Perpetual(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./PerpetualLiquidatable.sol";
/**
* @title Perpetual Multiparty Contract.
* @notice Convenient wrapper for Liquidatable.
*/
contract Perpetual is PerpetualLiquidatable {
/**
* @notice Constructs the Perpetual contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualLiquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./PerpetualPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title PerpetualLiquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract PerpetualLiquidatable is PerpetualPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PerpetualPositionManager only.
uint256 withdrawalLiveness;
address configStoreAddress;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
// Params specifically for PerpetualLiquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualPositionManager(
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.fundingRateIdentifier,
params.minSponsorTokens,
params.configStoreAddress,
params.tokenScaling,
params.timerAddress
)
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position
// are not funding-rate adjusted because the multiplier only affects their redemption value, not their
// notional.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated),
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
_getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final
* fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
// Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at
// liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in
// the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio.
FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement);
// If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./ExpiringMultiPartyLib.sol";
/**
* @title Expiring Multi Party Contract creator.
* @notice Factory contract to create and register new instances of expiring multiparty contracts.
* Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints
* that are applied to newly created expiring multi party contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* EMP CREATOR DATA STRUCTURES *
****************************************/
struct Params {
uint256 expirationTimestamp;
address collateralAddress;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address financialProductLibraryAddress;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress);
/**
* @notice Constructs the ExpiringMultiPartyCreator contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of expiring multi party and registers it within the registry.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract.
*/
function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) {
// Create a new synthetic token using the params.
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method, then a default precision of 18 will be
// applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedExpiringMultiParty(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createExpiringMultiParty params to ExpiringMultiParty constructor params.
function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
{
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
require(params.expirationTimestamp > now, "Invalid expiration time");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want EMP deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the EMP unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// Input from function call.
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.expirationTimestamp = params.expirationTimestamp;
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./ExpiringMultiParty.sol";
/**
* @title Provides convenient Expiring Multi Party contract utilities.
* @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode.
*/
library ExpiringMultiPartyLib {
/**
* @notice Returns address of new EMP deployed with given `params` configuration.
* @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract
*/
function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) {
ExpiringMultiParty derivative = new ExpiringMultiParty(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Liquidatable.sol";
/**
* @title Expiring Multi Party.
* @notice Convenient wrapper for Liquidatable.
*/
contract ExpiringMultiParty is Liquidatable {
/**
* @notice Constructs the ExpiringMultiParty contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
Liquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./PricelessPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Liquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract Liquidatable is PricelessPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PricelessPositionManager only.
uint256 expirationTimestamp;
uint256 withdrawalLiveness;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
address financialProductLibraryAddress;
bytes32 priceFeedIdentifier;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PricelessPositionManager(
params.expirationTimestamp,
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.minSponsorTokens,
params.timerAddress,
params.financialProductLibraryAddress
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
// maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: tokensLiquidated,
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
tokensLiquidated.rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePriceLiquidation(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: `payToLiquidator` should never be below zero since we enforce that
// (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/**
* @notice Accessor method to calculate a transformed collateral requirement using the finanical product library
specified during contract deployment. If no library was provided then no modification to the collateral requirement is done.
* @param price input price used as an input to transform the collateral requirement.
* @return transformedCollateralRequirement collateral requirement with transformation applied to it.
* @dev This method should never revert.
*/
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformCollateralRequirement(price);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform
// Collateral requirement method applies a from the financial Product library to change the scaled the collateral
// requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change.
FixedPoint.Unsigned memory requiredCollateral =
tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice));
// If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized,
"Invalid liquidation ID"
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)),
"Liquidation not withdrawable"
);
}
function _transformCollateralRequirement(FixedPoint.Unsigned memory price)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Structured Note Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If
* ETHUSD is above that strike, the contract pays out a given dollar amount of ETH.
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH
* If ETHUSD < $400 at expiry, token is redeemed for 1 ETH.
* If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM.
*/
contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable {
mapping(address => FixedPoint.Unsigned) financialProductStrikes;
/**
* @notice Enables the deployer of the library to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the structured note to be applied to the financial product.
* @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) financialProduct must exposes an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
onlyOwner
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the structured note payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThan(strike)) {
return FixedPoint.fromUnscaledUint(1);
} else {
// Token expires to be worth strike $ worth of collateral.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH.
return strike.div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price
* of the structured note is greater than the strike then the collateral requirement scales down accordingly.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If the price is less than the strike than the original collateral requirement is used.
if (oraclePrice.isLessThan(strike)) {
return collateralRequirement;
} else {
// If the price is more than the strike then the collateral requirement is scaled by the strike. For example
// a strike of $400 and a CR of 1.2 would yield:
// ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292
// ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96
return collateralRequirement.mul(strike.div(oraclePrice));
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Pre-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made before expiration then a transformation is made to the identifier
* & if it is at or after expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is before contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return financialProductTransformedIdentifiers[msg.sender];
} else {
return identifier;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Post-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier
* & if it is before expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is after contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return identifier;
} else {
return financialProductTransformedIdentifiers[msg.sender];
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title KPI Options Financial Product Library
* @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract.
* If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1.
* Post-expiry, the collateral requirement is left as 1 and the price is left unchanged.
*/
contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable {
/**
* @notice Returns a transformed price for pre-expiry price requests.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
// If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with
// each token backed 1:2 by collateral currency. Post-expiry, leave unchanged.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(2);
} else {
return oraclePrice;
}
}
/**
* @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled to a flat rate.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Always return 1.
return FixedPoint.fromUnscaledUint(1);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title CoveredCall Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If
* ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by
* (oraclePrice - strikePrice) / oraclePrice;
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH.
* If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200).
* If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400).
* If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH.
*/
contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => FixedPoint.Unsigned) private financialProductStrikes;
/**
* @notice Enables any address to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the covered call to be applied to the financial product.
* @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool.
* e) financialProduct must expose an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the call option payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThanOrEqual(strike)) {
return FixedPoint.fromUnscaledUint(0);
} else {
// Token expires to be worth the fraction of a collateral token that's in the money.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100).
// Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always
// true.
return (oraclePrice.sub(strike)).div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the covered call payout structure.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// Always return 1 because option must be collateralized by 1 token.
return FixedPoint.fromUnscaledUint(1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Lockable.sol";
import "./ReentrancyAttack.sol";
// Tests reentrancy guards defined in Lockable.sol.
// Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol.
contract ReentrancyMock is Lockable {
uint256 public counter;
constructor() public {
counter = 0;
}
function callback() external nonReentrant {
_count();
}
function countAndSend(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("callback()"));
attacker.callSender(func);
}
function countAndCall(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("getCount()"));
attacker.callSender(func);
}
function countLocalRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
countLocalRecursive(n - 1);
}
}
function countThisRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1));
require(success, "ReentrancyMock: failed call");
}
}
function countLocalCall() public nonReentrant {
getCount();
}
function countThisCall() public nonReentrant {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("getCount()"));
require(success, "ReentrancyMock: failed call");
}
function getCount() public view nonReentrantView returns (uint256) {
return counter;
}
function _count() private {
counter += 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
// Tests reentrancy guards defined in Lockable.sol.
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol.
contract ReentrancyAttack {
function callSender(bytes4 data) public {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = msg.sender.call(abi.encodeWithSelector(data));
require(success, "ReentrancyAttack: failed call");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../common/FeePayer.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/implementation/ContractCreator.sol";
/**
* @title Token Deposit Box
* @notice This is a minimal example of a financial template that depends on price requests from the DVM.
* This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral.
* The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount.
* When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM.
* For simplicty, the user is constrained to have one outstanding withdrawal request at any given time.
* Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box,
* and final fees are charged on each price request.
*
* This example is intended to accompany a technical tutorial for how to integrate the DVM into a project.
* The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price
* requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework.
*
* The typical user flow would be:
* - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit
* box is therefore wETH.
* The user can subsequently make withdrawal requests for USD-denominated amounts of wETH.
* - User deposits 10 wETH into their deposit box.
* - User later requests to withdraw $100 USD of wETH.
* - DepositBox asks DVM for latest wETH/USD exchange rate.
* - DVM resolves the exchange rate at: 1 wETH is worth 200 USD.
* - DepositBox transfers 0.5 wETH to user.
*/
contract DepositBox is FeePayer, ContractCreator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
// Represents a single caller's deposit box. All collateral is held by this contract.
struct DepositBoxData {
// Requested amount of collateral, denominated in quote asset of the price identifier.
// Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then
// this represents a withdrawal request for 100 USD worth of wETH.
FixedPoint.Unsigned withdrawalRequestAmount;
// Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`.
uint256 requestPassTimestamp;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps addresses to their deposit boxes. Each address can have only one position.
mapping(address => DepositBoxData) private depositBoxes;
// Unique identifier for DVM price feed ticker.
bytes32 private priceIdentifier;
// Similar to the rawCollateral in DepositBoxData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned private rawTotalDepositBoxCollateral;
// This blocks every public state-modifying method until it flips to true, via the `initialize()` method.
bool private initialized;
/****************************************
* EVENTS *
****************************************/
event NewDepositBox(address indexed user);
event EndedDepositBox(address indexed user);
event Deposit(address indexed user, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp);
event RequestWithdrawalExecuted(
address indexed user,
uint256 indexed collateralAmount,
uint256 exchangeRate,
uint256 requestPassTimestamp
);
event RequestWithdrawalCanceled(
address indexed user,
uint256 indexed collateralAmount,
uint256 requestPassTimestamp
);
/****************************************
* MODIFIERS *
****************************************/
modifier noPendingWithdrawal(address user) {
_depositBoxHasNoPendingWithdrawal(user);
_;
}
modifier isInitialized() {
_isInitialized();
_;
}
/****************************************
* PUBLIC FUNCTIONS *
****************************************/
/**
* @notice Construct the DepositBox.
* @param _collateralAddress ERC20 token to be deposited.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited.
* The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20
* currency deposited into this account, and it is denominated in the "quote" asset on withdrawals.
* An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
address _timerAddress
)
public
ContractCreator(_finderAddress)
FeePayer(_collateralAddress, _finderAddress, _timerAddress)
nonReentrant()
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
priceIdentifier = _priceIdentifier;
}
/**
* @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required
* to make price requests in production environments.
* @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM.
* Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role
* in order to register with the `Registry`. But, its address is not known until after deployment.
*/
function initialize() public nonReentrant() {
initialized = true;
_registerContract(new address[](0), address(this));
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box.
* @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() {
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) {
emit NewDepositBox(msg.sender);
}
// Increase the individual deposit box and global collateral balance by collateral amount.
_incrementCollateralBalances(depositBoxData, collateralAmount);
emit Deposit(msg.sender, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount`
* from their position denominated in the quote asset of the price identifier, following a DVM price resolution.
* @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time.
* Only one withdrawal request can exist for the user.
* @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw.
*/
function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount)
public
isInitialized()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Update the position object for the user.
depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount;
depositBoxData.requestPassTimestamp = getCurrentTime();
emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp);
// Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee.
FixedPoint.Unsigned memory finalFee = _computeFinalFees();
require(
_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee),
"Cannot pay final fee"
);
_payFinalFees(address(this), finalFee);
// A price request is sent for the current timestamp.
_requestOraclePrice(depositBoxData.requestPassTimestamp);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution),
* withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function executeWithdrawal()
external
isInitialized()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(
depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// Get the resolved price or revert.
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
// Calculate denomated amount of collateral based on resolved exchange rate.
// Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH.
// Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH.
FixedPoint.Unsigned memory denominatedAmountToWithdraw =
depositBoxData.withdrawalRequestAmount.div(exchangeRate);
// If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data.
if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) {
denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral);
// Reset the position state as all the value has been removed after settlement.
emit EndedDepositBox(msg.sender);
}
// Decrease the individual deposit box and global collateral balance.
amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw);
emit RequestWithdrawalExecuted(
msg.sender,
amountWithdrawn.rawValue,
exchangeRate.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external isInitialized() nonReentrant() {
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(
msg.sender,
depositBoxData.withdrawalRequestAmount.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
}
/**
* @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but
* because this is a minimal demo they will simply exit silently.
*/
function emergencyShutdown() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently.
*/
function remargin() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Accessor method for a user's collateral.
* @dev This is necessary because the struct returned by the depositBoxes() method shows
* rawCollateral, which isn't a user-readable value.
* @param user address whose collateral amount is retrieved.
* @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal).
*/
function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the entire contract.
* @return the total fee-adjusted collateral amount in the contract (i.e. across all users).
*/
function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(priceIdentifier, requestedTime);
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(depositBoxData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(depositBoxData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal {
depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
depositBoxData.requestPassTimestamp = 0;
}
function _depositBoxHasNoPendingWithdrawal(address user) internal view {
require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal");
}
function _isInitialized() internal view {
require(initialized, "Uninitialized contract");
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime);
// For simplicity we don't want to deal with negative prices.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from
// which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the
// contract.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "./VotingToken.sol";
/**
* @title Migration contract for VotingTokens.
* @dev Handles migrating token holders from one token to the next.
*/
contract TokenMigrator {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
VotingToken public oldToken;
ExpandedIERC20 public newToken;
uint256 public snapshotId;
FixedPoint.Unsigned public rate;
mapping(address => bool) public hasMigrated;
/**
* @notice Construct the TokenMigrator contract.
* @dev This function triggers the snapshot upon which all migrations will be based.
* @param _rate the number of old tokens it takes to generate one new token.
* @param _oldToken address of the token being migrated from.
* @param _newToken address of the token being migrated to.
*/
constructor(
FixedPoint.Unsigned memory _rate,
address _oldToken,
address _newToken
) public {
// Prevents division by 0 in migrateTokens().
// Also it doesn’t make sense to have “0 old tokens equate to 1 new token”.
require(_rate.isGreaterThan(0), "Rate can't be 0");
rate = _rate;
newToken = ExpandedIERC20(_newToken);
oldToken = VotingToken(_oldToken);
snapshotId = oldToken.snapshot();
}
/**
* @notice Migrates the tokenHolder's old tokens to new tokens.
* @dev This function can only be called once per `tokenHolder`. Anyone can call this method
* on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier.
* @param tokenHolder address of the token holder to migrate.
*/
function migrateTokens(address tokenHolder) external {
require(!hasMigrated[tokenHolder], "Already migrated tokens");
hasMigrated[tokenHolder] = true;
FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId));
if (!oldBalance.isGreaterThan(0)) {
return;
}
FixedPoint.Unsigned memory newBalance = oldBalance.div(rate);
require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/ExpandedERC20.sol";
contract TokenSender {
function transferERC20(
address tokenAddress,
address recipientAddress,
uint256 amount
) public returns (bool) {
IERC20 token = IERC20(tokenAddress);
token.transfer(recipientAddress, amount);
return true;
}
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @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 Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./IDepositExecute.sol";
import "./IBridge.sol";
import "./IERCHandler.sol";
import "./IGenericHandler.sol";
/**
@title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions.
@author ChainSafe Systems.
*/
contract Bridge is Pausable, AccessControl {
using SafeMath for uint256;
uint8 public _chainID;
uint256 public _relayerThreshold;
uint256 public _totalRelayers;
uint256 public _totalProposals;
uint256 public _fee;
uint256 public _expiry;
enum Vote { No, Yes }
enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled }
struct Proposal {
bytes32 _resourceID;
bytes32 _dataHash;
address[] _yesVotes;
address[] _noVotes;
ProposalStatus _status;
uint256 _proposedBlock;
}
// destinationChainID => number of deposits
mapping(uint8 => uint64) public _depositCounts;
// resourceID => handler address
mapping(bytes32 => address) public _resourceIDToHandlerAddress;
// depositNonce => destinationChainID => bytes
mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords;
// destinationChainID + depositNonce => dataHash => Proposal
mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals;
// destinationChainID + depositNonce => dataHash => relayerAddress => bool
mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal;
event RelayerThresholdChanged(uint256 indexed newThreshold);
event RelayerAdded(address indexed relayer);
event RelayerRemoved(address indexed relayer);
event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce);
event ProposalEvent(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID,
bytes32 dataHash
);
event ProposalVote(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID
);
bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE");
modifier onlyAdmin() {
_onlyAdmin();
_;
}
modifier onlyAdminOrRelayer() {
_onlyAdminOrRelayer();
_;
}
modifier onlyRelayers() {
_onlyRelayers();
_;
}
function _onlyAdminOrRelayer() private {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender),
"sender is not relayer or admin"
);
}
function _onlyAdmin() private {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role");
}
function _onlyRelayers() private {
require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role");
}
/**
@notice Initializes Bridge, creates and grants {msg.sender} the admin role,
creates and grants {initialRelayers} the relayer role.
@param chainID ID of chain the Bridge contract exists on.
@param initialRelayers Addresses that should be initially granted the relayer role.
@param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed.
*/
constructor(
uint8 chainID,
address[] memory initialRelayers,
uint256 initialRelayerThreshold,
uint256 fee,
uint256 expiry
) public {
_chainID = chainID;
_relayerThreshold = initialRelayerThreshold;
_fee = fee;
_expiry = expiry;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE);
for (uint256 i; i < initialRelayers.length; i++) {
grantRole(RELAYER_ROLE, initialRelayers[i]);
_totalRelayers++;
}
}
/**
@notice Returns true if {relayer} has the relayer role.
@param relayer Address to check.
*/
function isRelayer(address relayer) external view returns (bool) {
return hasRole(RELAYER_ROLE, relayer);
}
/**
@notice Removes admin role from {msg.sender} and grants it to {newAdmin}.
@notice Only callable by an address that currently has the admin role.
@param newAdmin Address that admin role will be granted to.
*/
function renounceAdmin(address newAdmin) external onlyAdmin {
grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
@notice Pauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminPauseTransfers() external onlyAdmin {
_pause();
}
/**
@notice Unpauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminUnpauseTransfers() external onlyAdmin {
_unpause();
}
/**
@notice Modifies the number of votes required for a proposal to be considered passed.
@notice Only callable by an address that currently has the admin role.
@param newThreshold Value {_relayerThreshold} will be changed to.
@notice Emits {RelayerThresholdChanged} event.
*/
function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin {
_relayerThreshold = newThreshold;
emit RelayerThresholdChanged(newThreshold);
}
/**
@notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be added.
@notice Emits {RelayerAdded} event.
*/
function adminAddRelayer(address relayerAddress) external onlyAdmin {
require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!");
grantRole(RELAYER_ROLE, relayerAddress);
emit RelayerAdded(relayerAddress);
_totalRelayers++;
}
/**
@notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be removed.
@notice Emits {RelayerRemoved} event.
*/
function adminRemoveRelayer(address relayerAddress) external onlyAdmin {
require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!");
revokeRole(RELAYER_ROLE, relayerAddress);
emit RelayerRemoved(relayerAddress);
_totalRelayers--;
}
/**
@notice Sets a new resource for handler contracts that use the IERCHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetResource(
address handlerAddress,
bytes32 resourceID,
address tokenAddress
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IERCHandler handler = IERCHandler(handlerAddress);
handler.setResource(resourceID, tokenAddress);
}
/**
@notice Sets a new resource for handler contracts that use the IGenericHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetGenericResource(
address handlerAddress,
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IGenericHandler handler = IGenericHandler(handlerAddress);
handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice Sets a resource as burnable for handler contracts that use the IERCHandler interface.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.setBurnable(tokenAddress);
}
/**
@notice Returns a proposal.
@param originChainID Chain ID deposit originated from.
@param depositNonce ID of proposal generated by proposal's origin Bridge contract.
@param dataHash Hash of data to be provided when deposit proposal is executed.
@return Proposal which consists of:
- _dataHash Hash of data to be provided when deposit proposal is executed.
- _yesVotes Number of votes in favor of proposal.
- _noVotes Number of votes against proposal.
- _status Current status of proposal.
*/
function getProposal(
uint8 originChainID,
uint64 depositNonce,
bytes32 dataHash
) external view returns (Proposal memory) {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID);
return _proposals[nonceAndID][dataHash];
}
/**
@notice Changes deposit fee.
@notice Only callable by admin.
@param newFee Value {_fee} will be updated to.
*/
function adminChangeFee(uint256 newFee) external onlyAdmin {
require(_fee != newFee, "Current fee is equal to new fee");
_fee = newFee;
}
/**
@notice Used to manually withdraw funds from ERC safes.
@param handlerAddress Address of handler to withdraw from.
@param tokenAddress Address of token to withdraw.
@param recipient Address to withdraw tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw.
*/
function adminWithdraw(
address handlerAddress,
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.withdraw(tokenAddress, recipient, amountOrTokenID);
}
/**
@notice Initiates a transfer using a specified handler contract.
@notice Only callable when Bridge is not paused.
@param destinationChainID ID of chain deposit will be bridged to.
@param resourceID ResourceID used to find address of handler to be used for deposit.
@param data Additional data to be passed to specified handler.
@notice Emits {Deposit} event.
*/
function deposit(
uint8 destinationChainID,
bytes32 resourceID,
bytes calldata data
) external payable whenNotPaused {
require(msg.value == _fee, "Incorrect fee supplied");
address handler = _resourceIDToHandlerAddress[resourceID];
require(handler != address(0), "resourceID not mapped to handler");
uint64 depositNonce = ++_depositCounts[destinationChainID];
_depositRecords[depositNonce][destinationChainID] = data;
IDepositExecute depositHandler = IDepositExecute(handler);
depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data);
emit Deposit(destinationChainID, resourceID, depositNonce);
}
/**
@notice When called, {msg.sender} will be marked as voting in favor of proposal.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data provided when deposit was made.
@notice Proposal must not have already been passed or executed.
@notice {msg.sender} must not have already voted on proposal.
@notice Emits {ProposalEvent} event with status indicating the proposal status.
@notice Emits {ProposalVote} event.
*/
function voteProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 resourceID,
bytes32 dataHash
) external onlyRelayers whenNotPaused {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID");
require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled");
require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted");
if (uint256(proposal._status) == 0) {
++_totalProposals;
_proposals[nonceAndID][dataHash] = Proposal({
_resourceID: resourceID,
_dataHash: dataHash,
_yesVotes: new address[](1),
_noVotes: new address[](0),
_status: ProposalStatus.Active,
_proposedBlock: block.number
});
proposal._yesVotes[0] = msg.sender;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash);
} else {
if (block.number.sub(proposal._proposedBlock) > _expiry) {
// if the number of blocks that has passed since this proposal was
// submitted exceeds the expiry threshold set, cancel the proposal
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash);
} else {
require(dataHash == proposal._dataHash, "datahash mismatch");
proposal._yesVotes.push(msg.sender);
}
}
if (proposal._status != ProposalStatus.Cancelled) {
_hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true;
emit ProposalVote(chainID, depositNonce, proposal._status, resourceID);
// If _depositThreshold is set to 1, then auto finalize
// or if _relayerThreshold has been exceeded
if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) {
proposal._status = ProposalStatus.Passed;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash);
}
}
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data originally provided when deposit was made.
@notice Proposal must be past expiry threshold.
@notice Emits {ProposalEvent} event with status {Cancelled}.
*/
function cancelProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 dataHash
) public onlyAdminOrRelayer {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled");
require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold");
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash);
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param resourceID ResourceID to be used when making deposits.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param data Data originally provided when deposit was made.
@notice Proposal must have Passed status.
@notice Hash of {data} must equal proposal's {dataHash}.
@notice Emits {ProposalEvent} event with status {Executed}.
*/
function executeProposal(
uint8 chainID,
uint64 depositNonce,
bytes calldata data,
bytes32 resourceID
) external onlyRelayers whenNotPaused {
address handler = _resourceIDToHandlerAddress[resourceID];
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
bytes32 dataHash = keccak256(abi.encodePacked(handler, data));
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Inactive, "proposal is not active");
require(proposal._status == ProposalStatus.Passed, "proposal already transferred");
require(dataHash == proposal._dataHash, "data doesn't match datahash");
proposal._status = ProposalStatus.Executed;
IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]);
depositHandler.executeProposal(proposal._resourceID, data);
emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash);
}
/**
@notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1.
This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0.
@param addrs Array of addresses to transfer {amounts} to.
@param amounts Array of amonuts to transfer to {addrs}.
*/
function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin {
for (uint256 i = 0; i < addrs.length; i++) {
addrs[i].transfer(amounts[i]);
}
}
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _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 AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `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());
}
}
}
pragma solidity ^0.6.0;
/**
@title Interface for handler contracts that support deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IDepositExecute {
/**
@notice It is intended that deposit are made using the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of additional data needed for a specific deposit.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external;
/**
@notice It is intended that proposals are executed by the Bridge contract.
@param data Consists of additional data needed for a specific deposit execution.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for Bridge contract.
@author ChainSafe Systems.
*/
interface IBridge {
/**
@notice Exposing getter for {_chainID} instead of forcing the use of call.
@return uint8 The {_chainID} that is currently set for the Bridge contract.
*/
function _chainID() external returns (uint8);
}
pragma solidity ^0.6.0;
/**
@title Interface to be used with handlers that support ERC20s and ERC721s.
@author ChainSafe Systems.
*/
interface IERCHandler {
/**
@notice Correlates {resourceID} with {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function setResource(bytes32 resourceID, address contractAddress) external;
/**
@notice Marks {contractAddress} as mintable/burnable.
@param contractAddress Address of contract to be used when making or executing deposits.
*/
function setBurnable(address contractAddress) external;
/**
@notice Used to manually release funds from ERC safes.
@param tokenAddress Address of token contract to release.
@param recipient Address to release tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release.
*/
function withdraw(
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for handler that handles generic deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IGenericHandler {
/**
@notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external;
}
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;
pragma experimental ABIEncoderV2;
import "./IGenericHandler.sol";
/**
@title Handles generic deposits and deposit executions.
@author ChainSafe Systems.
@notice This contract is intended to be used with the Bridge contract.
*/
contract GenericHandler is IGenericHandler {
address public _bridgeAddress;
struct DepositRecord {
uint8 _destinationChainID;
address _depositer;
bytes32 _resourceID;
bytes _metaData;
}
// depositNonce => Deposit Record
mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords;
// resourceID => contract address
mapping(bytes32 => address) public _resourceIDToContractAddress;
// contract address => resourceID
mapping(address => bytes32) public _contractAddressToResourceID;
// contract address => deposit function signature
mapping(address => bytes4) public _contractAddressToDepositFunctionSignature;
// contract address => execute proposal function signature
mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature;
// token contract address => is whitelisted
mapping(address => bool) public _contractWhitelist;
modifier onlyBridge() {
_onlyBridge();
_;
}
function _onlyBridge() private {
require(msg.sender == _bridgeAddress, "sender must be bridge contract");
}
/**
@param bridgeAddress Contract address of previously deployed Bridge.
@param initialResourceIDs Resource IDs used to identify a specific contract address.
These are the Resource IDs this contract will initially support.
@param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be
called to perform deposit and execution calls.
@param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {deposit}
@param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {executeProposal}
@dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures},
and {initialExecuteFunctionSignatures} must all have the same length. Also,
values must be ordered in the way that that index x of any mentioned array
must be intended for value x of any other array, e.g. {initialContractAddresses}[0]
is the intended address for {initialDepositFunctionSignatures}[0].
*/
constructor(
address bridgeAddress,
bytes32[] memory initialResourceIDs,
address[] memory initialContractAddresses,
bytes4[] memory initialDepositFunctionSignatures,
bytes4[] memory initialExecuteFunctionSignatures
) public {
require(
initialResourceIDs.length == initialContractAddresses.length,
"initialResourceIDs and initialContractAddresses len mismatch"
);
require(
initialContractAddresses.length == initialDepositFunctionSignatures.length,
"provided contract addresses and function signatures len mismatch"
);
require(
initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length,
"provided deposit and execute function signatures len mismatch"
);
_bridgeAddress = bridgeAddress;
for (uint256 i = 0; i < initialResourceIDs.length; i++) {
_setResource(
initialResourceIDs[i],
initialContractAddresses[i],
initialDepositFunctionSignatures[i],
initialExecuteFunctionSignatures[i]
);
}
}
/**
@param depositNonce This ID will have been generated by the Bridge contract.
@param destId ID of chain deposit will be bridged to.
@return DepositRecord which consists of:
- _destinationChainID ChainID deposited tokens are intended to end up on.
- _resourceID ResourceID used when {deposit} was executed.
- _depositer Address that initially called {deposit} in the Bridge contract.
- _metaData Data to be passed to method executed in corresponding {resourceID} contract.
*/
function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) {
return _depositRecords[destId][depositNonce];
}
/**
@notice First verifies {_resourceIDToContractAddress}[{resourceID}] and
{_contractAddressToResourceID}[{contractAddress}] are not already set,
then sets {_resourceIDToContractAddress} with {contractAddress},
{_contractAddressToResourceID} with {resourceID},
{_contractAddressToDepositFunctionSignature} with {depositFunctionSig},
{_contractAddressToExecuteFunctionSignature} with {executeFunctionSig},
and {_contractWhitelist} to true for {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external override onlyBridge {
_setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice A deposit is initiatied by making a deposit in the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 64 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external onlyBridge {
bytes32 lenMetadata;
bytes memory metadata;
assembly {
// Load length of metadata from data + 64
lenMetadata := calldataload(0xC4)
// Load free memory pointer
metadata := mload(0x40)
mstore(0x40, add(0x20, add(metadata, lenMetadata)))
// func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) +
// bytes length (32) + resourceId (32) + length (32) = 0xC4
calldatacopy(
metadata, // copy to metadata
0xC4, // copy from calldata after metadata length declaration @0xC4
sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up))
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metadata);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
_depositRecords[destinationChainID][depositNonce] = DepositRecord(
destinationChainID,
depositer,
resourceID,
metadata
);
}
/**
@notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract.
@param data Consists of {resourceID}, {lenMetaData}, and {metaData}.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 32 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge {
bytes memory metaData;
assembly {
// metadata has variable length
// load free memory pointer to store metadata
metaData := mload(0x40)
// first 32 bytes of variable length in storage refer to length
let lenMeta := calldataload(0x64)
mstore(0x40, add(0x60, add(metaData, lenMeta)))
// in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params
calldatacopy(
metaData, // copy to metaData
0x64, // copy from calldata after data length declaration at 0x64
sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64)
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metaData);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
}
function _setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) internal {
_resourceIDToContractAddress[resourceID] = contractAddress;
_contractAddressToResourceID[contractAddress] = resourceID;
_contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig;
_contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig;
_contractWhitelist[contractAddress] = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../interfaces/VotingInterface.sol";
import "../VoteTiming.sol";
// Wraps the library VoteTiming for testing purposes.
contract VoteTimingTest {
using VoteTiming for VoteTiming.Data;
VoteTiming.Data public voteTiming;
constructor(uint256 phaseLength) public {
wrapInit(phaseLength);
}
function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) {
return voteTiming.computeCurrentRoundId(currentTime);
}
function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) {
return voteTiming.computeCurrentPhase(currentTime);
}
function wrapInit(uint256 phaseLength) public {
voteTiming.init(phaseLength);
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/lib/contracts/libraries/Babylonian.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/lib/contracts/libraries/FullMath.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
/**
* @title UniswapBroker
* @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual
* synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically
* swap and move a uniswap market.
*/
contract UniswapBroker {
using SafeMath for uint256;
/**
* @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as
* possible to the truePrice.
* @dev True price is expressed in the ratio of token A to token B.
* @dev The caller must approve this contract to spend whichever token is intended to be swapped.
* @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param uniswapFactory address of the uniswap factory used to fetch current pair reserves.
* @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure
* out which tokens need to be exchanged to move the market to the desired "true" price.
* @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price
* and the 1st value is the the denominator of the true price.
* @param maxSpendTokens array of unit to represent the max to spend in the two tokens.
* @param to recipient of the trade proceeds.
* @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert.
*/
function swapToPrice(
bool tradingAsEOA,
address uniswapRouter,
address uniswapFactory,
address[2] memory swappedTokens,
uint256[2] memory truePriceTokens,
uint256[2] memory maxSpendTokens,
address to,
uint256 deadline
) public {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
// true price is expressed as a ratio, so both values must be non-zero
require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE");
// caller can specify 0 for either if they wish to swap in only one direction, but not both
require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND");
bool aToB;
uint256 amountIn;
{
(uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]);
(aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB);
}
require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN");
// spend up to the allowance of the token in
uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1];
if (amountIn > maxSpend) {
amountIn = maxSpend;
}
address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1];
address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0];
TransferHelper.safeApprove(tokenIn, address(router), amountIn);
if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn);
address[] memory path = new address[](2);
path[0] = tokenIn;
path[1] = tokenOut;
router.swapExactTokensForTokens(
amountIn,
0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests.
path,
to,
deadline
);
}
/**
* @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the
* uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move
* the pool price to be equal to the true price.
* @dev Note that this method uses the Babylonian square root method which has a small margin of error which will
* result in a small over or under estimation on the size of the trade needed.
* @param truePriceTokenA the nominator of the true price.
* @param truePriceTokenB the denominator of the true price.
* @param reserveA number of token A in the pair reserves
* @param reserveB number of token B in the pair reserves
*/
//
function computeTradeToMoveMarket(
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 reserveA,
uint256 reserveB
) public pure returns (bool aToB, uint256 amountIn) {
aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA;
uint256 invariant = reserveA.mul(reserveB);
// The trade ∆a of token a required to move the market to some desired price P' from the current price P can be
// found with ∆a=(kP')^1/2-Ra.
uint256 leftSide =
Babylonian.sqrt(
FullMath.mulDiv(
invariant,
aToB ? truePriceTokenA : truePriceTokenB,
aToB ? truePriceTokenB : truePriceTokenA
)
);
uint256 rightSide = (aToB ? reserveA : reserveB);
if (leftSide < rightSide) return (false, 0);
// compute the amount that must be sent to move the price back to the true price.
amountIn = leftSide.sub(rightSide);
}
// The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol
// We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound
// to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so
// unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant
// handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker
// are simply moved here to maintain truffle support.
function getReserves(
address factory,
address tokenA,
address tokenB
) public view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "UniswapV2Library: 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(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
);
}
}
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;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity >=0.4.0;
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
}
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.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title ReserveCurrencyLiquidator
* @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of
* financial contracts. Is assumed to be called by a DSProxy which holds reserve currency.
*/
contract ReserveCurrencyLiquidator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to
* liquidate a position within one transaction.
* @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending
* liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has
* passed liveness. At this point the position can be manually unwound.
* @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted.
* These existing tokens will be used first before any swaps or mints are done.
* @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough
* collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param financialContract address of the financial contract on which the liquidation is occurring.
* @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy.
* @param liquidatedSponsor address of the sponsor to be liquidated.
* @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage.
* @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt.
* @param deadline abort the trade and liquidation if the transaction is mined after this timestamp.
**/
function swapMintLiquidate(
address uniswapRouter,
address financialContract,
address reserveCurrency,
address liquidatedSponsor,
FixedPoint.Unsigned calldata maxReserveTokenSpent,
FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
) public {
IFinancialContract fc = IFinancialContract(financialContract);
// 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already
// has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall).
FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc));
// 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics.
FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding());
FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr);
// 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any
// collateral needed to mint the token short fall.
FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall);
// 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this
// will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0.
FixedPoint.Unsigned memory collateralToBePurchased =
subOrZero(totalCollateralRequired, getCollateralBalance(fc));
// 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall.
// Note the path assumes a direct route from the reserve currency to the collateral currency.
if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
address[] memory path = new address[](2);
path[0] = reserveCurrency;
path[1] = fc.collateralCurrency();
TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue);
router.swapTokensForExactTokens(
collateralToBePurchased.rawValue,
maxReserveTokenSpent.rawValue,
path,
address(this),
deadline
);
}
// 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve
// or not enough collateral in the contract) the script should try to liquidate as much as it can regardless.
// Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall
// as the maximum tokens that could be liquidated at the current GCR.
if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) {
totalCollateralRequired = getCollateralBalance(fc);
collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc));
tokenShortfall = collateralToMintShortfall.divCeil(gcr);
}
// 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR.
// If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral
// currency as this is needed to pay the final fee in the liquidation tx.
TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue);
if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall);
// The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full
// token token balance at this point if there was a shortfall.
FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate;
if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc);
// 6. Liquidate position with newly minted synthetics.
TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue);
fc.createLiquidation(
liquidatedSponsor,
minCollateralPerTokenLiquidated,
maxCollateralPerTokenLiquidated,
liquidatableTokens,
deadline
);
}
// Helper method to work around subtraction overflow in the case of: a - b with b > a.
function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b)
internal
pure
returns (FixedPoint.Unsigned memory)
{
return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b);
}
// Helper method to return the current final fee for a given financial contract instance.
function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency());
}
// Helper method to return the collateral balance of this contract.
function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this)));
}
// Helper method to return the synthetic balance of this contract.
function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this)));
}
}
// Define some simple interfaces for dealing with UMA contracts.
interface IFinancialContract {
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
FixedPoint.Unsigned rawCollateral;
uint256 transferPositionRequestPassTimestamp;
}
function positions(address sponsor) external returns (PositionData memory);
function collateralCurrency() external returns (address);
function tokenCurrency() external returns (address);
function finder() external returns (address);
function pfc() external returns (FixedPoint.Unsigned memory);
function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory);
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external;
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
);
}
interface IStore {
function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory);
}
interface IFinder {
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
// Simple contract used to redeem tokens using a DSProxy from an emp.
contract TokenRedeemer {
function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens)
public
returns (FixedPoint.Unsigned memory)
{
IFinancialContract fc = IFinancialContract(financialContractAddress);
TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue);
return fc.redeem(numTokens);
}
}
interface IFinancialContract {
function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn);
function tokenCurrency() external returns (address);
}
/*
MultiRoleTest contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/MultiRole.sol";
// The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes.
contract MultiRoleTest is MultiRole {
function createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] calldata initialMembers
) external {
_createSharedRole(roleId, managingRoleId, initialMembers);
}
function createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) external {
_createExclusiveRole(roleId, managingRoleId, initialMember);
}
// solhint-disable-next-line no-empty-blocks
function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Testable.sol";
// TestableTest is derived from the abstract contract Testable for testing purposes.
contract TestableTest is Testable {
// solhint-disable-next-line no-empty-blocks
constructor(address _timerAddress) public Testable(_timerAddress) {}
function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) {
// solhint-disable-next-line not-rely-on-time
return (getCurrentTime(), now);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/VaultInterface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Mock for yearn-style vaults for use in tests.
*/
contract VaultMock is VaultInterface {
IERC20 public override token;
uint256 private pricePerFullShare = 0;
constructor(IERC20 _token) public {
token = _token;
}
function getPricePerFullShare() external view override returns (uint256) {
return pricePerFullShare;
}
function setPricePerFullShare(uint256 _pricePerFullShare) external {
pricePerFullShare = _pricePerFullShare;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Interface for Yearn-style vaults.
* @dev This only contains the methods/events that we use in our contracts or offchain infrastructure.
*/
abstract contract VaultInterface {
// Return the underlying token.
function token() external view virtual returns (IERC20);
// Gets the number of return tokens that a "share" of this vault is worth.
function getPricePerFullShare() external view virtual returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Implements only the required ERC20 methods. This contract is used
* test how contracts handle ERC20 contracts that have not implemented `decimals()`
* @dev Mostly copied from Consensys EIP-20 implementation:
* https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol
*/
contract BasicERC20 is IERC20 {
uint256 private constant MAX_UINT256 = 2**256 - 1;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
uint256 private _totalSupply;
constructor(uint256 _initialAmount) public {
balances[msg.sender] = _initialAmount;
_totalSupply = _initialAmount;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function transfer(address _to, uint256 _value) public override returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) public override returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public override returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ResultComputation.sol";
import "../../../common/implementation/FixedPoint.sol";
// Wraps the library ResultComputation for testing purposes.
contract ResultComputationTest {
using ResultComputation for ResultComputation.Data;
ResultComputation.Data public data;
function wrapAddVote(int256 votePrice, uint256 numberTokens) external {
data.addVote(votePrice, FixedPoint.Unsigned(numberTokens));
}
function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) {
return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold));
}
function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) {
return data.wasVoteCorrect(revealHash);
}
function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) {
return data.getTotalCorrectlyVotedTokens().rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Voting.sol";
import "../../../common/implementation/FixedPoint.sol";
// Test contract used to access internal variables in the Voting contract.
contract VotingTest is Voting {
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
)
public
Voting(
_phaseLength,
_gatPercentage,
_inflationRate,
_rewardsExpirationTimeout,
_votingToken,
_finder,
_timerAddress
)
{}
function getPendingPriceRequestsArray() external view returns (bytes32[] memory) {
return pendingPriceRequests;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract UnsignedFixedPointTest {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeMath for uint256;
function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) {
return FixedPoint.fromUnscaledUint(a).rawValue;
}
function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(b);
}
function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b));
}
function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMin(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMax(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue;
}
function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(b).rawValue;
}
function wrapSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.sub(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(b).rawValue;
}
function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(b).rawValue;
}
function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue;
}
function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(b).rawValue;
}
function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.div(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract SignedFixedPointTest {
using FixedPoint for FixedPoint.Signed;
using FixedPoint for int256;
using SafeMath for int256;
function wrapFromSigned(int256 a) external pure returns (uint256) {
return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue;
}
function wrapFromUnsigned(uint256 a) external pure returns (int256) {
return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue;
}
function wrapFromUnscaledInt(int256 a) external pure returns (int256) {
return FixedPoint.fromUnscaledInt(a).rawValue;
}
function wrapIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b));
}
function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(b);
}
function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b));
}
function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b));
}
function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Signed(b));
}
function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMin(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue;
}
function wrapMax(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue;
}
function wrapAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(b).rawValue;
}
function wrapSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) {
return a.sub(FixedPoint.Signed(b)).rawValue;
}
function wrapMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue;
}
function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(b).rawValue;
}
function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue;
}
function wrapDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue;
}
function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(b).rawValue;
}
function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) {
return a.div(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(int256 a, uint256 b) external pure returns (int256) {
return FixedPoint.Signed(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Simple Perpetual Mock to serve trivial functions
*/
contract PerpetualMock {
struct FundingRate {
FixedPoint.Signed rate;
bytes32 identifier;
FixedPoint.Unsigned cumulativeMultiplier;
uint256 updateTime;
uint256 applicationTime;
uint256 proposalTime;
}
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
FundingRate public fundingRate;
// Interface functions required to be implemented in order for an instance of this contract to be passed into the
// off-chain FinancialContractClient helper module:
FixedPoint.Unsigned public collateralRequirement;
uint256 public liquidationLiveness;
FixedPoint.Unsigned public cumulativeFeeMultiplier;
mapping(address => uint256) public positions;
mapping(address => uint256) public liquidations;
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition();
event LiquidationCreated();
function getCurrentTime() public view returns (uint256) {
return now;
}
// Public methods that are useful for tests:
function setFundingRate(FundingRate memory _fundingRate) external {
fundingRate = _fundingRate;
}
function applyFundingRate() external {
fundingRate.applicationTime = block.timestamp;
// Simplified rate calcualtion.
// multiplier = multiplier * (1 + rate)
fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul(
FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate))
);
}
}
|
Whether `a` is less than or equal to `b`. a a uint256. b a FixedPoint. return True if `a <= b`, or False./
|
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
| 98,863
|
pragma solidity ^0.5.2;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./FlightSuretyDataInterface.sol";
contract FlightSuretyApp {
using SafeMath for uint256;
using SafeMath for uint8;
/* ============================================================================================== */
/* DATA STRUCTURES */
/* ============================================================================================== */
struct Flight {
bool isRegistered;
string name;
uint256 departure;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
/* ---------------------------------------------------------------------------------------------- */
/* ============================================================================================== */
/* DATA CONSTANTS&VARIABLES */
/* ============================================================================================== */
// 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;
/// Constant of allowed number of airline to be registered BY_MEDIATION
uint8 private constant MEDIATION_REGISTERATION_LIMET = 4;
/// Constant of persantage of active airline most votes for a new registered airline
uint8 private constant PERSANTAGE_OF_VOTER = 50;
/// constant of credit 1.5X if flight lates on airline fuiler
uint8 private constant CREDIT_RATE = 150;
/// Account used to deploy contract
address private contractOwner;
///
mapping(bytes32 => Flight) private flights;
///
FlightSuretyDataInterface flightSuretyData;
/* ---------------------------------------------------------------------------------------------- */
/* ============================================================================================== */
/* CONSTRUCTOR&FALLBACK FUNCTION */
/* ============================================================================================== */
/// @dev Constructor
/// The deploying account becomes contractOwner
constructor
(
address payable dataContractAddress
)
public
{
flightSuretyData = FlightSuretyDataInterface(dataContractAddress);
contractOwner = msg.sender;
}
/* ---------------------------------------------------------------------------------------------- */
/* ============================================================================================== */
/* EVENT DEFINITIONS */
/* ============================================================================================== */
event AirlineRegistered(address airlineAddress);
event AirlineFunded(address airlineAddress);
event VotedForAirline(address airlineAddress, address voterAddress);
event FlightRegistered(bytes32 flightKey);
event FlightTicketsAdded(uint[] ticketsNumbers, bytes32 flightKey);
event InsuranceBought(bytes32 insuranceKey);
event CreditDrawed(uint value);
/* ---------------------------------------------------------------------------------------------- */
/* ============================================================================================== */
/* FUNCTION MODIFIERS */
/* ============================================================================================== */
/// @dev Modifier that requires the "operational" boolean variable to be "true"
/// This is used on all state changing functions to pause the contract in the event
modifier requireIsOperational()
{
// Modify to call data contract's status
require(isOperational(), "Data contract is currently not operational");
require(flightSuretyData.isAuthorized(address(this)), "This app contract is currently not authorized");
_;
}
/// @dev Modifier that requires the "ContractOwner" account to be the function caller
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/// @dev Modifier that checks if airline address not existing in data
modifier requireNotExistAirline(address airlineAddress) {
require(!flightSuretyData.isAirlineExist(airlineAddress), "Cannot register a registered airline address");
_;
}
/// @dev Modifier that checks if airline address existing in data
modifier requireExistAirline(address airlineAddress) {
require(flightSuretyData.isAirlineExist(airlineAddress), "Airline address not existing");
_;
}
/// @dev Modifier that checks if airline address has registered
modifier requireIsAirlineRegistered(address airlineAddress) {
require(isAirlineRegistered(airlineAddress), "Airline not registered, or has been funded allready");
_;
}
/// @dev Modifier that checks if airline address waiting for votes
modifier requireIsAirlineWaitingForVotes(address airlineAddress) {
require(isAirlineWaitingForVotes(airlineAddress), "Airline not waiting for votes");
_;
}
/// @dev Modifier that checks if airline address has funded
modifier requireIsAirlineFunded(address airlineAddress) {
require(isAirlineFunded(airlineAddress), "Airline not funded");
_;
}
/// @dev Modifier checks if a voter airlin has allready votes for an airline
modifier requireNewVoter(address airline, address voter) {
require(!flightSuretyData.isVotedForRegisteringAirline(airline, voter), "You voted for this airline");
_;
}
/* ---------------------------------------------------------------------------------------------- */
/* ============================================================================================== */
/* SMART CONTRACT FUNCTIONS */
/* ============================================================================================== */
/// @dev Add an airline to the registration queue
function registerAirline
(
address airlineAddress,
string calldata name
)
external
requireIsOperational()
requireNotExistAirline(airlineAddress)
{
if (flightSuretyData.getRegistrationType() == FlightSuretyDataInterface.RegisterationType.BY_MEDIATION) {
require(isAirlineFunded(msg.sender), "Airline should be funded to add new airline");
flightSuretyData.registerAirline(
airlineAddress,
name,
FlightSuretyDataInterface.AirlineRegisterationState.Registered
);
if (flightSuretyData.getNumberOfRegisteredAirlines() == MEDIATION_REGISTERATION_LIMET)
flightSuretyData.setRegistrationType(FlightSuretyDataInterface.RegisterationType.BY_VOTERS);
} else {
require(msg.sender == airlineAddress, "Only the owner of registring account can register himself");
flightSuretyData.registerAirline(
airlineAddress,
name,
FlightSuretyDataInterface.AirlineRegisterationState.WaitingForVotes
);
}
emit AirlineRegistered(airlineAddress);
}
/// @dev Funding a caller address
/// @notice Caller airline should be in registered state to call this methode
function fundMyAirline()
external
payable
requireIsOperational()
requireExistAirline(msg.sender)
requireIsAirlineRegistered(msg.sender)
{
require(msg.value >= 10 ether, "Funding must be 10 Ether");
flightSuretyData.fund.value(msg.value)(msg.sender);
///(bool success, ) = address(flightSuretyData).call.value(10 ether)(abi.encodeWithSignature("empty()"));
///require(success, "somthing went rong, try again");
emit AirlineFunded(msg.sender);
}
/// @dev Votes for an airline registrineg address
/// @notice Caller address and airline to votes should meet a specific need to complete this methodes
/// @param airlineAddress Airline address to vote for
function voteForAirline(address airlineAddress)
external
requireIsOperational
requireExistAirline(airlineAddress)
requireIsAirlineWaitingForVotes(airlineAddress)
requireIsAirlineFunded(msg.sender)
requireNewVoter(airlineAddress, msg.sender)
{
flightSuretyData.addAirlineVote(airlineAddress, msg.sender);
//check if airline passes consensus voters
uint oddGarde = flightSuretyData.getNumberOfActiveAirlines().mod(2);
uint consensusLimtNumber = flightSuretyData.getNumberOfActiveAirlines().mul(PERSANTAGE_OF_VOTER).div(100).add(oddGarde);
if ((flightSuretyData.getAirlineVotes(airlineAddress)) >= consensusLimtNumber) {
flightSuretyData.setAirlineState(
airlineAddress,
FlightSuretyDataInterface.AirlineRegisterationState.Registered
);
}
emit VotedForAirline(airlineAddress, msg.sender);
}
/// @dev Register a future flight for insuring.
function registerFlight
(
string calldata flightName,
uint256 departure,
uint256[] calldata ticketNumbers
)
external
requireIsOperational
requireIsAirlineFunded(msg.sender)
{
bytes32 flightKey = getFlightKey(msg.sender, flightName, departure);
require(!flights[flightKey].isRegistered, "Flight allredy registered");
flights[flightKey] = Flight ({
isRegistered: true,
name: flightName,
departure: departure,
statusCode: 0,
updatedTimestamp: now,
airline: msg.sender
});
flightSuretyData.addFlightKeyToAirline(msg.sender, flightKey);
for (uint i = 0; i < ticketNumbers.length; i++) {
flightSuretyData.buildFlightInsurance(msg.sender, flightKey, ticketNumbers[i]);
}
emit FlightRegistered(flightKey);
emit FlightTicketsAdded(ticketNumbers, flightKey);
}
function addFlightTickets
(
string calldata flightName,
uint256 departure,
uint256[] calldata ticketNumbers
)
external
requireIsOperational
requireIsAirlineFunded(msg.sender)
{
bytes32 flightKey = getFlightKey(msg.sender, flightName, departure);
require(flights[flightKey].isRegistered, "Flight not registered");
for (uint i = 0; i < ticketNumbers.length; i++) {
flightSuretyData.buildFlightInsurance(msg.sender, flightKey, ticketNumbers[i]);
}
flights[flightKey].updatedTimestamp = now;
emit FlightTicketsAdded(ticketNumbers, flightKey);
}
function purchaseInsurance
(
address airlineAddress,
string calldata flightName,
uint256 departure,
uint256 ticketNumber
)
external
payable
requireIsOperational
{
require(msg.value > 0, "Insurance can accept more than 0");
require(msg.value <= 1 ether, "Insurance can accept less than 1 ether");
bytes32 flightKey = getFlightKey(airlineAddress, flightName, departure);
bytes32 insuranceKey = getInsuranceKey(flightKey, ticketNumber);
flightSuretyData.buyInsurance.value(msg.value)(msg.sender, insuranceKey);
emit InsuranceBought(insuranceKey);
}
function withdrawCredit
(
address airlineAddress,
string calldata flightName,
uint256 departure,
uint256 ticketNumber
)
external
requireIsOperational
{
bytes32 flightKey = getFlightKey(airlineAddress, flightName, departure);
bytes32 insuranceKey = getInsuranceKey(flightKey, ticketNumber);
(
address insuree,
,
uint value,
,
) = flightSuretyData.fetchInsuranceData(insuranceKey);
require(insuree == msg.sender, "You do not own this insurance");
flightSuretyData.payInsuree(insuranceKey);
emit CreditDrawed(value);
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus
(
address airline,
string calldata flight,
uint256 timestamp
)
external
requireIsOperational
{
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(
abi.encodePacked(
index,
airline,
flight,
timestamp
)
);
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
emit OracleRequest(
index,
airline,
flight,
timestamp
);
}
function getAirline(address airlineAddress)
external
view
returns(
bool isExist,
string memory name,
FlightSuretyDataInterface.AirlineRegisterationState state,
uint numberOfRegistringVotes,
uint numberOfRemovingVotes,
uint8 failureRate,
bytes32[] memory flightKeys,
uint numberOfInsurance
)
{
return flightSuretyData.fetchAirlineData(airlineAddress);
}
function getFlight
(
address airlineAddress,
string calldata flightName,
uint departureTime
)
external
view
returns(
bool isRegistered,
string memory name,
uint256 departure,
uint8 statusCode,
uint256 updatedTimestamp,
address airline
)
{
bytes32 flightKey = getFlightKey(airlineAddress, flightName, departureTime);
return (
flights[flightKey].isRegistered,
flights[flightKey].name,
flights[flightKey].departure,
flights[flightKey].statusCode,
flights[flightKey].updatedTimestamp,
flights[flightKey].airline
);
}
function getInsurance
(
address airlineAddress,
string calldata flightName,
uint departureTime,
uint _ticketNumber
)
external
view
returns(
address buyer,
address airline,
uint value,
uint ticketNumber,
FlightSuretyDataInterface.InsuranceState state
)
{
bytes32 flightKey = getFlightKey(airlineAddress, flightName, departureTime);
bytes32 insuranceKey = getInsuranceKey(flightKey, _ticketNumber);
return flightSuretyData.fetchInsuranceData(insuranceKey);
}
function getInsuranceKeysOfPassanger(address _address)
external
view
returns(bytes32[] memory)
{
return flightSuretyData.fetchPasengerInsurances(_address);
}
function getInsuranceKeysOfFlight
(
address airlineAddress,
string calldata flightName,
uint departureTime
)
external
view
returns(bytes32[] memory)
{
bytes32 flightKey = getFlightKey(airlineAddress, flightName, departureTime);
return flightSuretyData.fetchFlightInsurances(flightKey);
}
/* ---------------------------------------------------------------------------------------------- */
/* ============================================================================================== */
/* 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; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// 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
requireIsOperational
{
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
address payable dataContract = address(uint160(address(flightSuretyData)));
dataContract.transfer(msg.value);
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: indexes
});
}
function getMyIndexes()
external
view
requireIsOperational
returns(uint8[3] memory)
{
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 calldata flight,
uint256 timestamp,
uint8 statusCode
)
external
requireIsOperational
{
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) {
oracleResponses[key].isOpen = false;
emit FlightStatusInfo(
airline,
flight,
timestamp,
statusCode
);
// Handle flight status as appropriate
processFlightStatus(
airline,
flight,
timestamp,
statusCode
);
}
}
/* ---------------------------------------------------------------------------------------------- */
/* ============================================================================================== */
/* UTILITY FUNCTIONS */
/* ============================================================================================== */
/// @dev Get operating status of data contract
/// @return A bool that is the current operating status of data contract
function isOperational()
public
view
returns(bool)
{
return flightSuretyData.isOperational();
}
/// @dev Check if airline is waiting for votes
/// @param airlineAddress airline address to check
/// @return A boolean if airline state is `WaitingForVotes`
function isAirlineWaitingForVotes(address airlineAddress)
public
view
returns(bool)
{
return(
flightSuretyData.getAirlineState(airlineAddress) == FlightSuretyDataInterface.AirlineRegisterationState.WaitingForVotes
);
}
/// @dev Check if airline is registered
/// @param airlineAddress airline address to check
/// @return A boolean if airline state is `Registered`
function isAirlineRegistered(address airlineAddress)
public
view
returns(bool)
{
return(
flightSuretyData.getAirlineState(airlineAddress) == FlightSuretyDataInterface.AirlineRegisterationState.Registered
);
}
/// @dev Check if airline has funded
/// @param airlineAddress airline address to check
/// @return A boolean if airline state is `Funded`
function isAirlineFunded(address airlineAddress)
public
view
returns(bool)
{
return(
flightSuretyData.getAirlineState(airlineAddress) == FlightSuretyDataInterface.AirlineRegisterationState.Funded
);
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
function getInsuranceKey
(
bytes32 flightKey,
uint ticketNumber
)
internal
pure
returns(bytes32)
{
return keccak256(abi.encodePacked(flightKey, ticketNumber));
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes(address account)
internal
returns(uint8[3] memory)
{
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;
}
/// @dev Called after oracle has updated flight status
function processFlightStatus
(
address airline,
string memory flight,
uint256 timestamp,
uint8 statusCode
)
internal
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
flights[flightKey].statusCode = statusCode;
if (statusCode == STATUS_CODE_LATE_AIRLINE)
flightSuretyData.creditInsurees(flightKey, CREDIT_RATE);
else
flightSuretyData.creditInsurees(flightKey, 0);
}
/* ---------------------------------------------------------------------------------------------- */
}
|
Check if airline is registered airlineAddress airline address to check return A boolean if airline state is `Registered`
|
function isAirlineRegistered(address airlineAddress)
public
view
returns(bool)
{
return(
flightSuretyData.getAirlineState(airlineAddress) == FlightSuretyDataInterface.AirlineRegisterationState.Registered
);
}
| 2,544,103
|
./partial_match/1/0xdefac16715671b7b6aeeFE012125f1E19Ee4b7d7/sources/_Voting.sol
|
Gets the number of votes a suggestion has received. Blockwell Exclusive (Intellectual Property that lives on-chain via Smart License)/
|
function getVotes(uint256 suggestionId) public view returns (uint256) {
return suggestions[suggestionId].votes;
}
| 2,630,718
|
./full_match/5/0x8031255AbD1be24cf4D9e9256b5d1f1E65dcb2D1/sources/contracts/StakeChain.sol
|
Get the status of maximum stake (true => paused / false => unpaused)./
|
function getMaximumStakeStatus(uint256 poolId) public view returns (bool) {
return _maximumStakeActive[poolId];
}
| 1,953,243
|
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "./SafeMath.sol";
import "./Events.sol";
import "./Ownable.sol";
import "./Upgradeable.sol";
import "./UpgradeableMaster.sol";
/// @title Upgrade Gatekeeper Contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract UpgradeGatekeeper is UpgradeEvents, Ownable {
using SafeMath for uint256;
/// @notice Array of addresses of upgradeable contracts managed by the gatekeeper
Upgradeable[] public managedContracts;
/// @notice Upgrade mode statuses
enum UpgradeStatus {
Idle,
NoticePeriod,
Preparation
}
UpgradeStatus public upgradeStatus;
/// @notice Notice period finish timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint public noticePeriodFinishTimestamp;
/// @notice Addresses of the next versions of the contracts to be upgraded (if element of this array is equal to zero address it means that appropriate upgradeable contract wouldn't be upgraded this time)
/// @dev Will be empty in case of not active upgrade mode
address[] public nextTargets;
/// @notice Version id of contracts
uint public versionId;
/// @notice Contract which defines notice period duration and allows finish upgrade during preparation of it
UpgradeableMaster public mainContract;
/// @notice Contract constructor
/// @param _mainContract Contract which defines notice period duration and allows finish upgrade during preparation of it
/// @dev Calls Ownable contract constructor
constructor(UpgradeableMaster _mainContract) Ownable(msg.sender) public {
mainContract = _mainContract;
versionId = 0;
}
/// @notice Adds a new upgradeable contract to the list of contracts managed by the gatekeeper
/// @param addr Address of upgradeable contract to add
function addUpgradeable(address addr) external {
requireMaster(msg.sender);
require(upgradeStatus == UpgradeStatus.Idle, "apc11"); /// apc11 - upgradeable contract can't be added during upgrade
managedContracts.push(Upgradeable(addr));
emit NewUpgradable(versionId, addr);
}
/// @notice Starts upgrade (activates notice period)
/// @param newTargets New managed contracts targets (if element of this array is equal to zero address it means that appropriate upgradeable contract wouldn't be upgraded this time)
function startUpgrade(address[] calldata newTargets) external {
requireMaster(msg.sender);
require(upgradeStatus == UpgradeStatus.Idle, "spu11"); // spu11 - unable to activate active upgrade mode
require(newTargets.length == managedContracts.length, "spu12"); // spu12 - number of new targets must be equal to the number of managed contracts
uint noticePeriod = mainContract.getNoticePeriod();
mainContract.upgradeNoticePeriodStarted();
upgradeStatus = UpgradeStatus.NoticePeriod;
noticePeriodFinishTimestamp = now.add(noticePeriod);
nextTargets = newTargets;
emit NoticePeriodStart(versionId, newTargets, noticePeriod);
}
/// @notice Cancels upgrade
function cancelUpgrade() external {
requireMaster(msg.sender);
require(upgradeStatus != UpgradeStatus.Idle, "cpu11"); // cpu11 - unable to cancel not active upgrade mode
mainContract.upgradeCanceled();
upgradeStatus = UpgradeStatus.Idle;
noticePeriodFinishTimestamp = 0;
delete nextTargets;
emit UpgradeCancel(versionId);
}
/// @notice Activates preparation status
/// @return Bool flag indicating that preparation status has been successfully activated
function startPreparation() external returns (bool) {
requireMaster(msg.sender);
require(upgradeStatus == UpgradeStatus.NoticePeriod, "ugp11"); // ugp11 - unable to activate preparation status in case of not active notice period status
if (now >= noticePeriodFinishTimestamp) {
upgradeStatus = UpgradeStatus.Preparation;
mainContract.upgradePreparationStarted();
emit PreparationStart(versionId);
return true;
} else {
return false;
}
}
/// @notice Finishes upgrade
/// @param targetsUpgradeParameters New targets upgrade parameters per each upgradeable contract
function finishUpgrade(bytes[] calldata targetsUpgradeParameters) external {
requireMaster(msg.sender);
require(upgradeStatus == UpgradeStatus.Preparation, "fpu11"); // fpu11 - unable to finish upgrade without preparation status active
require(targetsUpgradeParameters.length == managedContracts.length, "fpu12"); // fpu12 - number of new targets upgrade parameters must be equal to the number of managed contracts
require(mainContract.isReadyForUpgrade(), "fpu13"); // fpu13 - main contract is not ready for upgrade
mainContract.upgradeFinishes();
for (uint64 i = 0; i < managedContracts.length; i++) {
address newTarget = nextTargets[i];
if (newTarget != address(0)) {
managedContracts[i].upgradeTarget(newTarget, targetsUpgradeParameters[i]);
}
}
versionId++;
emit UpgradeComplete(versionId, nextTargets);
upgradeStatus = UpgradeStatus.Idle;
noticePeriodFinishTimestamp = 0;
delete nextTargets;
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
import "./Upgradeable.sol";
import "./Operations.sol";
/// @title ZKSwap events
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface Events {
/// @notice Event emitted when a block is committed
event BlockCommit(uint32 indexed blockNumber);
/// @notice Event emitted when a block is verified
event BlockVerification(uint32 indexed blockNumber);
/// @notice Event emitted when a sequence of blocks is verified
event MultiblockVerification(uint32 indexed blockNumberFrom, uint32 indexed blockNumberTo);
/// @notice Event emitted when user send a transaction to withdraw her funds from onchain balance
event OnchainWithdrawal(
address indexed owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Event emitted when user send a transaction to deposit her funds
event OnchainDeposit(
address indexed sender,
uint16 indexed tokenId,
uint128 amount,
address indexed owner
);
/// @notice Event emitted when user send a transaction to deposit her NFT
event OnchainDepositNFT(
address indexed sender,
address indexed token,
uint256 tokenId,
address indexed owner
);
/// @notice Event emitted when user send a transaction to full exit her NFT
event OnchainFullExitNFT(
uint32 indexed accountId,
address indexed owner,
uint64 indexed globalId
);
event OnchainCreatePair(
uint16 indexed tokenAId,
uint16 indexed tokenBId,
uint16 indexed pairId,
address pair
);
/// @notice Event emitted when user sends a authentication fact (e.g. pub-key hash)
event FactAuth(
address indexed sender,
uint32 nonce,
bytes fact
);
/// @notice Event emitted when blocks are reverted
event BlocksRevert(
uint32 indexed totalBlocksVerified,
uint32 indexed totalBlocksCommitted
);
/// @notice Exodus mode entered event
event ExodusMode();
/// @notice New priority request event. Emitted when a request is placed into mapping
event NewPriorityRequest(
address sender,
uint64 serialId,
Operations.OpType opType,
bytes pubData,
bytes userData,
uint256 expirationBlock
);
/// @notice Deposit committed event.
event DepositCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Deposit committed event.
event DepositNFTCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint64 indexed globalId
);
/// @notice Full exit committed event.
event FullExitCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Full exit committed event.
event FullExitNFTCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint64 indexed globalId
);
/// @notice Pending withdrawals index range that were added in the verifyBlock operation.
/// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex)
event PendingWithdrawalsAdd(
uint32 queueStartIndex,
uint32 queueEndIndex
);
/// @notice Pending withdrawals index range that were executed in the completeWithdrawals operation.
/// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex)
event PendingWithdrawalsComplete(
uint32 queueStartIndex,
uint32 queueEndIndex
);
event CreatePairCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
uint16 tokenAId,
uint16 tokenBId,
uint16 indexed tokenPairId,
address pair
);
}
/// @title Upgrade events
/// @author Matter Labs
interface UpgradeEvents {
/// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts
event NewUpgradable(
uint indexed versionId,
address indexed upgradeable
);
/// @notice Upgrade mode enter event
event NoticePeriodStart(
uint indexed versionId,
address[] newTargets,
uint noticePeriod // notice period (in seconds)
);
/// @notice Upgrade mode cancel event
event UpgradeCancel(
uint indexed versionId
);
/// @notice Upgrade mode preparation status event
event PreparationStart(
uint indexed versionId
);
/// @notice Upgrade mode complete event
event UpgradeComplete(
uint indexed versionId,
address[] newTargets
);
}
pragma solidity ^0.5.0;
/// @title Ownable Contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract Ownable {
/// @notice Storage position of the masters address (keccak256('eip1967.proxy.admin') - 1)
bytes32 private constant masterPosition = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/// @notice Contract constructor
/// @dev Sets msg sender address as masters address
/// @param masterAddress Master address
constructor(address masterAddress) public {
setMaster(masterAddress);
}
/// @notice Check if specified address is master
/// @param _address Address to check
function requireMaster(address _address) internal view {
require(_address == getMaster(), "oro11"); // oro11 - only by master
}
/// @notice Returns contract masters address
/// @return Masters address
function getMaster() public view returns (address master) {
bytes32 position = masterPosition;
assembly {
master := sload(position)
}
}
/// @notice Sets new masters address
/// @param _newMaster New masters address
function setMaster(address _newMaster) internal {
bytes32 position = masterPosition;
assembly {
sstore(position, _newMaster)
}
}
/// @notice Transfer mastership of the contract to new master
/// @param _newMaster New masters address
function transferMastership(address _newMaster) external {
requireMaster(msg.sender);
require(_newMaster != address(0), "otp11"); // otp11 - new masters address can't be zero address
setMaster(_newMaster);
}
}
pragma solidity ^0.5.0;
/// @title Interface of the upgradeable contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface Upgradeable {
/// @notice Upgrades target of upgradeable contract
/// @param newTarget New target
/// @param newTargetInitializationParameters New target initialization parameters
function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external;
}
pragma solidity ^0.5.0;
/// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it)
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface UpgradeableMaster {
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint);
/// @notice Notifies contract that notice period started
function upgradeNoticePeriodStarted() external;
/// @notice Notifies contract that upgrade preparation status is activated
function upgradePreparationStarted() external;
/// @notice Notifies contract that upgrade canceled
function upgradeCanceled() external;
/// @notice Notifies contract that upgrade finishes
function upgradeFinishes() external;
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool);
}
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "./Bytes.sol";
/// @title ZKSwap operations tools
library Operations {
// Circuit ops and their pubdata (chunks * bytes)
/// @notice ZKSwap circuit operation type
enum OpType {
Noop,
Deposit,
TransferToNew,
PartialExit,
_CloseAccount, // used for correct op id offset
Transfer,
FullExit,
ChangePubKey,
CreatePair,
AddLiquidity,
RemoveLiquidity,
Swap,
DepositNFT,
MintNFT,
TransferNFT,
TransferToNewNFT,
PartialExitNFT,
FullExitNFT,
ApproveNFT,
ExchangeNFT
}
// Byte lengths
uint8 constant TOKEN_BYTES = 2;
uint8 constant PUBKEY_BYTES = 32;
uint8 constant NONCE_BYTES = 4;
uint8 constant PUBKEY_HASH_BYTES = 20;
uint8 constant ADDRESS_BYTES = 20;
/// @notice Packed fee bytes lengths
uint8 constant FEE_BYTES = 2;
/// @notice ZKSwap account id bytes lengths
uint8 constant ACCOUNT_ID_BYTES = 4;
uint8 constant AMOUNT_BYTES = 16;
/// @notice Signature (for example full exit signature) bytes length
uint8 constant SIGNATURE_BYTES = 64;
/// @notice nft uri bytes lengths
uint8 constant NFT_URI_BYTES = 32;
/// @notice nft seq id bytes lengths
uint8 constant NFT_SEQUENCE_ID_BYTES = 4;
/// @notice nft creator bytes lengths
uint8 constant NFT_CREATOR_ID_BYTES = 4;
/// @notice nft priority op id bytes lengths
uint8 constant NFT_PRIORITY_OP_ID_BYTES = 8;
/// @notice nft global id bytes lengths
uint8 constant NFT_GLOBAL_ID_BYTES = 8;
/// @notic withdraw nft use fee token id bytes lengths
uint8 constant NFT_FEE_TOKEN_ID = 1;
/// @notic fullexit nft success bytes lengths
uint8 constant NFT_SUCCESS = 1;
// Deposit pubdata
struct Deposit {
uint32 accountId;
uint16 tokenId;
uint128 amount;
address owner;
}
uint public constant PACKED_DEPOSIT_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES;
/// Deserialize deposit pubdata
function readDepositPubdata(bytes memory _data) internal pure
returns (Deposit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "rdp10"); // reading invalid deposit pubdata size
}
/// Serialize deposit pubdata
function writeDepositPubdata(Deposit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenId, // tokenId
op.amount, // amount
op.owner // owner
);
}
/// @notice Check that deposit pubdata from request and block matches
function depositPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// We must ignore `accountId` because it is present in block pubdata but not in priority queue
bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}
// FullExit pubdata
struct FullExit {
uint32 accountId;
address owner;
uint16 tokenId;
uint128 amount;
}
uint public constant PACKED_FULL_EXIT_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES;
function readFullExitPubdata(bytes memory _data) internal pure
returns (FullExit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "rfp10"); // reading invalid full exit pubdata size
}
function writeFullExitPubdata(FullExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
op.accountId, // accountId
op.owner, // owner
op.tokenId, // tokenId
op.amount // amount
);
}
/// @notice Check that full exit pubdata from request and block matches
function fullExitPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// `amount` is ignored because it is present in block pubdata but not in priority queue
uint lhs = Bytes.trim(_lhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES);
uint rhs = Bytes.trim(_rhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES);
return lhs == rhs;
}
// PartialExit pubdata
struct PartialExit {
//uint32 accountId; -- present in pubdata, ignored at serialization
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address owner;
}
function readPartialExitPubdata(bytes memory _data, uint _offset) internal pure
returns (PartialExit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = _offset + ACCOUNT_ID_BYTES; // accountId (ignored)
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
}
function writePartialExitPubdata(PartialExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenId, // tokenId
op.amount, // amount
bytes2(0), // fee (ignored) (update when FEE_BYTES is changed)
op.owner // owner
);
}
// ChangePubKey
struct ChangePubKey {
uint32 accountId;
bytes20 pubKeyHash;
address owner;
uint32 nonce;
}
function readChangePubKeyPubdata(bytes memory _data, uint _offset) internal pure
returns (ChangePubKey memory parsed)
{
uint offset = _offset;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce
}
// Withdrawal nft data process
struct WithdrawNFTData {
bool valid; //confirm the necessity of this field
bool pendingWithdraw;
uint64 globalId;
uint32 creatorId;
uint32 seqId;
address target;
bytes32 uri;
}
function readWithdrawalData(bytes memory _data, uint _offset) internal pure
returns (bool isNFTWithdraw, uint128 amount, uint16 _tokenId, WithdrawNFTData memory parsed)
{
uint offset = _offset;
(offset, isNFTWithdraw) = Bytes.readBool(_data, offset);
(offset, parsed.pendingWithdraw) = Bytes.readBool(_data, offset);
(offset, parsed.target) = Bytes.readAddress(_data, offset); // target
if (isNFTWithdraw) {
(offset, parsed.globalId) = Bytes.readUInt64(_data, offset);
(offset, parsed.creatorId) = Bytes.readUInt32(_data, offset); // creatorId
(offset, parsed.seqId) = Bytes.readUInt32(_data, offset); // seqId
(offset, parsed.uri) = Bytes.readBytes32(_data, offset); // uri
(offset, parsed.valid) = Bytes.readBool(_data, offset); // is withdraw valid
} else {
(offset, _tokenId) = Bytes.readUInt16(_data, offset);
(offset, amount) = Bytes.readUInt128(_data, offset); // withdraw erc20 or eth token amount
}
}
// CreatePair pubdata
struct CreatePair {
uint32 accountId;
uint16 tokenA;
uint16 tokenB;
uint16 tokenPair;
address pair;
}
uint public constant PACKED_CREATE_PAIR_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES;
function readCreatePairPubdata(bytes memory _data) internal pure
returns (CreatePair memory parsed)
{
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId
(offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId
(offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId
(offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId
require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size
}
function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenA, // tokenAId
op.tokenB, // tokenBId
op.tokenPair, // pairId
op.pair // pair account
);
}
/// @notice Check that create pair pubdata from request and block matches
function createPairPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// We must ignore `accountId` because it is present in block pubdata but not in priority queue
bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}
// DepositNFT pubdata
struct DepositNFT {
uint64 globalId;
uint32 creatorId;
uint32 seqId;
bytes32 uri;
address owner;
uint32 accountId;
}
uint public constant PACKED_DEPOSIT_NFT_PUBDATA_BYTES = ACCOUNT_ID_BYTES +
NFT_GLOBAL_ID_BYTES + NFT_CREATOR_ID_BYTES + NFT_SEQUENCE_ID_BYTES +
NFT_URI_BYTES + ADDRESS_BYTES ;
/// Deserialize deposit nft pubdata
function readDepositNFTPubdata(bytes memory _data) internal pure
returns (DepositNFT memory parsed) {
uint offset = 0;
(offset, parsed.globalId) = Bytes.readUInt64(_data, offset); // globalId
(offset, parsed.creatorId) = Bytes.readUInt32(_data, offset); // creatorId
(offset, parsed.seqId) = Bytes.readUInt32(_data, offset); // seqId
(offset, parsed.uri) = Bytes.readBytes32(_data, offset); // uri
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
require(offset == PACKED_DEPOSIT_NFT_PUBDATA_BYTES, "rdnp10"); // reading invalid deposit pubdata size
}
/// Serialize deposit pubdata
function writeDepositNFTPubdata(DepositNFT memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
op.globalId,
op.creatorId,
op.seqId,
op.uri,
op.owner, // owner
bytes4(0)
);
}
/// @notice Check that deposit nft pubdata from request and block matches
function depositNFTPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// We must ignore `accountId` because it is present in block pubdata but not in priority queue
uint offset = 0;
uint64 globalId;
(offset, globalId) = Bytes.readUInt64(_lhs, offset); // globalId
if (globalId == 0){
bytes memory lhs_trimmed = Bytes.slice(_lhs, NFT_GLOBAL_ID_BYTES, PACKED_DEPOSIT_NFT_PUBDATA_BYTES - ACCOUNT_ID_BYTES - NFT_GLOBAL_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, NFT_GLOBAL_ID_BYTES, PACKED_DEPOSIT_NFT_PUBDATA_BYTES - ACCOUNT_ID_BYTES - NFT_GLOBAL_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}else{
bytes memory lhs_trimmed = Bytes.slice(_lhs, 0, PACKED_DEPOSIT_NFT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, 0, PACKED_DEPOSIT_NFT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}
}
// FullExitNFT pubdata
struct FullExitNFT {
uint32 accountId;
uint64 globalId;
uint32 creatorId;
uint32 seqId;
bytes32 uri;
address owner;
uint8 success;
}
uint public constant PACKED_FULL_EXIT_NFT_PUBDATA_BYTES = ACCOUNT_ID_BYTES +
NFT_GLOBAL_ID_BYTES + NFT_CREATOR_ID_BYTES +
NFT_SEQUENCE_ID_BYTES + NFT_URI_BYTES + ADDRESS_BYTES + NFT_SUCCESS;
function readFullExitNFTPubdata(bytes memory _data) internal pure returns (FullExitNFT memory parsed) {
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.globalId) = Bytes.readUInt64(_data, offset); // globalId
(offset, parsed.creatorId) = Bytes.readUInt32(_data, offset); // creator
(offset, parsed.seqId) = Bytes.readUInt32(_data, offset); // seqId
(offset, parsed.uri) = Bytes.readBytes32(_data, offset); // uri
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.success) = Bytes.readUint8(_data, offset); // success
require(offset == PACKED_FULL_EXIT_NFT_PUBDATA_BYTES, "rfnp10"); // reading invalid deposit pubdata size
}
function writeFullExitNFTPubdata(FullExitNFT memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
op.accountId,
op.globalId, // nft id in layer2
op.creatorId,
op.seqId,
op.uri,
op.owner,
op.success
);
}
/// @notice Check that full exit pubdata from request and block matches
/// TODO check it
function fullExitNFTPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
bytes memory lhs_trimmed_1 = Bytes.slice(_lhs, 0, ACCOUNT_ID_BYTES + NFT_GLOBAL_ID_BYTES);
bytes memory rhs_trimmed_1 = Bytes.slice(_rhs, 0, ACCOUNT_ID_BYTES + NFT_GLOBAL_ID_BYTES);
bytes memory lhs_trimmed_2 = Bytes.slice(_lhs, PACKED_FULL_EXIT_NFT_PUBDATA_BYTES - ADDRESS_BYTES - NFT_SUCCESS, ADDRESS_BYTES);
bytes memory rhs_trimmed_2 = Bytes.slice(_rhs, PACKED_FULL_EXIT_NFT_PUBDATA_BYTES - ADDRESS_BYTES - NFT_SUCCESS, ADDRESS_BYTES);
return keccak256(lhs_trimmed_1) == keccak256(rhs_trimmed_1) && keccak256(lhs_trimmed_2) == keccak256(rhs_trimmed_2);
}
// PartialExitNFT pubdata
struct PartialExitNFT {
// uint32 accountId;
uint64 globalId;
uint32 creatorId;
uint32 seqId;
bytes32 uri;
address owner;
}
function readPartialExitNFTPubdata(bytes memory _data, uint _offset) internal pure
returns (PartialExitNFT memory parsed) {
uint offset = _offset + ACCOUNT_ID_BYTES; // accountId (ignored)
(offset, parsed.globalId) = Bytes.readUInt64(_data, offset); // globalId
(offset, parsed.creatorId) = Bytes.readUInt32(_data, offset); // creatorId
(offset, parsed.seqId) = Bytes.readUInt32(_data, offset); // seqId
(offset, parsed.uri) = Bytes.readBytes32(_data, offset); // uri
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
}
function writePartialExitNFTPubdata(PartialExitNFT memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.globalId, // tokenId in layer2
bytes4(0),
bytes4(0),
bytes32(0),
op.owner
);
}
}
pragma solidity ^0.5.0;
// Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word)
// implements the following algorithm:
// f(bytes memory input, uint offset) -> X out
// where byte representation of out is N bytes from input at the given offset
// 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N]
// W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N
// 2) We load W from memory into out, last N bytes of W are placed into out
library Bytes {
function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 2);
}
function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 3);
}
function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 4);
}
function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 16);
}
// Copies 'len' lower bytes from 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'.
function toBytesFromUIntTruncated(uint self, uint8 byteLength) private pure returns (bytes memory bts) {
require(byteLength <= 32, "bt211");
bts = new bytes(byteLength);
// Even though the bytes will allocate a full word, we don't want
// any potential garbage bytes in there.
uint data = self << ((32 - byteLength) * 8);
assembly {
mstore(add(bts, /*BYTES_HEADER_SIZE*/32), data)
}
}
// Copies 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length '20'.
function toBytesFromAddress(address self) internal pure returns (bytes memory bts) {
bts = toBytesFromUIntTruncated(uint(self), 20);
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) {
uint256 offset = _start + 20;
require(self.length >= offset, "bta11");
assembly {
addr := mload(add(self, offset))
}
}
// Reasoning about why this function works is similar to that of other similar functions, except NOTE below.
// NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) {
require(self.length >= (_start + 20), "btb20");
assembly {
r := mload(add(add(self, 0x20), _start))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x2)
function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) {
uint256 offset = _start + 0x2;
require(_bytes.length >= offset, "btu02");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x3)
function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) {
uint256 offset = _start + 0x3;
require(_bytes.length >= offset, "btu03");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x4)
function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) {
uint256 offset = _start + 0x4;
require(_bytes.length >= offset, "btu04");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x8)
function bytesToUInt64(bytes memory _bytes, uint256 _start) internal pure returns (uint64 r) {
uint256 offset = _start + 0x8;
require(_bytes.length >= offset, "btu08");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x10)
function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) {
uint256 offset = _start + 0x10;
require(_bytes.length >= offset, "btu16");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x14)
function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) {
uint256 offset = _start + 0x14;
require(_bytes.length >= offset, "btu20");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x20)
function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) {
uint256 offset = _start + 0x20;
require(_bytes.length >= offset, "btb32");
assembly {
r := mload(add(_bytes, offset))
}
}
// Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228
// Get slice from bytes arrays
// Returns the newly created 'bytes memory'
// NOTE: theoretically possible overflow of (_start + _length)
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length), "bse11"); // bytes length is less then start byte + length bytes
bytes memory tempBytes = new bytes(_length);
if (_length != 0) {
// TODO: Review this thoroughly.
assembly {
let slice_curr := add(tempBytes, 0x20)
let slice_end := add(slice_curr, _length)
for {
let array_current := add(_bytes, add(_start, 0x20))
} lt(slice_curr, slice_end) {
slice_curr := add(slice_curr, 0x20)
array_current := add(array_current, 0x20)
} {
mstore(slice_curr, mload(array_current))
}
}
}
return tempBytes;
}
/// Reads byte stream
/// @return new_offset - offset + amount of bytes read
/// @return data - actually read data
// NOTE: theoretically possible overflow of (_offset + _length)
function read(bytes memory _data, uint _offset, uint _length) internal pure returns (uint new_offset, bytes memory data) {
data = slice(_data, _offset, _length);
new_offset = _offset + _length;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readBool(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bool r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]) != 0;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readUint8(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint8 r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]);
}
// NOTE: theoretically possible overflow of (_offset + 2)
function readUInt16(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint16 r) {
new_offset = _offset + 2;
r = bytesToUInt16(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 3)
function readUInt24(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint24 r) {
new_offset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 4)
function readUInt32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint32 r) {
new_offset = _offset + 4;
r = bytesToUInt32(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 8)
function readUInt64(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint64 r) {
new_offset = _offset + 8;
r = bytesToUInt64(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 16)
function readUInt128(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint128 r) {
new_offset = _offset + 16;
r = bytesToUInt128(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readUInt160(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint160 r) {
new_offset = _offset + 20;
r = bytesToUInt160(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readAddress(bytes memory _data, uint _offset) internal pure returns (uint new_offset, address r) {
new_offset = _offset + 20;
r = bytesToAddress(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readBytes20(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes20 r) {
new_offset = _offset + 20;
r = bytesToBytes20(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 32)
function readBytes32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes32 r) {
new_offset = _offset + 32;
r = bytesToBytes32(_data, _offset);
}
// Helper function for hex conversion.
function halfByteToHex(byte _byte) internal pure returns (byte _hexByte) {
require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range.
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
return byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byte) * 8)));
}
// Convert bytes to ASCII hex representation
function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) {
bytes memory outStringBytes = new bytes(_input.length * 2);
// code in `assembly` construction is equivalent of the next code:
// for (uint i = 0; i < _input.length; ++i) {
// outStringBytes[i*2] = halfByteToHex(_input[i] >> 4);
// outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f);
// }
assembly {
let input_curr := add(_input, 0x20)
let input_end := add(input_curr, mload(_input))
for {
let out_curr := add(outStringBytes, 0x20)
} lt(input_curr, input_end) {
input_curr := add(input_curr, 0x01)
out_curr := add(out_curr, 0x02)
} {
let curr_input_byte := shr(0xf8, mload(input_curr))
// here outStringByte from each half of input byte calculates by the next:
//
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
// outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8)))
mstore(out_curr, shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130)))
mstore(add(out_curr, 0x01), shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130)))
}
}
return outStringBytes;
}
/// Trim bytes into single word
function trim(bytes memory _data, uint _new_length) internal pure returns (uint r) {
require(_new_length <= 0x20, "trm10"); // new_length is longer than word
require(_data.length >= _new_length, "trm11"); // data is to short
uint a;
assembly {
a := mload(add(_data, 0x20)) // load bytes into uint256
}
return a >> ((0x20 - _new_length) * 8);
}
}
|
NOTE: theoretically possible overflow of (_offset + 3)
|
function readUInt24(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint24 r) {
new_offset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
| 287,876
|
./partial_match/1/0x5A63Bd386DAC512De49c75fa9e71b3A0F3C4096F/sources/TwoChan.sol
|
only use to disable contract sales if absolutely necessary (emergency use only)
|
function updateContrattSellEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
| 2,611,140
|
pragma solidity ^0.5.1;
// File: contracts/Cogmento.sol
interface IERC20 {
function TOTALSUPPLY452() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF833(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE554(address owner, address spender) //inject NONSTANDARD NAMING
external view returns (uint256);
function TRANSFER570(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE66(address spender, uint256 value) //inject NONSTANDARD NAMING
external returns (bool);
function TRANSFERFROM524(address from, address to, uint256 value) //inject NONSTANDARD NAMING
external returns (bool);
event TRANSFER174( //inject NONSTANDARD NAMING
address indexed from,
address indexed to,
uint256 value
);
event APPROVAL465( //inject NONSTANDARD NAMING
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeMath {
function MUL507(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV872(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function SUB851(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD842(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD98(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
contract Owned {
address public owner;
address public newOwner;
modifier ONLYOWNER420 { //inject NONSTANDARD NAMING
require(msg.sender == owner);
_;
}
function TRANSFEROWNERSHIP119(address _newOwner) public ONLYOWNER420 { //inject NONSTANDARD NAMING
newOwner = _newOwner;
}
function ACCEPTOWNERSHIP717() public { //inject NONSTANDARD NAMING
require(msg.sender == newOwner);
owner = newOwner;
}
}
contract CogmentoToken is IERC20, Owned {
using SafeMath for uint256;
// Constructor - Sets the token Owner
constructor() public {
owner = 0xFCAeeDcC9DfEB56af067f3d4e79caB8ABDd31cF7;
contractAddress = address(this);
_balances[owner] = 1000000000 * 10 ** decimals102;
_balances[contractAddress] = 1000000000 * 10 ** decimals102;
emit TRANSFER174(address(0), owner, 1000000000 * 10 ** decimals102);
emit TRANSFER174(address(0), contractAddress, 1000000000 * 10 ** decimals102);
}
// Events
event ERROR503(string err); //inject NONSTANDARD NAMING
event MINT826(uint mintAmount, address to); //inject NONSTANDARD NAMING
event BURN394(uint burnAmount, address from); //inject NONSTANDARD NAMING
// Token Setup
string public constant name276 = "Cogmento"; //inject NONSTANDARD NAMING
string public constant symbol405 = "COGS"; //inject NONSTANDARD NAMING
uint256 public constant decimals102 = 18; //inject NONSTANDARD NAMING
uint256 public supply = 1000000000 * 10 ** decimals102;
address private contractAddress;
uint256 public ICOPrice;
// Balances for each account
mapping(address => uint256) _balances;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) public _allowed;
// Get the total supply of tokens
function TOTALSUPPLY452() public view returns (uint) { //inject NONSTANDARD NAMING
return supply;
}
// Get the token balance for account `tokenOwner`
function BALANCEOF833(address tokenOwner) public view returns (uint balance) { //inject NONSTANDARD NAMING
return _balances[tokenOwner];
}
// Get the allowance of funds beteen a token holder and a spender
function ALLOWANCE554(address tokenOwner, address spender) public view returns (uint remaining) { //inject NONSTANDARD NAMING
return _allowed[tokenOwner][spender];
}
// Transfer the balance from owner's account to another account
function TRANSFER570(address to, uint value) public returns (bool success) { //inject NONSTANDARD NAMING
require(_balances[msg.sender] >= value);
require(to != contractAddress);
_balances[msg.sender] = _balances[msg.sender].SUB851(value);
_balances[to] = _balances[to].ADD842(value);
emit TRANSFER174(msg.sender, to, value);
return true;
}
// Sets how much a sender is allowed to use of an owners funds
function APPROVE66(address spender, uint value) public returns (bool success) { //inject NONSTANDARD NAMING
_allowed[msg.sender][spender] = value;
emit APPROVAL465(msg.sender, spender, value);
return true;
}
// Transfer from function, pulls from allowance
function TRANSFERFROM524(address from, address to, uint value) public returns (bool success) { //inject NONSTANDARD NAMING
require(value <= BALANCEOF833(from));
require(value <= ALLOWANCE554(from, to));
_balances[from] = _balances[from].SUB851(value);
_balances[to] = _balances[to].ADD842(value);
_allowed[from][to] = _allowed[from][to].SUB851(value);
emit TRANSFER174(from, to, value);
return true;
}
// Users Cannot acidentaly send ETH to the contract
function () external payable {
revert();
}
// Owner Can mint new tokens
function MINT964(uint256 amount, address to) public ONLYOWNER420 { //inject NONSTANDARD NAMING
_balances[to] = _balances[to].ADD842(amount);
supply = supply.ADD842(amount);
emit MINT826(amount, to);
}
// Owner can burn existing tokens
function BURN156(uint256 amount, address from) public ONLYOWNER420 { //inject NONSTANDARD NAMING
require(_balances[from] >= amount);
_balances[from] = _balances[from].SUB851(amount);
supply = supply.SUB851(amount);
emit BURN394(amount, from);
}
// Change ICO Price
function SETICOPRICE755(uint256 _newPrice) public ONLYOWNER420 { //inject NONSTANDARD NAMING
ICOPrice = _newPrice;
}
// See how many tokens are available to be purcahsed.
function GETREMAININGICOBALANCE812() public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[contractAddress];
}
// Top up ICO balance
function TOPUPICO333(uint256 _amount) public ONLYOWNER420 { //inject NONSTANDARD NAMING
require(_balances[owner] >= _amount);
_balances[owner] = _balances[owner].SUB851(_amount);
_balances[contractAddress] = _balances[contractAddress].ADD842(_amount);
emit TRANSFER174(msg.sender, contractAddress, _amount);
}
// Buy tokens
function BUYTOKENS290() public payable { //inject NONSTANDARD NAMING
require(ICOPrice > 0);
require(msg.value >= ICOPrice);
uint256 affordAmount = msg.value / ICOPrice;
require(_balances[contractAddress] >= affordAmount * 10 ** decimals102);
_balances[contractAddress] = _balances[contractAddress].SUB851(affordAmount * 10 ** decimals102);
_balances[msg.sender] = _balances[msg.sender].ADD842(affordAmount * 10 ** decimals102);
emit TRANSFER174(contractAddress, msg.sender, affordAmount * 10 ** decimals102);
}
// Withdraw ETH
function WITHDRAWCONTRACTBALANCE542() public ONLYOWNER420 { //inject NONSTANDARD NAMING
msg.sender.transfer(contractAddress.balance);
}
// Cancel and withdraw ICO tokens
function WITHDRAWCONTRACTTOKENS839(uint256 _amount) public ONLYOWNER420 { //inject NONSTANDARD NAMING
require(_balances[contractAddress] >= _amount);
_balances[contractAddress] = _balances[contractAddress].SUB851(_amount);
_balances[owner] = _balances[owner].ADD842(_amount);
emit TRANSFER174(contractAddress, owner, _amount);
}
}
|
inject NONSTANDARD NAMING
|
function ACCEPTOWNERSHIP717() public {
| 5,457,931
|
./full_match/80001/0xc632E7fde2cA79D0D5D5e25399d7048EfE7b868f/sources/TestSasWecoin.sol
|
Returns the total staking power for the given epoch. epochToCheck The epoch to check if adjustement ahs been made return The total staking power with adjustments made for the given epoch/
|
function _latestStakingPower(uint epochToCheck) internal returns (uint) {
EpochInfo storage epoch = epochs[epochToCheck];
(
uint stakingPower,
uint adjustment,
bool update
) = _getLatestStakingPower(epochToCheck);
if (update) {
epoch.adjusted = true;
totalBonusStakingPower -= adjustment;
}
return stakingPower;
}
| 875,262
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.