file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
./full_match/137/0x58292361816431Cd8822b94DBc388343C94F21c4/sources/contracts/MasterChef.sol
|
Deposit LP tokens to MasterChef for FLOO allocation.
|
function deposit(uint256 _pid, uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending =
user.amount.mul(pool.accFlooPerShare).div(1e18).sub(
user.rewardDebt
);
if (pending > 0) {
safeFlooTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
if (pool.depositFeeBP > 0) {
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accFlooPerShare).div(1e18);
emit Deposit(msg.sender, _pid, _amount);
}
| 4,693,683
|
./full_match/3/0x17E27c0e9264973D23215cC10Fb2d988D183cff5/sources/bozy.sol
|
See {ERC20Interface - balanceOf} Returns owner's token balance.
|
function balanceOf(address _owner) public view override returns (uint256 holdings) {
return balances[_owner] / (10 ** decimals);
}
| 14,145,698
|
// SPDX-License-Identifier: MIT LICENSE
/**
. ' , ' , . ' .
_________ _________ _________
_ /_|_____|_\ _ _ /_|_____|_\ _ _ /_|_____|_\ _
'. \ / .' '. \ / .' '. \ / .'
'.\ /.' '.\ /.' '.\ /.'
'.' '.' '.'
βββββββ βββ ββββββ ββββ ββββ βββββββ ββββ ββββββββββ
ββββββββββββββββββββββββ βββββββββββββββββββ βββββββββββ
βββ ββββββββββββββββββββββββββββ βββββββββ ββββββ βββ
βββ ββββββββββββββββββββββββββββ ββββββββββββββββ βββ
ββββββββββββββ ββββββ βββ βββββββββββββββ ββββββββββββββ
βββββββ ββββββ ββββββ βββ βββββββ βββ ββββββββββββ
βββ βββββββββββββββββββββββββββββββ
βββ βββββββββββββββββββββββββββββββ <'l
__ ββββββββββββββ βββββββββββ βββ ll
(___()'`; ββββββββββββββ βββββββββββ βββ llama~
/, /` βββ ββββββββββββββββββββββ βββ || ||
\\"--\\ βββ ββββββββββββββββββββββ βββ '' ''
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./interfaces/ITraits.sol";
import "./interfaces/IDiamondHeist.sol";
contract TraitsV2 is Ownable, ITraits {
using Strings for uint256;
// struct to store each trait's data for metadata and rendering
struct Trait {
string name;
string png;
}
// mapping from trait type (index) to its name
string[9] _traitTypes = [
"Body",
"Hat",
"Eye",
"Mouth",
"Clothes",
"Tail",
"Alpha"
];
// storage of each traits name and base64 PNG data
mapping(uint8 => mapping(uint8 => Trait)) public traitData;
// mapping from alphaIndex to its score
string[4] _alphas = [
"8",
"7",
"6",
"5"
];
IDiamondHeist public diamondheist;
string private llamaDescription;
string private dogDescription;
constructor() {}
/** ADMIN */
function setGame(address _diamondheist) external onlyOwner {
diamondheist = IDiamondHeist(_diamondheist);
}
/**
* administrative to upload the names and images associated with each trait
* @param traitType the trait type to upload the traits for (see traitTypes for a mapping)
* @param traits the names and base64 encoded PNGs for each trait
*/
function uploadTraits(uint8 traitType, uint8[] calldata traitIds, Trait[] calldata traits) external onlyOwner {
require(traitIds.length == traits.length, "Mismatched inputs");
for (uint i = 0; i < traits.length; i++) {
traitData[traitType][traitIds[i]] = Trait(
traits[i].name,
traits[i].png
);
}
}
/** RENDER */
/**
* generates an <image> element using base64 encoded PNGs
* @param trait the trait storing the PNG data
* @return the <image> element
*/
function drawTrait(Trait memory trait) internal pure returns (string memory) {
return string(abi.encodePacked(
'<image x="4" y="4" width="32" height="32" image-rendering="pixelated" preserveAspectRatio="xMidYMid" xlink:href="data:image/png;base64,',
trait.png,
'"/>'
));
}
/**
* generates an entire SVG by composing multiple <image> elements of PNGs
* @param tokenId the ID of the token to generate an SVG for
* @return a valid SVG of the Llama / Dog
*/
function drawSVG(uint256 tokenId) public view returns (string memory) {
IDiamondHeist.LlamaDog memory s = diamondheist.getTokenTraits(tokenId);
uint8 shift = s.isLlama ? 0 : 7;
string memory svgString = string(abi.encodePacked(
drawTrait(traitData[0 + shift][s.body]),
drawTrait(traitData[1 + shift][s.hat]),
drawTrait(traitData[2 + shift][s.eye]),
drawTrait(traitData[3 + shift][s.mouth]),
drawTrait(traitData[4 + shift][s.clothes]),
drawTrait(traitData[5 + shift][s.tail])
));
return string(abi.encodePacked(
'<svg id="diamondheist" width="100%" height="100%" version="1.1" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">',
svgString,
"</svg>"
));
}
/**
* generates an attribute for the attributes array in the ERC721 metadata standard
* @param traitType the trait type to reference as the metadata key
* @param value the token's trait associated with the key
* @return a JSON dictionary for the single attribute
*/
function attributeForTypeAndValue(string memory traitType, string memory value) internal pure returns (string memory) {
return string(abi.encodePacked(
'{"trait_type":"',
traitType,
'","value":"',
value,
'"}'
));
}
/**
* generates an attribute for the attributes array in the ERC721 metadata standard
* @param traitType the trait type to reference as the metadata key
* @param value the token's trait associated with the key
* @return a JSON dictionary for the single attribute
*/
function attributeForTypeAndValueNumber(string memory traitType, string memory value) internal pure returns (string memory) {
return string(abi.encodePacked(
'{"display_type": "number", "trait_type":"',
traitType,
'","value":',
value,
'}'
));
}
function getGen(uint256 tokenId) internal pure returns (string memory) {
if (tokenId <= 7500) return "Gen 0";
if (tokenId <= 15000) return "Gen 1";
if (tokenId <= 22500) return "Gen 2";
if (tokenId <= 30000) return "Gen 3";
return "Gen 4";
}
/**
* generates an array composed of all the individual traits and values
* @param tokenId the ID of the token to compose the metadata for
* @return a JSON array of all of the attributes for given token ID
*/
function compileAttributes(uint256 tokenId) public view returns (string memory) {
IDiamondHeist.LlamaDog memory s = diamondheist.getTokenTraits(tokenId);
string memory traits;
if (s.isLlama) {
traits = string(abi.encodePacked(
attributeForTypeAndValue(_traitTypes[0], traitData[0][s.body].name),",",
attributeForTypeAndValue(_traitTypes[1], traitData[1][s.hat].name),",",
attributeForTypeAndValue(_traitTypes[2], traitData[2][s.eye].name),",",
attributeForTypeAndValue(_traitTypes[3], traitData[3][s.mouth].name),",",
attributeForTypeAndValue(_traitTypes[4], traitData[4][s.clothes].name),",",
attributeForTypeAndValue(_traitTypes[5], traitData[5][s.tail].name),","
// traitData 6 = alpha score, but not visible
));
} else {
traits = string(abi.encodePacked(
attributeForTypeAndValue(_traitTypes[0], traitData[7][s.body].name),",",
attributeForTypeAndValue(_traitTypes[1], traitData[8][s.hat].name),",",
attributeForTypeAndValue(_traitTypes[2], traitData[9][s.eye].name),",",
attributeForTypeAndValue(_traitTypes[3], traitData[10][s.mouth].name),",",
attributeForTypeAndValue(_traitTypes[4], traitData[11][s.clothes].name),",",
attributeForTypeAndValue(_traitTypes[5], traitData[12][s.tail].name),",",
attributeForTypeAndValueNumber("Sneaky Score", _alphas[s.alphaIndex]),","
));
}
return string(abi.encodePacked(
'[',
traits,
'{"trait_type":"Generation","value":"',
getGen(tokenId),
'"},{"trait_type":"Type","value":',
s.isLlama ? '"Llama"' : '"Dog"',
'}]'
));
}
/**
* generates a base64 encoded metadata response without referencing off-chain content
* @param tokenId the ID of the token to generate the metadata for
* @return a base64 encoded JSON dictionary of the token's metadata and SVG
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
IDiamondHeist.LlamaDog memory s = diamondheist.getTokenTraits(tokenId);
string memory metadata = string(abi.encodePacked(
'{"name": "',
s.isLlama ? 'Llama #' : 'Dog #',
tokenId.toString(),
'", "description": "',
s.isLlama ? llamaDescription : dogDescription,
'", "image": "data:image/svg+xml;base64,',
base64(bytes(drawSVG(tokenId))),
'", "attributes":',
compileAttributes(tokenId),
"}"
));
return string(abi.encodePacked(
"data:application/json;base64,",
base64(bytes(metadata))
));
}
function setDescription(string memory _llama, string memory _dog) external onlyOwner {
llamaDescription = _llama;
dogDescription = _dog;
}
/** BASE 64 - Written by Brech Devos */
string internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function base64(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F)))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
}
// SPDX-License-Identifier: MIT
// 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/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface ITraits {
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol";
interface IDiamondHeist is IERC721Upgradeable, IERC721MetadataUpgradeable {
// struct to store each token's traits
struct LlamaDog {
bool isLlama;
uint8 body;
uint8 hat;
uint8 eye;
uint8 mouth;
uint8 clothes;
uint8 tail;
uint8 alphaIndex;
}
function getPaidTokens() external view returns (uint256);
function getTokenTraits(uint256 tokenId) external view returns (LlamaDog memory);
function isLlama(uint256 tokenId) external view returns(bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/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/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/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);
}
|
generates an attribute for the attributes array in the ERC721 metadata standard traitType the trait type to reference as the metadata key value the token's trait associated with the key return a JSON dictionary for the single attribute/
|
function attributeForTypeAndValueNumber(string memory traitType, string memory value) internal pure returns (string memory) {
return string(abi.encodePacked(
'{"display_type": "number", "trait_type":"',
traitType,
'","value":',
value,
'}'
));
}
| 5,985,483
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./DonationEvents.sol";
/// @title Contract for charity funding with ether donations
/// @author Pengyang Zhou
/// @notice Allows users to propose charity funding project and expense and get donations
/// @dev EthDonation is contract manages charity projects. A project founder proposes a project,
/// and adds expenses plans. A donator or investor donates to a project and approve expense according
/// to their available donations.
contract EthDonation is DonationEvents, Ownable {
/// @dev Tracks total project count
uint public projectCount;
/// @dev Tracks mapping between project ID and project detail
mapping(uint => Project) public projects;
/// @dev ExpenseState is the two states of an expense
enum ExpenseState {
Pending,
Approved
}
constructor() {
}
/// @dev Donation tracks donations from a donator with total amount and available amount
/// to approve expenses. If an expense is approved, the available amount will be substracted
/// by the approved amount.
struct Donation {
uint256 total;
uint256 available;
bool refunded;
}
/// @dev Project is the information of the project to be funded by donators
/// amountFunded tracks the total amount funded and it is temperorally stored in the contract balances
/// amountAllocated tracks the amount that has been allocated to the founder.
struct Project {
address payable founder;
string title;
string description;
uint endTime;
uint256 amountFunded;
uint256 amountAllocated;
uint expenseCount;
address[] donators;
mapping(address => Donation) donations;
mapping(uint => Expense) expenses;
}
/// @dev Expense is the detail of a single expense item in a project
struct Expense {
string description;
uint256 allocation;
uint256 approvedAmount;
ExpenseState state;
}
/// @notice Creates a project to be donated with project title, description and the project end time
/// @param _title Project title
/// @param _description Project description
/// @param _endTime Project end time in unix seconds
/// @return Returns project ID
function createProject(string memory _title, string memory _description, uint _endTime) public returns(uint) {
require(_endTime > block.timestamp);
projectCount += 1;
Project storage proj = projects[projectCount];
proj.founder = payable(msg.sender);
proj.title= _title;
// TODO: project description could be optimized to use S3 along with more functionalities like adding images
proj.description= _description;
proj.endTime= _endTime;
return projectCount;
}
/// @notice Donates the amount of ETH from donator and temporally stored in the contract address
/// @param projectId Project ID
function donate(uint projectId) public payable {
require(msg.value > 0);
require(projects[projectId].endTime > block.timestamp);
Project storage proj = projects[projectId];
proj.amountFunded += msg.value;
Donation storage donation = proj.donations[msg.sender];
if (donation.total == 0) {
proj.donators.push(msg.sender);
}
donation.total += msg.value;
donation.available += msg.value;
emit LogDonationMade(msg.sender, msg.value, projectId);
}
/// @notice Refunds donations to the original donator if the project ends and there are their donations left
/// @param projectId Project ID
function refund(uint projectId) public {
require(projectId >= 1 && projectId <= projectCount);
// project should be ended
require(projects[projectId].endTime < block.timestamp);
// msg.sender should be one of the donator and has available amount
require(projects[projectId].donations[msg.sender].available > 0);
Project storage proj = projects[projectId];
uint256 amount = proj.donations[msg.sender].available;
Donation storage dona = proj.donations[msg.sender];
dona.available = 0;
dona.refunded = true;
(bool success, ) = msg.sender.call{value: amount}("");
if (success) {
emit LogRefund(projectId, msg.sender, amount);
} else {
emit LogRefundFailure(projectId, msg.sender, amount);
dona.available = amount;
dona.refunded = false;
}
}
/// @notice Creates an expense for a project
/// @param projectId Project ID
/// @param allocation Expense allocation asked
/// @param description Expense description
/// @return Returns expense ID
function createExpense(uint projectId, uint256 allocation, string memory description) public returns(uint) {
require(projects[projectId].founder == msg.sender);
require(projectId >= 1 && projectId <= projectCount);
require(allocation > 0);
Project storage proj = projects[projectId];
uint expenseId = proj.expenseCount + 1;
Expense storage exps = proj.expenses[expenseId];
exps.description = description;
exps.allocation = allocation;
exps.state = ExpenseState.Pending;
proj.expenseCount += 1;
return expenseId;
}
/// @notice Gets expense count for a project
/// @param projectId Project ID
/// @return Returns expense count
function getExpenseCount(uint projectId) public view returns (uint) {
require(projectId >= 1 && projectId <= projectCount);
return projects[projectId].expenseCount;
}
/// @notice Gets an expense by expense ID and project ID
/// @param projectId Project ID
/// @param expenseId Expense ID
/// @return Returns expense detail with description, allocation, amount approved and state
function getExpense(uint projectId, uint expenseId) public view returns (string memory, uint256, uint256, uint) {
require(projectId >= 1 && projectId <= projectCount);
require(expenseId >= 1 && expenseId <= projects[projectId].expenseCount);
require(projects[projectId].expenses[expenseId].allocation > 0);
Expense storage exp = projects[projectId].expenses[expenseId];
return (exp.description, exp.allocation, exp.approvedAmount, uint(exp.state));
}
/// @notice Gets the donation a project of a caller
/// @param projectId Project ID
/// @return Returns the total donation amount and the available amount
function getMyDonation(uint projectId) public view returns (uint256, uint256) {
require(projectId >= 1 && projectId <= projectCount);
require(projects[projectId].donations[msg.sender].total > 0, "you must be one of the donators");
Donation memory dona = projects[projectId].donations[msg.sender];
return (dona.total, dona.available);
}
/// @notice Gets the donations a project
/// @param projectId Project ID
/// @return Returns a list of donators, a list of their total donation amounts, and a list of their the available amounts
function getDonations(uint projectId) public view returns (address[] memory, uint256[] memory, uint256[] memory){
require(projectId >= 1 && projectId <= projectCount);
Project storage proj = projects[projectId];
uint length = proj.donators.length;
address[] memory donators = new address[](length);
uint256[] memory allocations = new uint256[](length);
uint256[] memory availables = new uint256[](length);
for (uint i = 0; i < length; i++) {
address donator = proj.donators[i];
Donation memory dona = proj.donations[donator];
donators[i] = donator;
allocations[i] = dona.total;
availables[i] = dona.available;
}
return (donators, allocations, availables);
}
/// @notice Approves an expense of a project
/// @dev When the total approved amount is greater than or equal to the allocation for the proposed expense
/// the approved amount will be transferred to the project founder's address
function approveExpense(uint projectId, uint expenseId) public {
/// projectId should be valid
require(projectId >= 1 && projectId <= projectCount);
/// msg.sender should be one of the donator and has available amount
require(projects[projectId].donations[msg.sender].available > 0);
/// expenseId should be valid
require(expenseId >= 1 && expenseId <= projects[projectId].expenseCount);
/// expense should be in pending state
require(projects[projectId].expenses[expenseId].state == ExpenseState.Pending);
Project storage project = projects[projectId];
Expense storage expense = project.expenses[expenseId];
uint256 amountToApprove = Math.min(expense.allocation - expense.approvedAmount, project.donations[msg.sender].available);
expense.approvedAmount += amountToApprove;
project.donations[msg.sender].available -= amountToApprove;
emit LogExpenseApproved(projectId, expenseId, msg.sender);
if (expense.approvedAmount == expense.allocation) { // expense allocation is filled, yay
expense.state = ExpenseState.Approved;
project.amountAllocated += expense.allocation;
(bool success, ) = project.founder.call{value:expense.allocation}("");
if (success) {
emit LogExpenseAllocated(projectId, expenseId, expense.allocation);
} else {
emit LogExpenseAllocationFailure(projectId, expenseId, expense.allocation);
expense.state = ExpenseState.Pending;
project.amountAllocated -= expense.allocation;
}
}
}
/// @dev Migrates the contract balances to an address
function migrateTo(address to) public onlyOwner {
/// TODO: In an emergency the owner can migrate allfunds to a different address.
}
}
|
Approves an expense of a project When the total approved amount is greater than or equal to the allocation for the proposed expense the approved amount will be transferred to the project founder's address
|
function approveExpense(uint projectId, uint expenseId) public {
require(projectId >= 1 && projectId <= projectCount);
require(projects[projectId].donations[msg.sender].available > 0);
require(expenseId >= 1 && expenseId <= projects[projectId].expenseCount);
require(projects[projectId].expenses[expenseId].state == ExpenseState.Pending);
Project storage project = projects[projectId];
Expense storage expense = project.expenses[expenseId];
uint256 amountToApprove = Math.min(expense.allocation - expense.approvedAmount, project.donations[msg.sender].available);
expense.approvedAmount += amountToApprove;
project.donations[msg.sender].available -= amountToApprove;
emit LogExpenseApproved(projectId, expenseId, msg.sender);
expense.state = ExpenseState.Approved;
project.amountAllocated += expense.allocation;
if (success) {
emit LogExpenseAllocated(projectId, expenseId, expense.allocation);
emit LogExpenseAllocationFailure(projectId, expenseId, expense.allocation);
expense.state = ExpenseState.Pending;
project.amountAllocated -= expense.allocation;
}
}
| 15,796,568
|
./full_match/1/0xF527c0F73d96F853A48D1B53Bcf3aCb4983CE702/sources/contracts/Campaign.sol
|
campaign_id task_id -> reward level task_id -> campaign_id task_id, user address -> claimed task_id -> isMultipleClaimed address -> boolean
|
{
using SafeERC20Upgradeable for IERC20Upgradeable;
mapping(uint80 => CampaignInfo) private campaignInfos;
mapping(uint80 => uint256) private taskToAmountReward;
mapping(uint80 => uint80) private taskToCampaignId;
mapping(uint80 => mapping(address => uint8)) private claimedTasks;
mapping(uint80 => uint8) private multipleClaim;
mapping(address => uint8) private isOperator;
AggregatorV3Interface internal dataFeed;
address private chappyToken;
address private cookieToken;
address private cutReceiver;
address[] private admins;
uint80 private newCampaignId;
uint80 private newTaskId;
uint72 private nonce;
error InvalidSignature();
error InsufficentChappy(uint80);
error InsufficentChappyNFT(uint80);
error UnavailableCampaign(uint80);
error TaskNotInCampaign(uint80, uint80);
error ClaimedTask(uint80);
error InsufficentFund(uint80);
error Unauthorized();
error InvalidTime();
error InvalidAddress();
error InvalidNumber();
error SentZeroNative();
error SentNativeFailed();
error NativeNotAllowed();
error InvalidCampaign(uint80);
error InvalidEligibility(uint80);
error InvalidInput();
error Underflow();
error InvalidValue();
error InvalidFee();
error InvalidTip();
error InvalidReward(uint80);
error AlreadyOperators(address);
error NotOperators(address);
error InvalidPriceFeed();
error InvalidPoint();
event ChangeAdmin(address[]);
event ChangeToken(address);
event AddOperator(address);
event RemoveOperator(address);
event CreateCampaign(uint80, uint80[]);
event AddTasks(uint80, uint80[]);
event ChangeCutReceiver(address);
event ChangeTreasury(address);
event ChangeSharePercent(uint16);
event FundCampaign(uint80, uint256);
event WithdrawFundCampaign(uint80, uint256);
event ClaimReward(uint80[][]);
struct CampaignInfo {
address rewardToken;
address collection;
address owner;
uint256 amount;
uint256 minimumBalance;
uint32 startAt;
uint32 endAt;
uint8 checkNFT;
}
struct CampaignInput {
address rewardToken;
address collection;
uint256 minimumBalance;
uint256 amount;
uint32 startAt;
uint32 endAt;
uint8 checkNFT;
}
struct ClaimInput {
uint80[][] taskIds;
uint80[][] pointForMultiple;
bytes signature;
uint8[] isValidUser;
}
modifier onlyAdmins() {
address[] memory memAdmins = admins;
bool checked = false;
for (uint256 idx = 0; idx < memAdmins.length; ++idx) {
if (memAdmins[idx] == msg.sender) {
checked = true;
break;
}
}
if (checked == false) {
revert Unauthorized();
}
_;
}
modifier onlyAdmins() {
address[] memory memAdmins = admins;
bool checked = false;
for (uint256 idx = 0; idx < memAdmins.length; ++idx) {
if (memAdmins[idx] == msg.sender) {
checked = true;
break;
}
}
if (checked == false) {
revert Unauthorized();
}
_;
}
modifier onlyAdmins() {
address[] memory memAdmins = admins;
bool checked = false;
for (uint256 idx = 0; idx < memAdmins.length; ++idx) {
if (memAdmins[idx] == msg.sender) {
checked = true;
break;
}
}
if (checked == false) {
revert Unauthorized();
}
_;
}
modifier onlyAdmins() {
address[] memory memAdmins = admins;
bool checked = false;
for (uint256 idx = 0; idx < memAdmins.length; ++idx) {
if (memAdmins[idx] == msg.sender) {
checked = true;
break;
}
}
if (checked == false) {
revert Unauthorized();
}
_;
}
modifier byOperator() {
bool checked = false;
if (isOperator[msg.sender] == 1 || msg.sender == owner()) {
checked = true;
}
if (checked == false) {
revert Unauthorized();
}
_;
}
modifier byOperator() {
bool checked = false;
if (isOperator[msg.sender] == 1 || msg.sender == owner()) {
checked = true;
}
if (checked == false) {
revert Unauthorized();
}
_;
}
modifier byOperator() {
bool checked = false;
if (isOperator[msg.sender] == 1 || msg.sender == owner()) {
checked = true;
}
if (checked == false) {
revert Unauthorized();
}
_;
}
function initialize(
address operatorAddress,
address chappyTokenAddress,
address cookieTokenAddress,
address cutReceiverAddress,
address[] memory newAdmins,
uint16 newSharePercent,
address chainlinkPriceFeedNativeCoin
) external initializer {
__Ownable_init_unchained();
__ReentrancyGuard_init_unchained();
if (newSharePercent > 10000) {
revert InvalidNumber();
}
dataFeed = AggregatorV3Interface(
chainlinkPriceFeedNativeCoin
);
isOperator[operatorAddress] = 1;
admins = newAdmins;
chappyToken = chappyTokenAddress;
cookieToken = cookieTokenAddress;
sharePercent = newSharePercent;
cutReceiver = cutReceiverAddress;
}
function initialize(
address operatorAddress,
address chappyTokenAddress,
address cookieTokenAddress,
address cutReceiverAddress,
address[] memory newAdmins,
uint16 newSharePercent,
address chainlinkPriceFeedNativeCoin
) external initializer {
__Ownable_init_unchained();
__ReentrancyGuard_init_unchained();
if (newSharePercent > 10000) {
revert InvalidNumber();
}
dataFeed = AggregatorV3Interface(
chainlinkPriceFeedNativeCoin
);
isOperator[operatorAddress] = 1;
admins = newAdmins;
chappyToken = chappyTokenAddress;
cookieToken = cookieTokenAddress;
sharePercent = newSharePercent;
cutReceiver = cutReceiverAddress;
}
function addOperator(address operatorAddress) external onlyOwner {
if (isOperator[operatorAddress] == 1) {
revert AlreadyOperators(operatorAddress);
}
isOperator[operatorAddress] = 1;
emit AddOperator(operatorAddress);
}
function addOperator(address operatorAddress) external onlyOwner {
if (isOperator[operatorAddress] == 1) {
revert AlreadyOperators(operatorAddress);
}
isOperator[operatorAddress] = 1;
emit AddOperator(operatorAddress);
}
function removeOperator(address operatorAddress) external onlyOwner {
if (isOperator[operatorAddress] == 0) {
revert NotOperators(operatorAddress);
}
isOperator[operatorAddress] = 0;
emit RemoveOperator(operatorAddress);
}
function removeOperator(address operatorAddress) external onlyOwner {
if (isOperator[operatorAddress] == 0) {
revert NotOperators(operatorAddress);
}
isOperator[operatorAddress] = 0;
emit RemoveOperator(operatorAddress);
}
function changeAdmins(address[] calldata newAdmins) external byOperator {
admins = newAdmins;
emit ChangeAdmin(newAdmins);
}
function changeTokenPlatform(address newToken) external byOperator {
chappyToken = newToken;
emit ChangeToken(newToken);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
} else {
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
} else {
function createCampaign(
CampaignInput calldata campaign,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external payable onlyAdmins nonReentrant {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
if (campaign.startAt >= campaign.endAt && campaign.endAt != 0) {
revert InvalidTime();
}
if (campaign.collection == address(0)) {
if (campaign.checkNFT == 1 || campaign.checkNFT == 2) {
revert InvalidAddress();
}
}
if (campaign.checkNFT > 2) {
revert InvalidValue();
}
if (
campaign.rewardToken == address(0) && msg.value != campaign.amount
) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
address clonedRewardToken = campaign.rewardToken;
uint256 cutAmount = 0;
uint256 actualAmount = 0;
if (campaign.rewardToken != address(0)) {
cutAmount = mulDiv(campaign.amount, sharePercent, 10000);
actualAmount = campaign.amount - cutAmount;
cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
}
CampaignInfo memory campaignInfo = CampaignInfo(
clonedRewardToken,
campaign.collection,
msg.sender,
actualAmount,
campaign.minimumBalance,
campaign.startAt,
campaign.endAt,
campaign.checkNFT
);
uint80 taskId = newTaskId;
uint80 campaignId = newCampaignId;
campaignInfos[campaignId] = campaignInfo;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (rewardEachTask[idx] >= campaign.amount) {
revert InvalidNumber();
}
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
++newCampaignId;
if (clonedRewardToken == address(0)) {
if (msg.value != campaign.amount) {
revert InvalidInput();
}
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(clonedRewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit CreateCampaign(campaignId, taskIds);
}
function addTasks(
uint80 campaignId,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external onlyAdmins {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
uint80 taskId = newTaskId;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
emit AddTasks(campaignId, taskIds);
}
function addTasks(
uint80 campaignId,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external onlyAdmins {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
uint80 taskId = newTaskId;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
emit AddTasks(campaignId, taskIds);
}
function addTasks(
uint80 campaignId,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external onlyAdmins {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
uint80 taskId = newTaskId;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
emit AddTasks(campaignId, taskIds);
}
function addTasks(
uint80 campaignId,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external onlyAdmins {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
uint80 taskId = newTaskId;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
emit AddTasks(campaignId, taskIds);
}
function addTasks(
uint80 campaignId,
uint256[] calldata rewardEachTask,
uint8[] calldata isMultipleClaim
) external onlyAdmins {
if (rewardEachTask.length != isMultipleClaim.length) {
revert InvalidInput();
}
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
uint80 taskId = newTaskId;
uint80[] memory taskIds = new uint80[](rewardEachTask.length);
for (uint80 idx; idx < rewardEachTask.length; ++idx) {
if (isMultipleClaim[idx] == 1) {
multipleClaim[taskId] = 1;
}
taskToAmountReward[taskId] = rewardEachTask[idx];
taskToCampaignId[taskId] = campaignId;
taskIds[idx] = taskId;
++taskId;
}
newTaskId = taskId;
emit AddTasks(campaignId, taskIds);
}
function changeCutReceiver(
address receiver
) external byOperator nonReentrant {
cutReceiver = receiver;
emit ChangeCutReceiver(receiver);
}
function changeSharePercent(
uint16 newSharePpercent
) external byOperator nonReentrant {
if (newSharePpercent > 10000) {
revert InvalidNumber();
}
sharePercent = newSharePpercent;
emit ChangeSharePercent(newSharePpercent);
}
function changeSharePercent(
uint16 newSharePpercent
) external byOperator nonReentrant {
if (newSharePpercent > 10000) {
revert InvalidNumber();
}
sharePercent = newSharePpercent;
emit ChangeSharePercent(newSharePpercent);
}
function fundCampaign(
uint80 campaignId,
uint256 amount
) external payable nonReentrant {
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0) && msg.value != amount) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
uint256 actualAmount = 0;
if (campaign.rewardToken == address(0)) {
if (msg.value != amount) {
revert InvalidInput();
}
uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
campaign.amount = campaign.amount + actualAmount;
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
uint256 cutAmount = mulDiv(amount, sharePercent, 10000);
actualAmount = amount - cutAmount;
campaign.amount = campaign.amount + actualAmount;
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit FundCampaign(campaignId, actualAmount);
}
function fundCampaign(
uint80 campaignId,
uint256 amount
) external payable nonReentrant {
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0) && msg.value != amount) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
uint256 actualAmount = 0;
if (campaign.rewardToken == address(0)) {
if (msg.value != amount) {
revert InvalidInput();
}
uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
campaign.amount = campaign.amount + actualAmount;
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
uint256 cutAmount = mulDiv(amount, sharePercent, 10000);
actualAmount = amount - cutAmount;
campaign.amount = campaign.amount + actualAmount;
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit FundCampaign(campaignId, actualAmount);
}
function fundCampaign(
uint80 campaignId,
uint256 amount
) external payable nonReentrant {
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0) && msg.value != amount) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
uint256 actualAmount = 0;
if (campaign.rewardToken == address(0)) {
if (msg.value != amount) {
revert InvalidInput();
}
uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
campaign.amount = campaign.amount + actualAmount;
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
uint256 cutAmount = mulDiv(amount, sharePercent, 10000);
actualAmount = amount - cutAmount;
campaign.amount = campaign.amount + actualAmount;
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit FundCampaign(campaignId, actualAmount);
}
function fundCampaign(
uint80 campaignId,
uint256 amount
) external payable nonReentrant {
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0) && msg.value != amount) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
uint256 actualAmount = 0;
if (campaign.rewardToken == address(0)) {
if (msg.value != amount) {
revert InvalidInput();
}
uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
campaign.amount = campaign.amount + actualAmount;
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
uint256 cutAmount = mulDiv(amount, sharePercent, 10000);
actualAmount = amount - cutAmount;
campaign.amount = campaign.amount + actualAmount;
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit FundCampaign(campaignId, actualAmount);
}
function fundCampaign(
uint80 campaignId,
uint256 amount
) external payable nonReentrant {
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0) && msg.value != amount) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
uint256 actualAmount = 0;
if (campaign.rewardToken == address(0)) {
if (msg.value != amount) {
revert InvalidInput();
}
uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
campaign.amount = campaign.amount + actualAmount;
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
uint256 cutAmount = mulDiv(amount, sharePercent, 10000);
actualAmount = amount - cutAmount;
campaign.amount = campaign.amount + actualAmount;
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit FundCampaign(campaignId, actualAmount);
}
function fundCampaign(
uint80 campaignId,
uint256 amount
) external payable nonReentrant {
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0) && msg.value != amount) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
uint256 actualAmount = 0;
if (campaign.rewardToken == address(0)) {
if (msg.value != amount) {
revert InvalidInput();
}
uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
campaign.amount = campaign.amount + actualAmount;
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
uint256 cutAmount = mulDiv(amount, sharePercent, 10000);
actualAmount = amount - cutAmount;
campaign.amount = campaign.amount + actualAmount;
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit FundCampaign(campaignId, actualAmount);
}
function fundCampaign(
uint80 campaignId,
uint256 amount
) external payable nonReentrant {
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0) && msg.value != amount) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
uint256 actualAmount = 0;
if (campaign.rewardToken == address(0)) {
if (msg.value != amount) {
revert InvalidInput();
}
uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
campaign.amount = campaign.amount + actualAmount;
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
uint256 cutAmount = mulDiv(amount, sharePercent, 10000);
actualAmount = amount - cutAmount;
campaign.amount = campaign.amount + actualAmount;
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit FundCampaign(campaignId, actualAmount);
}
function fundCampaign(
uint80 campaignId,
uint256 amount
) external payable nonReentrant {
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0) && msg.value != amount) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
uint256 actualAmount = 0;
if (campaign.rewardToken == address(0)) {
if (msg.value != amount) {
revert InvalidInput();
}
uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
campaign.amount = campaign.amount + actualAmount;
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
uint256 cutAmount = mulDiv(amount, sharePercent, 10000);
actualAmount = amount - cutAmount;
campaign.amount = campaign.amount + actualAmount;
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit FundCampaign(campaignId, actualAmount);
}
} else {
function fundCampaign(
uint80 campaignId,
uint256 amount
) external payable nonReentrant {
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0) && msg.value != amount) {
revert InvalidValue();
}
if (campaign.rewardToken != address(0) && msg.value != 0) {
revert InvalidValue();
}
uint256 actualAmount = 0;
if (campaign.rewardToken == address(0)) {
if (msg.value != amount) {
revert InvalidInput();
}
uint256 cutAmount = mulDiv(msg.value, sharePercent, 10000);
actualAmount = msg.value - cutAmount;
campaign.amount = campaign.amount + actualAmount;
(bool sent_cut, bytes memory data2) = payable(cutReceiver).call{
value: cutAmount
}("");
if (sent_cut == false) {
revert SentNativeFailed();
}
if (msg.value != 0 ether) {
revert NativeNotAllowed();
}
uint256 cutAmount = mulDiv(amount, sharePercent, 10000);
actualAmount = amount - cutAmount;
campaign.amount = campaign.amount + actualAmount;
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
address(this),
actualAmount
);
IERC20Upgradeable(campaign.rewardToken).safeTransferFrom(
address(msg.sender),
cutReceiver,
cutAmount
);
}
emit FundCampaign(campaignId, actualAmount);
}
function withdrawFundCampaign(
uint80 campaignId,
uint256 amount,
bytes calldata signature
) external nonReentrant {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, signature) == false) {
revert InvalidSignature();
}
CampaignInfo storage campaign = campaignInfos[campaignId];
if (amount > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - amount;
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0)) {
(bool sent, bytes memory data) = payable(msg.sender).call{
value: amount
}("");
if (sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(campaign.rewardToken).safeTransfer(
address(msg.sender),
amount
);
}
emit WithdrawFundCampaign(campaignId, amount);
}
function withdrawFundCampaign(
uint80 campaignId,
uint256 amount,
bytes calldata signature
) external nonReentrant {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, signature) == false) {
revert InvalidSignature();
}
CampaignInfo storage campaign = campaignInfos[campaignId];
if (amount > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - amount;
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0)) {
(bool sent, bytes memory data) = payable(msg.sender).call{
value: amount
}("");
if (sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(campaign.rewardToken).safeTransfer(
address(msg.sender),
amount
);
}
emit WithdrawFundCampaign(campaignId, amount);
}
function withdrawFundCampaign(
uint80 campaignId,
uint256 amount,
bytes calldata signature
) external nonReentrant {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, signature) == false) {
revert InvalidSignature();
}
CampaignInfo storage campaign = campaignInfos[campaignId];
if (amount > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - amount;
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0)) {
(bool sent, bytes memory data) = payable(msg.sender).call{
value: amount
}("");
if (sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(campaign.rewardToken).safeTransfer(
address(msg.sender),
amount
);
}
emit WithdrawFundCampaign(campaignId, amount);
}
function withdrawFundCampaign(
uint80 campaignId,
uint256 amount,
bytes calldata signature
) external nonReentrant {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, signature) == false) {
revert InvalidSignature();
}
CampaignInfo storage campaign = campaignInfos[campaignId];
if (amount > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - amount;
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0)) {
(bool sent, bytes memory data) = payable(msg.sender).call{
value: amount
}("");
if (sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(campaign.rewardToken).safeTransfer(
address(msg.sender),
amount
);
}
emit WithdrawFundCampaign(campaignId, amount);
}
function withdrawFundCampaign(
uint80 campaignId,
uint256 amount,
bytes calldata signature
) external nonReentrant {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, signature) == false) {
revert InvalidSignature();
}
CampaignInfo storage campaign = campaignInfos[campaignId];
if (amount > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - amount;
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0)) {
(bool sent, bytes memory data) = payable(msg.sender).call{
value: amount
}("");
if (sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(campaign.rewardToken).safeTransfer(
address(msg.sender),
amount
);
}
emit WithdrawFundCampaign(campaignId, amount);
}
function withdrawFundCampaign(
uint80 campaignId,
uint256 amount,
bytes calldata signature
) external nonReentrant {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, signature) == false) {
revert InvalidSignature();
}
CampaignInfo storage campaign = campaignInfos[campaignId];
if (amount > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - amount;
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0)) {
(bool sent, bytes memory data) = payable(msg.sender).call{
value: amount
}("");
if (sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(campaign.rewardToken).safeTransfer(
address(msg.sender),
amount
);
}
emit WithdrawFundCampaign(campaignId, amount);
}
function withdrawFundCampaign(
uint80 campaignId,
uint256 amount,
bytes calldata signature
) external nonReentrant {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, signature) == false) {
revert InvalidSignature();
}
CampaignInfo storage campaign = campaignInfos[campaignId];
if (amount > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - amount;
if (campaign.owner != msg.sender) {
revert Unauthorized();
}
if (campaign.rewardToken == address(0)) {
(bool sent, bytes memory data) = payable(msg.sender).call{
value: amount
}("");
if (sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(campaign.rewardToken).safeTransfer(
address(msg.sender),
amount
);
}
emit WithdrawFundCampaign(campaignId, amount);
}
} else {
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
uint256[] memory accRewardPerToken = new uint256[](claimInput.taskIds.length);
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
} else {
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
} else {
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
} else {
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
} else {
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
} else {
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
} else {
function claimReward(
ClaimInput calldata claimInput
) external nonReentrant payable {
bytes32 messageHash = getMessageHash(_msgSender());
if (verifySignature(messageHash, claimInput.signature) == false) {
revert InvalidSignature();
}
if (claimInput.taskIds.length != claimInput.isValidUser.length) {
revert InvalidInput();
}
address[] memory addressPerToken = new address[](claimInput.taskIds.length);
uint8 count = 0;
uint8 counter = 0;
uint8 checkClaimCookie = 0;
uint256 reward;
for (uint256 idx; idx < claimInput.taskIds.length; ++idx) {
uint80[] memory tasksPerCampaign = claimInput.taskIds[idx];
uint80 campaignId = taskToCampaignId[tasksPerCampaign[0]];
CampaignInfo storage campaign = campaignInfos[campaignId];
if (campaign.rewardToken == cookieToken) {
checkClaimCookie = 1;
}
if (claimInput.isValidUser[idx] == 0) {
uint256 nftBalance;
uint256 balance = IERC20Upgradeable(chappyToken).balanceOf(
msg.sender
);
uint256 check = 0;
if (campaign.checkNFT == 2) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance > 0 || balance > 0) {
check += 1;
}
if (check == 0) {
revert InvalidEligibility(campaignId);
}
}
if (campaign.checkNFT == 1) {
nftBalance = IERC721Upgradeable(campaign.collection)
.balanceOf(msg.sender);
if (nftBalance == 0) {
revert InsufficentChappyNFT(campaignId);
}
if (balance < campaign.minimumBalance) {
revert InsufficentChappy(campaignId);
}
}
}
if (campaign.startAt > block.timestamp) {
revert UnavailableCampaign(campaignId);
}
reward = 0;
for (uint80 id; id < tasksPerCampaign.length; ++id) {
uint80 taskId = tasksPerCampaign[id];
if (taskToCampaignId[taskId] != campaignId) {
revert TaskNotInCampaign(taskId, campaignId);
}
if (
claimedTasks[taskId][msg.sender] == 1 &&
multipleClaim[taskId] != 1
) {
revert ClaimedTask(taskId);
}
claimedTasks[taskId][msg.sender] = 1;
if (multipleClaim[taskId] == 1) {
uint80 userPoint = claimInput.pointForMultiple[counter][0];
uint80 totalPoint = claimInput.pointForMultiple[counter][1];
if (totalPoint == 0) {
revert InvalidPoint();
}
reward += taskToAmountReward[taskId] * userPoint / totalPoint;
++counter;
reward += taskToAmountReward[taskId];
}
}
if (reward > campaign.amount) {
revert InsufficentFund(campaignId);
}
campaign.amount = campaign.amount - reward;
if (count == 0) {
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
if (addressPerToken[count-1] == addressPerToken[count]) {
accRewardPerToken[count-1] += reward;
accRewardPerToken[count] = reward;
addressPerToken[count] = campaign.rewardToken;
count++;
}
}
for (uint idx = 0; idx < addressPerToken.length; ++idx) {
if (addressPerToken[idx] == address(0)) {
(bool reward_sent, bytes memory reward_data) = payable(msg.sender).call{
value: accRewardPerToken[idx]
}("");
if (reward_sent == false) {
revert SentNativeFailed();
}
IERC20Upgradeable(addressPerToken[idx]).safeTransfer(
address(msg.sender),
accRewardPerToken[idx]
);
}
if (checkClaimCookie == 1) {
(
int answer,
) = dataFeed.latestRoundData();
if (answer == 0) {
revert InvalidPriceFeed();
}
int fourDollarInNative = (4 * 1e8 * 1e18)/answer;
if (msg.value < uint256(fourDollarInNative)) {
revert InvalidFee();
}
(bool sent, bytes memory data) = payable(cutReceiver).call{
value: uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
(bool sent_back, bytes memory data_back) = payable(msg.sender).call{
value: msg.value - uint256(fourDollarInNative)
}("");
if (sent == false) {
revert SentNativeFailed();
}
if (msg.value != 0) {
revert NativeNotAllowed();
}
}
emit ClaimReward(claimInput.taskIds);
}
function changeOracle(address newDataFeed) external {
dataFeed = AggregatorV3Interface(
newDataFeed
);
}
function checkOperator(address operator) external view returns (uint8) {
return isOperator[operator];
}
function getCookieAddress() external view returns (address) {
return cookieToken;
}
function getNonce() external view returns (uint72) {
return nonce;
}
function getCampaignInfo(
uint80 campaignId
) external view returns (CampaignInfo memory) {
return campaignInfos[campaignId];
}
function getTaskInCampaign(uint80 taskId) external view returns (uint80) {
return taskToCampaignId[taskId];
}
function checkClaimedTasks(
uint80[] calldata taskIds,
address[] memory users
) external view returns (uint80[] memory) {
if (taskIds.length != users.length) {
revert InvalidInput();
}
uint80[] memory checkIndex = new uint80[](users.length);
for (uint256 idx; idx < taskIds.length; ++idx) {
uint80 taskId = taskIds[idx];
if (claimedTasks[taskId][users[idx]] == 1) {
checkIndex[idx] = 1;
checkIndex[idx] = 0;
}
}
return checkIndex;
}
function checkClaimedTasks(
uint80[] calldata taskIds,
address[] memory users
) external view returns (uint80[] memory) {
if (taskIds.length != users.length) {
revert InvalidInput();
}
uint80[] memory checkIndex = new uint80[](users.length);
for (uint256 idx; idx < taskIds.length; ++idx) {
uint80 taskId = taskIds[idx];
if (claimedTasks[taskId][users[idx]] == 1) {
checkIndex[idx] = 1;
checkIndex[idx] = 0;
}
}
return checkIndex;
}
function checkClaimedTasks(
uint80[] calldata taskIds,
address[] memory users
) external view returns (uint80[] memory) {
if (taskIds.length != users.length) {
revert InvalidInput();
}
uint80[] memory checkIndex = new uint80[](users.length);
for (uint256 idx; idx < taskIds.length; ++idx) {
uint80 taskId = taskIds[idx];
if (claimedTasks[taskId][users[idx]] == 1) {
checkIndex[idx] = 1;
checkIndex[idx] = 0;
}
}
return checkIndex;
}
function checkClaimedTasks(
uint80[] calldata taskIds,
address[] memory users
) external view returns (uint80[] memory) {
if (taskIds.length != users.length) {
revert InvalidInput();
}
uint80[] memory checkIndex = new uint80[](users.length);
for (uint256 idx; idx < taskIds.length; ++idx) {
uint80 taskId = taskIds[idx];
if (claimedTasks[taskId][users[idx]] == 1) {
checkIndex[idx] = 1;
checkIndex[idx] = 0;
}
}
return checkIndex;
}
} else {
function getMessageHash(address user) private view returns (bytes32) {
return keccak256(abi.encodePacked(nonce, user));
}
function verifySignature(
bytes32 messageHash,
bytes calldata signature
) private returns (bool) {
++nonce;
bytes32 ethSignedMessageHash = ECDSAUpgradeable.toEthSignedMessageHash(
messageHash
);
address signer = getSignerAddress(ethSignedMessageHash, signature);
return isOperator[signer] == 1;
}
function getSignerAddress(
bytes32 messageHash,
bytes calldata signature
) private pure returns (address) {
return ECDSAUpgradeable.recover(messageHash, signature);
}
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
return prod0 / denominator;
}
assembly {
remainder := mulmod(x, y, denominator)
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
assembly {
denominator := div(denominator, twos)
prod0 := div(prod0, twos)
twos := add(div(sub(0, twos), twos), 1)
}
return result;
}
}
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
return prod0 / denominator;
}
assembly {
remainder := mulmod(x, y, denominator)
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
assembly {
denominator := div(denominator, twos)
prod0 := div(prod0, twos)
twos := add(div(sub(0, twos), twos), 1)
}
return result;
}
}
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
return prod0 / denominator;
}
assembly {
remainder := mulmod(x, y, denominator)
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
assembly {
denominator := div(denominator, twos)
prod0 := div(prod0, twos)
twos := add(div(sub(0, twos), twos), 1)
}
return result;
}
}
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
return prod0 / denominator;
}
assembly {
remainder := mulmod(x, y, denominator)
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
assembly {
denominator := div(denominator, twos)
prod0 := div(prod0, twos)
twos := add(div(sub(0, twos), twos), 1)
}
return result;
}
}
require(denominator > prod1);
uint256 remainder;
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
return prod0 / denominator;
}
assembly {
remainder := mulmod(x, y, denominator)
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
assembly {
denominator := div(denominator, twos)
prod0 := div(prod0, twos)
twos := add(div(sub(0, twos), twos), 1)
}
return result;
}
}
uint256 twos = denominator & (~denominator + 1);
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
return prod0 / denominator;
}
assembly {
remainder := mulmod(x, y, denominator)
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
assembly {
denominator := div(denominator, twos)
prod0 := div(prod0, twos)
twos := add(div(sub(0, twos), twos), 1)
}
return result;
}
}
prod0 |= prod1 * twos;
uint256 inverse = (3 * denominator) ^ 2;
result = prod0 * inverse;
}
| 3,033,899
|
pragma solidity ^0.4.21;
/**
* @title Safe maths library for big numbers.
*/
library SafeMath {
/**
* @notice Sums two numbers.
* @param a Number to add to.
* @param b Number to add.
* @return Returns the sum of two numbers.
*/
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
/**
* @notice Subtracts two numbers.
* @param a Number to subtract from.
* @param b Number to subtract.
* @return Returns the subtraction of two numbers.
*/
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
/**
* @notice Multiplies two numbers.
* @param a Number to multiply.
* @param b Number to multiply by.
* @return Returns the multiplication of two numbers.
*/
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
/**
* @notice Divides two numbers.
* @param a Number to divide.
* @param b Number to divide by.
* @return Returns the division of two numbers.
*/
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
/**
* @title ERC Token Standard #20 Interface.
* @notice https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
/**
* @title Contract function to receive approval and execute function in one call (borrowed from MiniMeToken).
*/
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
/**
* @title Owned smart contract.
*/
contract Owned {
/**
* @notice Smart ccontract events.
*/
event OwnershipTransferred(address indexed _from, address indexed _to);
/**
* @notice Address of the owner.
*/
address public owner;
/**
* @notice Makes sure that only owner can call the function.
*/
modifier _onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @notice Transfers token ownership.
* @param _newOwner Address of the new token owner.
*/
function transferOwnership(address _newOwner) public _onlyOwner {
owner = _newOwner;
}
/**
* @notice Smart contract contstructor.
*/
function Owned() public {
owner = msg.sender;
}
}
/**
* @title ERC20 token contract.
*/
contract ERC20 is ERC20Interface, Owned {
/**
* @notice Libraries for smart contract.
*/
using SafeMath for uint;
/**
* @notice Currency symbol.
*/
string public symbol;
/**
* @notice Currency name.
*/
string public name;
/**
* @notice Currency decimal places.
*/
uint8 public decimals;
/**
* @notice Currency total supply.
*/
uint public _totalSupply;
/**
* @notice Balances map.
*/
mapping(address => uint) balances;
/**
* @notice Currency allowance.
*/
mapping(address => mapping(address => uint)) allowed;
/**
* @notice Currency total supply.
* @return Returns number of minted units.
*/
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)] - balances[owner];
}
/**
* @notice Get the token balance for account `tokenOwner`.
* @param tokenOwner Address you're looking the balance for.
* @return Returns balance for the given address.
*/
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
/**
* @notice Transfer the balance from token owner's account to `to` account.
* @param to Address you're sending tokens to.
* @param tokens Number of tokens you're sending.
* @return A boolean that indicates if the operation was successful.
*/
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
/**
* @notice Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account.
* @param spender Address of the spender you're approving funds for.
* @param tokens Number of tokens you're approving.
* @return A boolean that indicates if the operation was successful.
*/
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
/**
* @notice Transfer `tokens` from the `from` account to the `to` account.
* @param from Address of the account you're sending funds from.
* @param to Address of the account you're sending funds to.
* @param tokens Number of tokens you're transfering.
* @return A boolean that indicates if the operation was successful.
*/
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
/**
* @notice Returns the amount of tokens approved by the owner that can be transferred to the spender's account.
* @param tokenOwner Token owner's address.
* @param spender Token spender's address.
* @return Number of remaining tokens to spend.
*/
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
/**
* @notice Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account. The `spender` contract function `receiveApproval(...)` is then executed
* @param spender Token spender's address.
* @param tokens Number of tokens you're approving for spending.
* @param data Data being sent.
* @return A boolean that indicates if the operation was successful.
*/
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
/**
* @notice Don't accept ETH
*/
function () public payable {
revert();
}
/**
* @notice Owner can transfer out any accidentally sent ERC20 tokens
* @param tokenAddress Address of the token you're sending.
* @param tokens Number of tokens you're sending.
* @return A boolean that indicates if the operation was successful.
*/
function transferAnyERC20Token(address tokenAddress, uint tokens) public _onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
/**
* @title For accessing crypto fiat contracts.
*/
contract Currency {
function transferOwnership(address) public pure {}
function acceptOwnership() public pure {}
function decimals() public pure returns (uint8) {}
function mint(address, uint256) public pure returns (bool) {}
function destroy(address, uint256) public pure returns (bool) {}
}
/**
* @title Payable smart contract - can receive ETH.
*/
contract Payable {
/**
* @notice Constructor which allows us to fund contract on creation.
*/
function Payable() public payable {
}
/**
* @notice `fallback` function called when eth is sent to Payable contract.
*/
function () public payable {
}
}
/**
* @title Mintable ERC20 token contract.
*/
contract MintableToken is ERC20 {
/**
* @notice Smart ccontract events.
*/
event Mint(address indexed to, uint256 amount);
event Destroy(address indexed from, uint256 amount);
/**
* @notice 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) internal returns (bool) {
_totalSupply = _totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @notice Function to destroy tokens.
* @param _from The address that we will destroy tokens from.
* @param _amount The amount of tokens to destroy.
* @return A boolean that indicates if the operation was successful.
*/
function destroy(address _from, uint256 _amount) internal returns (bool) {
if (balances[_from] >= _amount) {
_totalSupply = _totalSupply.sub(_amount);
balances[_from] = balances[_from].sub(_amount);
emit Destroy(_from, _amount);
return true;
} else {
return false;
}
}
}
/**
* @title Main Anote (ANT) smart contract.
*/
contract ANT is MintableToken, Payable {
/**
* @notice Libraries for smart contract.
*/
using SafeMath for uint;
using SafeMath for uint8;
/**
* @notice Telling us if Anote is in stabilization mode.
*/
bool public switched = false;
/**
* @notice Step for increasing Anote buy price.
*/
uint public priceStep = 10000 szabo;
/**
* @notice Anote buy price in EUR.
*/
uint public priceBuy = priceStep;
/**
* @notice Anote sell price in EUR.
*/
uint public priceSell = 0;
/**
* @notice Total deposits in EUR at any given time.
*/
uint public totalDeposits = 0;
/**
* @notice Number of all Anote fundings.
*/
uint public fundingsNumber = 0;
/**
* @notice This holds tier supply.
*/
uint public tierSupplyHolder = 25000 ether;
/**
* @notice Tier counter variable.
*/
uint public tierSupply = tierSupplyHolder;
/**
* @notice This percentage goes for crowdfunding.
*/
uint public crowdfundingFactor = 20;
/**
* @notice This percentage goes to funding referral.
*/
uint public referralFactor = 20;
/**
* @notice This percentage is being held in the contract.
*/
uint public holdingFactor = 500;
/**
* @notice This percentage of Anote has to be backuped up in EUR.
*/
uint public drainFactor = 500;
/**
* @notice Crypto fiat currencies.
*/
address[] public currencies;
/**
* @notice Ant fund balance.
*/
uint public antBalance;
/**
* @notice Crypto fiat fund balance.
*/
uint public fiatBalance;
/**
* @notice Tier counter.
*/
uint public tierCounter = 0;
/**
* @notice Is holding factor increasing or decreasing.
*/
bool public increaseHoldingFactor = false;
/**
* @notice Address of the new contract version.
*/
address public newContract = address(0);
/**
* @notice Address of the old contract version.
*/
address public oldContract = address(0);
/**
* @notice Flag telling if contract is currently being upgraded.
*/
bool public upgrading = false;
/**
* @notice Profit balances map.
*/
mapping(address => uint) balancesProfit;
/**
* @notice Crypto fiat prices.
*/
mapping(address => uint) prices;
/**
* @notice ANT users.
*/
address[] users;
/**
* @notice ANT oracles.
*/
address[] oracles;
/**
* @notice Variable used to make some functions state-changing.
*/
bool changestate = false;
// ------------------------------------------------------------------------
// PUBLIC FUNCTIONS
// ------------------------------------------------------------------------
/**
* @notice Creates ANT from ETH.
* @param _referral Address of the referral user.
* @return A boolean that indicates if the operation was successful.
*/
function ethToAnt(address _referral) public payable _notUpgrading returns (bool) {
uint investment = _splitInvestment(msg.value, _referral);
if (investment > 0) {
totalDeposits = totalDeposits.add(investment);
_mintAnt(investment);
_updateSellPrice();
return true;
} else {
return false;
}
}
/**
* @notice Creates crypto fiat from ETH.
* @param _currency Address of the fiat currency contract.
* @return A boolean that indicates if the operation was successful.
*/
function ethToFiat(address _currency) public payable _notUpgrading returns (bool) {
fiatBalance = fiatBalance.add(msg.value);
Currency c = Currency(_currency);
uint8 decimals = c.decimals();
uint amount = msg.value.mul(uint(10)**decimals).div(prices[_currency]);
c.mint(msg.sender, amount);
return true;
}
/**
* @notice Exchanges ANT to ETH.
* @param _tokenCount Number of ANT tokens to exchange for ETH.
* @return A boolean that indicates if the operation was successful.
*/
function antToEth(uint _tokenCount) public _notUpgrading returns (bool) {
if (destroy(msg.sender, _tokenCount)) {
uint withdrawal = _tokenCount.mul(priceSell).div(1 ether).mul(getCurrencyPrice(getCurrencyAddress(0))).div(1 ether);
msg.sender.transfer(withdrawal);
return true;
} else {
return false;
}
}
/**
* @notice Creates crypto fiat from ANT.
* @param _currency Contract address of crypto fiat to create.
* @param _tokenCount Number of ANT tokens to exchange for crypto fiat.
* @return A boolean that indicates if the operation was successful.
*/
function antToFiat(address _currency, uint _tokenCount) public _notUpgrading returns (bool) {
if (destroy(msg.sender, _tokenCount)) {
Currency c = Currency(_currency);
uint8 decimals = c.decimals();
uint withdrawal = _tokenCount.mul(priceSell).div(1 ether).mul(getCurrencyPrice(getCurrencyAddress(0))).div(1 ether);
uint amount = withdrawal.mul(uint(10)**decimals).div(getCurrencyPrice(_currency));
uint ethWithdrawal = _tokenCount.mul(priceSell).div(1 ether);
antBalance = antBalance.sub(ethWithdrawal);
fiatBalance = fiatBalance.add(ethWithdrawal);
c.mint(msg.sender, amount);
return true;
} else {
return false;
}
}
/**
* @notice Exchanges crypto fiat to ETH.
* @param _currency Contract address of crypto fiat being exchanged for ETH.
* @param _tokenCount Number of crypto fiat tokens being exchanged for ETH.
* @return A boolean that indicates if the operation was successful.
*/
function fiatToEth(address _currency, uint _tokenCount) public _notUpgrading returns (bool) {
Currency c = Currency(_currency);
if (c.destroy(msg.sender, _tokenCount)) {
uint withdrawal = _tokenCount.mul(getCurrencyPrice(_currency)).div(1 ether);
msg.sender.transfer(withdrawal);
return true;
} else {
return false;
}
}
/**
* @notice Function to mint ANT from fiat.
* @param _currency Address of the currency that will be used to mint ANT.
* @param _tokenCount The amount of tokens to pay for minting.
* @return A boolean that indicates if the operation was successful.
*/
function fiatToAnt(address _currency, uint _tokenCount) public _notUpgrading returns (bool) {
Currency c = Currency(_currency);
if (c.destroy(msg.sender, _tokenCount)) {
uint investment = _tokenCount.mul(getCurrencyPrice(_currency)).div(getCurrencyPrice(getCurrencyAddress(0)));
if (investment > 0) {
totalDeposits = totalDeposits.add(investment);
_mintAnt(investment);
uint ethInvestment = _tokenCount.mul(getCurrencyPrice(_currency)).div(1 ether);
fiatBalance = fiatBalance.sub(ethInvestment);
_splitInvestment(ethInvestment, address(0));
_updateSellPrice();
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* @notice Function to exchange crypto fiat for another crypto fiat.
* @param _currencyFrom Contract address of the currency that's being exchanged from.
* @param _currencyTo Contract address of the currency that's being exchanged to.
* @param _tokenCount The amount of tokens you have to exchange.
* @return A boolean that indicates if the operation was successful.
*/
function fiatToFiat(address _currencyFrom, address _currencyTo, uint _tokenCount) public _notUpgrading returns (bool) {
Currency cf = Currency(_currencyFrom);
if (cf.destroy(msg.sender, _tokenCount)) {
Currency ct = Currency(_currencyTo);
uint amount = _tokenCount.mul(getCurrencyPrice(_currencyFrom)).div(getCurrencyPrice(_currencyTo));
ct.mint(msg.sender, amount);
changestate = true;
return true;
} else {
return false;
}
}
/**
* @notice Updates crypto fiat currency price.
* @param _currency Crypto fiat currency address.
* @param _price Crypto fiat currency price in ETH.
*/
function updateCurrencyPrice(address _currency, uint _price) public _isOracle _notUpgrading {
prices[_currency] = _price;
}
/**
* @notice Returns fiat currency price in ETH.
* @param _currency Address of the fiat currency.
* @return Currency price as uint.
*/
function getCurrencyPrice(address _currency) view public returns (uint) {
return prices[_currency];
}
/**
* @notice Returns number of crypto fiat currencies.
* @return Number of crypto fiat currencies.
*/
function currenciesCount() view public returns (uint) {
return currencies.length;
}
/**
* @notice Returns fiat currency contract address.
* @param _position Crypto fiat currency index.
* @return Fiat crypto currency contract address.
*/
function getCurrencyAddress(uint _position) view public returns (address) {
return currencies[_position];
}
/**
* @notice Registers new fiat currency in ANT contract.
* @param _currency Crypto fiat currency address.
* @param _price Crypto fiat currency price in ETH.
* @return A boolean that indicates if the operation was successful.
*/
function registerCurrency(address _currency, uint _price) public _onlyOwner returns (bool) {
for (uint i = 0; i < currencies.length; i++) {
if (currencies[i] == _currency) {
return false;
}
}
currencies.push(_currency);
prices[_currency] = _price;
return true;
}
/**
* @notice Checks if ANT user exists.
* @param _user Address of user to check.
* @return A boolean that indicates if users exists.
*/
function userExists(address _user) view public returns (bool) {
for (uint i = 0; i < users.length; i++) {
if (users[i] == _user) {
return true;
}
}
return false;
}
/**
* @notice Counts ANT users.
* @return Count of ANT users.
*/
function usersCount() view public returns (uint) {
return users.length;
}
/**
* @notice Returns address of the user.
* @param _index Index of the user.
* @return User's address.
*/
function userGet(uint _index) view public returns (address) {
return users[_index];
}
/**
* @notice Closes ANT contract passing ETH to some address.
* @param _destination Destination for the ETH to get moved to.
*/
function close(address _destination) public _onlyOwner {
if (_destination != address(0)) {
selfdestruct(_destination);
} else if (newContract != address(0)) {
selfdestruct(newContract);
}
}
/**
* @notice Prepares ANT contract for upgrade to this version.
* @param _newContract Old contract address.
*/
function lockForUpgrade(address _newContract) public _onlyOwner {
newContract = _newContract;
upgrading = true;
}
/**
* @notice Finishes upgrade process by sending ETH to the new contract address and destroying the contract.
*/
function finishUpgrade() public _hasUpgradePermissions {
selfdestruct(newContract);
}
/**
* @notice Upgrades ANT contract to new version.
* @param _oldContract Old contract address.
*/
function upgrade(address _oldContract, bool _closeOld) public _onlyOwner {
ANT oldAnt = ANT(_oldContract);
uint cc = oldAnt.currenciesCount();
uint uc = oldAnt.usersCount();
uint oc = oldAnt.oraclesCount();
for (uint i = 0; i < cc; i++) {
address currency = oldAnt.getCurrencyAddress(i);
oldAnt.transferCurrencyOwnership(currency, this);
registerCurrency(currency, oldAnt.getCurrencyPrice(currency));
}
for (i = 0; i < uc; i++) {
address user = oldAnt.userGet(i);
users.push(user);
balances[user] = oldAnt.balanceOf(user);
balancesProfit[user] = oldAnt.balanceProfitOf(user);
}
for (i = 0; i < oc; i++) {
address oracle = oldAnt.oracleGet(i);
oracles.push(oracle);
}
_totalSupply = oldAnt._totalSupply();
switched = oldAnt.switched();
priceBuy = oldAnt.priceBuy();
priceSell = oldAnt.priceSell();
priceStep = oldAnt.priceStep();
totalDeposits = oldAnt.totalDeposits();
fundingsNumber = oldAnt.fundingsNumber();
tierSupply = oldAnt.tierSupply();
holdingFactor = oldAnt.holdingFactor();
drainFactor = oldAnt.drainFactor();
antBalance = oldAnt.antBalance();
fiatBalance = oldAnt.fiatBalance();
tierCounter = oldAnt.tierCounter();
oldContract = _oldContract;
if (_closeOld) {
oldAnt.finishUpgrade();
}
}
/**
* @notice Transfers fiat crypto currency ownership.
* @param _currency Address of the fiat currency contract.
* @param _newOwner New owner's address.
*/
function transferCurrencyOwnership(address _currency, address _newOwner) public _hasUpgradePermissions {
Currency c;
c = Currency(_currency);
c.transferOwnership(_newOwner);
changestate = true;
}
/**
* @notice Pulls ANT balance from previous contract version.
* @param _owner Owner of the address.
* @param _oldContract Address of the previous contract.
*/
function pullBalance(address _owner, address _oldContract) public {
ANT oldAnt = ANT(_oldContract);
balances[_owner] = oldAnt.balanceOf(_owner);
}
/**
* @notice Get the profit balance for account `tokenOwner`.
* @param _tokenOwner Address you're looking the balance for.
* @return Returns balance for the given address.
*/
function balanceProfitOf(address _tokenOwner) public view returns (uint balance) {
return balancesProfit[_tokenOwner];
}
/**
* @notice Get the profit balance for account `tokenOwner`.
* @return Returns balance for the given address.
*/
function withdrawProfit() public _notUpgrading {
uint profit = balancesProfit[msg.sender];
balancesProfit[msg.sender] = 0;
msg.sender.transfer(profit);
}
/**
* @notice Registers a new oracle.
* @param _oracle Address of the oracle to register.
*/
function registerOracle(address _oracle) public _onlyOwner _notUpgrading {
oracles.push(_oracle);
}
/**
* @notice Checks if ANT oracle exists.
* @param _oracle Address of oracle to check.
* @return A boolean that indicates if oracle exists.
*/
function oracleExists(address _oracle) public view returns (bool) {
for (uint i = 0; i < oracles.length; i++) {
if (oracles[i] == _oracle) {
return true;
}
}
return false;
}
/**
* @notice Counts ANT oracles.
* @return Count of ANT oracles.
*/
function oraclesCount() public view returns (uint) {
return oracles.length;
}
/**
* @notice Returns address of the oracle.
* @param _index Index of the oracle.
* @return Oracle's address.
*/
function oracleGet(uint _index) public view returns (address) {
return oracles[_index];
}
/**
* @notice Transfer the balance from token owner's account to `to` account.
* @param to Address you're sending tokens to.
* @param tokens Number of tokens you're sending.
* @return A boolean that indicates if the operation was successful.
*/
function transfer(address to, uint tokens) public returns (bool success) {
if (super.transfer(to, tokens)) {
if (!userExists(to)) {
users.push(to);
}
return true;
}
return false;
}
// ------------------------------------------------------------------------
// PRIVATE FUNCTIONS
// ------------------------------------------------------------------------
/**
* @notice Mints new ANT tokens.
* @param _investment Investment amount in EUR.
*/
function _mintAnt(uint _investment) private {
uint _inv = _investment;
uint _tokenCount = 0;
uint _tierSupply = tierSupply;
uint _priceBuy = priceBuy;
uint _priceStep = priceStep;
uint _tierSupplyHolder = tierSupplyHolder;
uint _tierCounter = tierCounter;
uint _tierInvestment = 0;
uint _drainFactor = drainFactor;
while (_inv > 0) {
_tierInvestment = _inv;
if (_tierInvestment >= _tierSupply) {
_tierInvestment = _tierSupply;
_inv = _inv.sub(_tierInvestment);
_tierSupply = _tierSupplyHolder;
_priceBuy = _priceBuy.add(_priceStep);
_tierCounter++;
_priceStep = _updatePriceStep(_priceStep, _tierCounter);
if (!switched) {
_drainFactor = _updateDrainFactor(_tierCounter, _drainFactor);
}
_updateHoldingFactor(_tierCounter);
} else {
_inv = 0;
_tierSupply = _tierSupply.sub(_tierInvestment);
}
_tokenCount = _tokenCount.add(_tierInvestment.mul(1 ether).div(_priceBuy));
}
tierSupply = _tierSupply;
priceBuy = _priceBuy;
priceStep = _priceStep;
tierCounter = _tierCounter;
drainFactor = _drainFactor;
if (_tokenCount > 0) {
mint(msg.sender, _tokenCount);
fundingsNumber++;
if (!userExists(msg.sender)) {
users.push(msg.sender);
}
}
}
/**
* @notice Updates price step.
*/
function _updatePriceStep(uint _priceStep, uint _tierCounter) private pure returns (uint) {
uint ps = _priceStep;
if (ps > 5 szabo && _tierCounter % 1000 == 0) {
ps /= 4;
}
return ps;
}
/**
* @notice Updates drain factor.
*/
function _updateDrainFactor(uint _tierCounter, uint _drainFactor) private pure returns (uint) {
uint df = _drainFactor;
if (df > 100 && _tierCounter % 10 == 0) {
df--;
}
return df;
}
/**
* @notice Updates holding factor.
*/
function _updateHoldingFactor(uint _tierCounter) private {
uint hf = holdingFactor;
if (_tierCounter % 100 == 0) {
if (switched) {
if (increaseHoldingFactor) {
hf++;
} else if (holdingFactor > 100) {
hf--;
}
} else {
if (holdingFactor > 105) {
hf--;
}
}
}
holdingFactor = hf;
}
/**
* @notice Checks if holding factor should be increased for backup purposes.
*/
function _checkBackup() private {
if (antBalance.mul(1 ether).div(getCurrencyPrice(getCurrencyAddress(0))).div(priceSell.mul(100).div(super.totalSupply())) < 10) {
increaseHoldingFactor = false;
} else {
increaseHoldingFactor = true;
}
}
/**
* @notice Updates ANT selling price.
*/
function _updateSellPrice() private {
if (switched) {
priceSell = priceBuy.mul(95).div(100);
} else {
priceSell = antBalance.mul(1 ether).div(getCurrencyPrice(getCurrencyAddress(0))).mul(1 ether).div(super.totalSupply()).mul(1000).div(drainFactor);
if (priceSell.mul(100).div(priceBuy) > 95) {
priceSell = priceBuy.mul(95).div(100);
if (totalDeposits > 100000 ether) {
switched = true;
}
}
}
}
/**
* @notice Splits investment between appropriate funds.
* @param _investment Investment amount.
* @param _referral Referral user's address.
* @return Investment in Euro.
*/
function _splitInvestment(uint _investment, address _referral) private returns (uint) {
uint eurInvestment = _investment.mul(1 ether).div(getCurrencyPrice(getCurrencyAddress(0)));
uint crowdfundingInvestment = _investment.mul(crowdfundingFactor).div(100);
uint referralInvestment = _investment.mul(referralFactor).div(100);
uint antInvestment = _investment.mul(holdingFactor).div(1000);
owner.transfer(crowdfundingInvestment);
if (_referral != address(0) && _referral != msg.sender) {
_referral.transfer(referralInvestment);
} else {
antInvestment = antInvestment.add(referralInvestment);
referralInvestment = 0;
}
antBalance = antBalance.add(antInvestment);
_splitInvestmentToHolders(_investment.sub(antInvestment).sub(crowdfundingInvestment).sub(referralInvestment));
return eurInvestment;
}
/**
* @notice Splits investment to holders.
* @param _investment Investment amount.
*/
function _splitInvestmentToHolders(uint _investment) private {
uint _inv = _investment;
uint uc = usersCount();
uint ts = super.totalSupply();
address user = address(0);
uint amount = 0;
for (uint i = 0; i < uc; i++) {
user = userGet(i);
if (user != owner) {
amount = _investment.mul(balanceOf(user).mul(1 ether).div(ts)).div(1 ether);
if (_inv >= amount) {
_inv = _inv.sub(amount);
balancesProfit[user] = balancesProfit[user].add(amount);
}
}
}
if (_inv > 0) {
antBalance = antBalance.add(_inv);
}
}
/**
* @notice Checks if caller has upgrade permissions.
*/
modifier _hasUpgradePermissions() {
require(msg.sender == newContract);
_;
}
/**
* @notice Checks if contract is being upgraded.
*/
modifier _notUpgrading() {
require(!upgrading);
_;
}
/**
* @notice Checks if contract is being upgraded.
*/
modifier _isOracle() {
require(oracleExists(msg.sender));
_;
}
/**
* @notice ANT constructor.
*/
function ANT(uint _initialBalance) public payable {
symbol = "ANT";
name = "Anote";
decimals = 18;
mint(msg.sender, _initialBalance);
users.push(msg.sender);
}
}
|
Upgrades ANT contract to new version. _oldContract Old contract address./
|
function upgrade(address _oldContract, bool _closeOld) public _onlyOwner {
ANT oldAnt = ANT(_oldContract);
uint cc = oldAnt.currenciesCount();
uint uc = oldAnt.usersCount();
uint oc = oldAnt.oraclesCount();
for (uint i = 0; i < cc; i++) {
address currency = oldAnt.getCurrencyAddress(i);
oldAnt.transferCurrencyOwnership(currency, this);
registerCurrency(currency, oldAnt.getCurrencyPrice(currency));
}
for (i = 0; i < uc; i++) {
address user = oldAnt.userGet(i);
users.push(user);
balances[user] = oldAnt.balanceOf(user);
balancesProfit[user] = oldAnt.balanceProfitOf(user);
}
for (i = 0; i < oc; i++) {
address oracle = oldAnt.oracleGet(i);
oracles.push(oracle);
}
_totalSupply = oldAnt._totalSupply();
switched = oldAnt.switched();
priceBuy = oldAnt.priceBuy();
priceSell = oldAnt.priceSell();
priceStep = oldAnt.priceStep();
totalDeposits = oldAnt.totalDeposits();
fundingsNumber = oldAnt.fundingsNumber();
tierSupply = oldAnt.tierSupply();
holdingFactor = oldAnt.holdingFactor();
drainFactor = oldAnt.drainFactor();
antBalance = oldAnt.antBalance();
fiatBalance = oldAnt.fiatBalance();
tierCounter = oldAnt.tierCounter();
oldContract = _oldContract;
if (_closeOld) {
oldAnt.finishUpgrade();
}
}
| 14,105,569
|
// File: @openzeppelin/contracts/math/SafeMath.sol
// 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;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: solidity/contracts/converter/ConverterVersion.sol
pragma solidity 0.6.12;
contract ConverterVersion {
uint16 public constant version = 46;
}
// File: solidity/contracts/utility/interfaces/IOwned.sol
pragma solidity 0.6.12;
/*
Owned contract interface
*/
interface IOwned {
// this function isn't since the compiler emits automatically generated getter functions as external
function owner() external view returns (address);
function transferOwnership(address _newOwner) external;
function acceptOwnership() external;
}
// File: solidity/contracts/converter/interfaces/IConverterAnchor.sol
pragma solidity 0.6.12;
/*
Converter Anchor interface
*/
interface IConverterAnchor is IOwned {
}
// File: solidity/contracts/converter/interfaces/IConverter.sol
pragma solidity 0.6.12;
/*
Converter interface
*/
interface IConverter is IOwned {
function converterType() external pure returns (uint16);
function anchor() external view returns (IConverterAnchor);
function isActive() external view returns (bool);
function targetAmountAndFee(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _amount
) external view returns (uint256, uint256);
function convert(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _amount,
address _trader,
address payable _beneficiary
) external payable returns (uint256);
function conversionFee() external view returns (uint32);
function maxConversionFee() external view returns (uint32);
function reserveBalance(IERC20 _reserveToken) external view returns (uint256);
receive() external payable;
function transferAnchorOwnership(address _newOwner) external;
function acceptAnchorOwnership() external;
function setConversionFee(uint32 _conversionFee) external;
function addReserve(IERC20 _token, uint32 _weight) external;
function transferReservesOnUpgrade(address _newConverter) external;
function onUpgradeComplete() external;
// deprecated, backward compatibility
function token() external view returns (IConverterAnchor);
function transferTokenOwnership(address _newOwner) external;
function acceptTokenOwnership() external;
function connectors(IERC20 _address)
external
view
returns (
uint256,
uint32,
bool,
bool,
bool
);
function getConnectorBalance(IERC20 _connectorToken) external view returns (uint256);
function connectorTokens(uint256 _index) external view returns (IERC20);
function connectorTokenCount() external view returns (uint16);
/**
* @dev triggered when the converter is activated
*
* @param _type converter type
* @param _anchor converter anchor
* @param _activated true if the converter was activated, false if it was deactivated
*/
event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated);
/**
* @dev triggered when a conversion between two tokens occurs
*
* @param _fromToken source ERC20 token
* @param _toToken target ERC20 token
* @param _trader wallet that initiated the trade
* @param _amount input amount in units of the source token
* @param _return output amount minus conversion fee in units of the target token
* @param _conversionFee conversion fee in units of the target token
*/
event Conversion(
IERC20 indexed _fromToken,
IERC20 indexed _toToken,
address indexed _trader,
uint256 _amount,
uint256 _return,
int256 _conversionFee
);
/**
* @dev triggered when the rate between two tokens in the converter changes
* note that the event might be dispatched for rate updates between any two tokens in the converter
*
* @param _token1 address of the first token
* @param _token2 address of the second token
* @param _rateN rate of 1 unit of `_token1` in `_token2` (numerator)
* @param _rateD rate of 1 unit of `_token1` in `_token2` (denominator)
*/
event TokenRateUpdate(IERC20 indexed _token1, IERC20 indexed _token2, uint256 _rateN, uint256 _rateD);
/**
* @dev triggered when the conversion fee is updated
*
* @param _prevFee previous fee percentage, represented in ppm
* @param _newFee new fee percentage, represented in ppm
*/
event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
}
// File: solidity/contracts/converter/interfaces/IConverterUpgrader.sol
pragma solidity 0.6.12;
/*
Converter Upgrader interface
*/
interface IConverterUpgrader {
function upgrade(bytes32 _version) external;
function upgrade(uint16 _version) external;
}
// File: solidity/contracts/utility/interfaces/ITokenHolder.sol
pragma solidity 0.6.12;
/*
Token Holder interface
*/
interface ITokenHolder is IOwned {
receive() external payable;
function withdrawTokens(
IERC20 token,
address payable to,
uint256 amount
) external;
function withdrawTokensMultiple(
IERC20[] calldata tokens,
address payable to,
uint256[] calldata amounts
) external;
}
// File: solidity/contracts/INetworkSettings.sol
pragma solidity 0.6.12;
interface INetworkSettings {
function networkFeeParams() external view returns (ITokenHolder, uint32);
function networkFeeWallet() external view returns (ITokenHolder);
function networkFee() external view returns (uint32);
}
// File: solidity/contracts/token/interfaces/IDSToken.sol
pragma solidity 0.6.12;
/*
DSToken interface
*/
interface IDSToken is IConverterAnchor, IERC20 {
function issue(address _to, uint256 _amount) external;
function destroy(address _from, uint256 _amount) external;
}
// File: solidity/contracts/utility/MathEx.sol
pragma solidity 0.6.12;
/**
* @dev This library provides a set of complex math operations.
*/
library MathEx {
uint256 private constant MAX_EXP_BIT_LEN = 4;
uint256 private constant MAX_EXP = 2**MAX_EXP_BIT_LEN - 1;
uint256 private constant MAX_UINT128 = 2**128 - 1;
/**
* @dev returns the largest integer smaller than or equal to the square root of a positive integer
*
* @param _num a positive integer
*
* @return the largest integer smaller than or equal to the square root of the positive integer
*/
function floorSqrt(uint256 _num) internal pure returns (uint256) {
uint256 x = _num / 2 + 1;
uint256 y = (x + _num / x) / 2;
while (x > y) {
x = y;
y = (x + _num / x) / 2;
}
return x;
}
/**
* @dev returns the smallest integer larger than or equal to the square root of a positive integer
*
* @param _num a positive integer
*
* @return the smallest integer larger than or equal to the square root of the positive integer
*/
function ceilSqrt(uint256 _num) internal pure returns (uint256) {
uint256 x = floorSqrt(_num);
return x * x == _num ? x : x + 1;
}
/**
* @dev computes a powered ratio
*
* @param _n ratio numerator
* @param _d ratio denominator
* @param _exp ratio exponent
*
* @return powered ratio's numerator and denominator
*/
function poweredRatio(
uint256 _n,
uint256 _d,
uint256 _exp
) internal pure returns (uint256, uint256) {
require(_exp <= MAX_EXP, "ERR_EXP_TOO_LARGE");
uint256[MAX_EXP_BIT_LEN] memory ns;
uint256[MAX_EXP_BIT_LEN] memory ds;
(ns[0], ds[0]) = reducedRatio(_n, _d, MAX_UINT128);
for (uint256 i = 0; (_exp >> i) > 1; i++) {
(ns[i + 1], ds[i + 1]) = reducedRatio(ns[i] ** 2, ds[i] ** 2, MAX_UINT128);
}
uint256 n = 1;
uint256 d = 1;
for (uint256 i = 0; (_exp >> i) > 0; i++) {
if (((_exp >> i) & 1) > 0) {
(n, d) = reducedRatio(n * ns[i], d * ds[i], MAX_UINT128);
}
}
return (n, d);
}
/**
* @dev computes a reduced-scalar ratio
*
* @param _n ratio numerator
* @param _d ratio denominator
* @param _max maximum desired scalar
*
* @return ratio's numerator and denominator
*/
function reducedRatio(
uint256 _n,
uint256 _d,
uint256 _max
) internal pure returns (uint256, uint256) {
(uint256 n, uint256 d) = (_n, _d);
if (n > _max || d > _max) {
(n, d) = normalizedRatio(n, d, _max);
}
if (n != d) {
return (n, d);
}
return (1, 1);
}
/**
* @dev computes "scale * a / (a + b)" and "scale * b / (a + b)".
*/
function normalizedRatio(
uint256 _a,
uint256 _b,
uint256 _scale
) internal pure returns (uint256, uint256) {
if (_a <= _b) {
return accurateRatio(_a, _b, _scale);
}
(uint256 y, uint256 x) = accurateRatio(_b, _a, _scale);
return (x, y);
}
/**
* @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a <= b".
*/
function accurateRatio(
uint256 _a,
uint256 _b,
uint256 _scale
) internal pure returns (uint256, uint256) {
uint256 maxVal = uint256(-1) / _scale;
if (_a > maxVal) {
uint256 c = _a / (maxVal + 1) + 1;
_a /= c; // we can now safely compute `_a * _scale`
_b /= c;
}
if (_a != _b) {
uint256 n = _a * _scale;
uint256 d = _a + _b; // can overflow
if (d >= _a) {
// no overflow in `_a + _b`
uint256 x = roundDiv(n, d); // we can now safely compute `_scale - x`
uint256 y = _scale - x;
return (x, y);
}
if (n < _b - (_b - _a) / 2) {
return (0, _scale); // `_a * _scale < (_a + _b) / 2 < MAX_UINT256 < _a + _b`
}
return (1, _scale - 1); // `(_a + _b) / 2 < _a * _scale < MAX_UINT256 < _a + _b`
}
return (_scale / 2, _scale / 2); // allow reduction to `(1, 1)` in the calling function
}
/**
* @dev computes the nearest integer to a given quotient without overflowing or underflowing.
*/
function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) {
return _n / _d + (_n % _d) / (_d - _d / 2);
}
/**
* @dev returns the average number of decimal digits in a given list of positive integers
*
* @param _values list of positive integers
*
* @return the average number of decimal digits in the given list of positive integers
*/
function geometricMean(uint256[] memory _values) internal pure returns (uint256) {
uint256 numOfDigits = 0;
uint256 length = _values.length;
for (uint256 i = 0; i < length; i++) {
numOfDigits += decimalLength(_values[i]);
}
return uint256(10)**(roundDivUnsafe(numOfDigits, length) - 1);
}
/**
* @dev returns the number of decimal digits in a given positive integer
*
* @param _x positive integer
*
* @return the number of decimal digits in the given positive integer
*/
function decimalLength(uint256 _x) internal pure returns (uint256) {
uint256 y = 0;
for (uint256 x = _x; x > 0; x /= 10) {
y++;
}
return y;
}
/**
* @dev returns the nearest integer to a given quotient
* the computation is overflow-safe assuming that the input is sufficiently small
*
* @param _n quotient numerator
* @param _d quotient denominator
*
* @return the nearest integer to the given quotient
*/
function roundDivUnsafe(uint256 _n, uint256 _d) internal pure returns (uint256) {
return (_n + _d / 2) / _d;
}
/**
* @dev returns the larger of two values
*
* @param _val1 the first value
* @param _val2 the second value
*/
function max(uint256 _val1, uint256 _val2) internal pure returns (uint256) {
return _val1 > _val2 ? _val1 : _val2;
}
}
// File: solidity/contracts/utility/Owned.sol
pragma solidity 0.6.12;
/**
* @dev This contract provides support and utilities for contract ownership.
*/
contract Owned is IOwned {
address public override owner;
address public newOwner;
/**
* @dev triggered when the owner is updated
*
* @param _prevOwner previous owner
* @param _newOwner new owner
*/
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
* @dev initializes a new Owned instance
*/
constructor() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
_ownerOnly();
_;
}
// error message binary size optimization
function _ownerOnly() internal view {
require(msg.sender == owner, "ERR_ACCESS_DENIED");
}
/**
* @dev allows transferring the contract ownership
* the new owner still needs to accept the transfer
* can only be called by the contract owner
*
* @param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public override ownerOnly {
require(_newOwner != owner, "ERR_SAME_OWNER");
newOwner = _newOwner;
}
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public override {
require(msg.sender == newOwner, "ERR_ACCESS_DENIED");
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// File: solidity/contracts/utility/Utils.sol
pragma solidity 0.6.12;
/**
* @dev Utilities & Common Modifiers
*/
contract Utils {
uint32 internal constant PPM_RESOLUTION = 1000000;
IERC20 internal constant NATIVE_TOKEN_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 _value) {
_greaterThanZero(_value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 _value) internal pure {
require(_value > 0, "ERR_ZERO_VALUE");
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
_validAddress(_address);
_;
}
// error message binary size optimization
function _validAddress(address _address) internal pure {
require(_address != address(0), "ERR_INVALID_ADDRESS");
}
// ensures that the portion is valid
modifier validPortion(uint32 _portion) {
_validPortion(_portion);
_;
}
// error message binary size optimization
function _validPortion(uint32 _portion) internal pure {
require(_portion > 0 && _portion <= PPM_RESOLUTION, "ERR_INVALID_PORTION");
}
// validates an external address - currently only checks that it isn't null or this
modifier validExternalAddress(address _address) {
_validExternalAddress(_address);
_;
}
// error message binary size optimization
function _validExternalAddress(address _address) internal view {
require(_address != address(0) && _address != address(this), "ERR_INVALID_EXTERNAL_ADDRESS");
}
// ensures that the fee is valid
modifier validFee(uint32 fee) {
_validFee(fee);
_;
}
// error message binary size optimization
function _validFee(uint32 fee) internal pure {
require(fee <= PPM_RESOLUTION, "ERR_INVALID_FEE");
}
}
// File: solidity/contracts/utility/interfaces/IContractRegistry.sol
pragma solidity 0.6.12;
/*
Contract Registry interface
*/
interface IContractRegistry {
function addressOf(bytes32 _contractName) external view returns (address);
}
// File: solidity/contracts/utility/ContractRegistryClient.sol
pragma solidity 0.6.12;
/**
* @dev This is the base contract for ContractRegistry clients.
*/
contract ContractRegistryClient is Owned, Utils {
bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry";
bytes32 internal constant BANCOR_NETWORK = "BancorNetwork";
bytes32 internal constant BANCOR_FORMULA = "BancorFormula";
bytes32 internal constant CONVERTER_FACTORY = "ConverterFactory";
bytes32 internal constant CONVERSION_PATH_FINDER = "ConversionPathFinder";
bytes32 internal constant CONVERTER_UPGRADER = "BancorConverterUpgrader";
bytes32 internal constant CONVERTER_REGISTRY = "BancorConverterRegistry";
bytes32 internal constant CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData";
bytes32 internal constant BNT_TOKEN = "BNTToken";
bytes32 internal constant BANCOR_X = "BancorX";
bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader";
bytes32 internal constant LIQUIDITY_PROTECTION = "LiquidityProtection";
bytes32 internal constant NETWORK_SETTINGS = "NetworkSettings";
IContractRegistry public registry; // address of the current contract-registry
IContractRegistry public prevRegistry; // address of the previous contract-registry
bool public onlyOwnerCanUpdateRegistry; // only an owner can update the contract-registry
/**
* @dev verifies that the caller is mapped to the given contract name
*
* @param _contractName contract name
*/
modifier only(bytes32 _contractName) {
_only(_contractName);
_;
}
// error message binary size optimization
function _only(bytes32 _contractName) internal view {
require(msg.sender == addressOf(_contractName), "ERR_ACCESS_DENIED");
}
/**
* @dev initializes a new ContractRegistryClient instance
*
* @param _registry address of a contract-registry contract
*/
constructor(IContractRegistry _registry) internal validAddress(address(_registry)) {
registry = IContractRegistry(_registry);
prevRegistry = IContractRegistry(_registry);
}
/**
* @dev updates to the new contract-registry
*/
function updateRegistry() public {
// verify that this function is permitted
require(msg.sender == owner || !onlyOwnerCanUpdateRegistry, "ERR_ACCESS_DENIED");
// get the new contract-registry
IContractRegistry newRegistry = IContractRegistry(addressOf(CONTRACT_REGISTRY));
// verify that the new contract-registry is different and not zero
require(newRegistry != registry && address(newRegistry) != address(0), "ERR_INVALID_REGISTRY");
// verify that the new contract-registry is pointing to a non-zero contract-registry
require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY");
// save a backup of the current contract-registry before replacing it
prevRegistry = registry;
// replace the current contract-registry with the new contract-registry
registry = newRegistry;
}
/**
* @dev restores the previous contract-registry
*/
function restoreRegistry() public ownerOnly {
// restore the previous contract-registry
registry = prevRegistry;
}
/**
* @dev restricts the permission to update the contract-registry
*
* @param _onlyOwnerCanUpdateRegistry indicates whether or not permission is restricted to owner only
*/
function restrictRegistryUpdate(bool _onlyOwnerCanUpdateRegistry) public ownerOnly {
// change the permission to update the contract-registry
onlyOwnerCanUpdateRegistry = _onlyOwnerCanUpdateRegistry;
}
/**
* @dev returns the address associated with the given contract name
*
* @param _contractName contract name
*
* @return contract address
*/
function addressOf(bytes32 _contractName) internal view returns (address) {
return registry.addressOf(_contractName);
}
}
// File: solidity/contracts/utility/ReentrancyGuard.sol
pragma solidity 0.6.12;
/**
* @dev This contract provides protection against calling a function
* (directly or indirectly) from within itself.
*/
contract ReentrancyGuard {
uint256 private constant UNLOCKED = 1;
uint256 private constant LOCKED = 2;
// LOCKED while protected code is being executed, UNLOCKED otherwise
uint256 private state = UNLOCKED;
/**
* @dev ensures instantiation only by sub-contracts
*/
constructor() internal {}
// protects a function against reentrancy attacks
modifier protected() {
_protected();
state = LOCKED;
_;
state = UNLOCKED;
}
// error message binary size optimization
function _protected() internal view {
require(state == UNLOCKED, "ERR_REENTRANCY");
}
}
// File: solidity/contracts/utility/Time.sol
pragma solidity 0.6.12;
/*
Time implementing contract
*/
contract Time {
/**
* @dev returns the current time
*/
function time() internal view virtual returns (uint256) {
return block.timestamp;
}
}
// File: solidity/contracts/converter/types/standard-pool/StandardPoolConverter.sol
pragma solidity 0.6.12;
/**
* @dev This contract is a specialized version of the converter, which is
* optimized for a liquidity pool that has 2 reserves with 50%/50% weights.
*/
contract StandardPoolConverter is ConverterVersion, IConverter, ContractRegistryClient, ReentrancyGuard, Time {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using MathEx for *;
uint256 private constant MAX_UINT128 = 2**128 - 1;
uint256 private constant MAX_UINT112 = 2**112 - 1;
uint256 private constant MAX_UINT32 = 2**32 - 1;
uint256 private constant AVERAGE_RATE_PERIOD = 10 minutes;
uint256 private __reserveBalances;
uint256 private _reserveBalancesProduct;
IERC20[] private __reserveTokens;
mapping(IERC20 => uint256) private __reserveIds;
IConverterAnchor public override anchor; // converter anchor contract
uint32 public override maxConversionFee; // maximum conversion fee, represented in ppm, 0...1000000
uint32 public override conversionFee; // current conversion fee, represented in ppm, 0...maxConversionFee
// average rate details:
// bits 0...111 represent the numerator of the rate between reserve token 0 and reserve token 1
// bits 111...223 represent the denominator of the rate between reserve token 0 and reserve token 1
// bits 224...255 represent the update-time of the rate between reserve token 0 and reserve token 1
// where `numerator / denominator` gives the worth of one reserve token 0 in units of reserve token 1
uint256 public averageRateInfo;
/**
* @dev triggered after liquidity is added
*
* @param _provider liquidity provider
* @param _reserveToken reserve token address
* @param _amount reserve token amount
* @param _newBalance reserve token new balance
* @param _newSupply pool token new supply
*/
event LiquidityAdded(
address indexed _provider,
IERC20 indexed _reserveToken,
uint256 _amount,
uint256 _newBalance,
uint256 _newSupply
);
/**
* @dev triggered after liquidity is removed
*
* @param _provider liquidity provider
* @param _reserveToken reserve token address
* @param _amount reserve token amount
* @param _newBalance reserve token new balance
* @param _newSupply pool token new supply
*/
event LiquidityRemoved(
address indexed _provider,
IERC20 indexed _reserveToken,
uint256 _amount,
uint256 _newBalance,
uint256 _newSupply
);
/**
* @dev initializes a new StandardPoolConverter instance
*
* @param _anchor anchor governed by the converter
* @param _registry address of a contract registry contract
* @param _maxConversionFee maximum conversion fee, represented in ppm
*/
constructor(
IConverterAnchor _anchor,
IContractRegistry _registry,
uint32 _maxConversionFee
) public ContractRegistryClient(_registry) validAddress(address(_anchor)) validConversionFee(_maxConversionFee) {
anchor = _anchor;
maxConversionFee = _maxConversionFee;
}
// ensures that the converter is active
modifier active() {
_active();
_;
}
// error message binary size optimization
function _active() internal view {
require(isActive(), "ERR_INACTIVE");
}
// ensures that the converter is not active
modifier inactive() {
_inactive();
_;
}
// error message binary size optimization
function _inactive() internal view {
require(!isActive(), "ERR_ACTIVE");
}
// validates a reserve token address - verifies that the address belongs to one of the reserve tokens
modifier validReserve(IERC20 _address) {
_validReserve(_address);
_;
}
// error message binary size optimization
function _validReserve(IERC20 _address) internal view {
require(__reserveIds[_address] != 0, "ERR_INVALID_RESERVE");
}
// validates conversion fee
modifier validConversionFee(uint32 _conversionFee) {
_validConversionFee(_conversionFee);
_;
}
// error message binary size optimization
function _validConversionFee(uint32 _conversionFee) internal pure {
require(_conversionFee <= PPM_RESOLUTION, "ERR_INVALID_CONVERSION_FEE");
}
// validates reserve weight
modifier validReserveWeight(uint32 _weight) {
_validReserveWeight(_weight);
_;
}
// error message binary size optimization
function _validReserveWeight(uint32 _weight) internal pure {
require(_weight == PPM_RESOLUTION / 2, "ERR_INVALID_RESERVE_WEIGHT");
}
/**
* @dev returns the converter type
*
* @return see the converter types in the the main contract doc
*/
function converterType() public pure virtual override returns (uint16) {
return 3;
}
/**
* @dev deposits ether
* can only be called if the converter has an ETH reserve
*/
receive() external payable override(IConverter) validReserve(NATIVE_TOKEN_ADDRESS) {}
/**
* @dev checks whether or not the converter version is 28 or higher
*
* @return true, since the converter version is 28 or higher
*/
function isV28OrHigher() public pure returns (bool) {
return true;
}
/**
* @dev returns true if the converter is active, false otherwise
*
* @return true if the converter is active, false otherwise
*/
function isActive() public view virtual override returns (bool) {
return anchor.owner() == address(this);
}
/**
* @dev transfers the anchor ownership
* the new owner needs to accept the transfer
* can only be called by the converter upgrader while the upgrader is the owner
* note that prior to version 28, you should use 'transferAnchorOwnership' instead
*
* @param _newOwner new token owner
*/
function transferAnchorOwnership(address _newOwner) public override ownerOnly only(CONVERTER_UPGRADER) {
anchor.transferOwnership(_newOwner);
}
/**
* @dev accepts ownership of the anchor after an ownership transfer
* most converters are also activated as soon as they accept the anchor ownership
* can only be called by the contract owner
* note that prior to version 28, you should use 'acceptTokenOwnership' instead
*/
function acceptAnchorOwnership() public virtual override ownerOnly {
// verify the the converter has exactly two reserves
require(reserveTokenCount() == 2, "ERR_INVALID_RESERVE_COUNT");
anchor.acceptOwnership();
syncReserveBalances(0);
emit Activation(converterType(), anchor, true);
}
/**
* @dev updates the current conversion fee
* can only be called by the contract owner
*
* @param _conversionFee new conversion fee, represented in ppm
*/
function setConversionFee(uint32 _conversionFee) public override ownerOnly {
require(_conversionFee <= maxConversionFee, "ERR_INVALID_CONVERSION_FEE");
emit ConversionFeeUpdate(conversionFee, _conversionFee);
conversionFee = _conversionFee;
}
/**
* @dev transfers reserve balances to a new converter during an upgrade
* can only be called by the converter upgraded which should be set at its owner
*
* @param _newConverter address of the converter to receive the new amount
*/
function transferReservesOnUpgrade(address _newConverter)
external
override
protected
ownerOnly
only(CONVERTER_UPGRADER)
{
uint256 reserveCount = __reserveTokens.length;
for (uint256 i = 0; i < reserveCount; ++i) {
IERC20 reserveToken = __reserveTokens[i];
uint256 amount;
if (reserveToken == NATIVE_TOKEN_ADDRESS) {
amount = address(this).balance;
} else {
amount = reserveToken.balanceOf(address(this));
}
safeTransfer(reserveToken, _newConverter, amount);
syncReserveBalance(reserveToken);
}
}
/**
* @dev upgrades the converter to the latest version
* can only be called by the owner
* note that the owner needs to call acceptOwnership on the new converter after the upgrade
*/
function upgrade() public ownerOnly {
IConverterUpgrader converterUpgrader = IConverterUpgrader(addressOf(CONVERTER_UPGRADER));
// trigger de-activation event
emit Activation(converterType(), anchor, false);
transferOwnership(address(converterUpgrader));
converterUpgrader.upgrade(version);
acceptOwnership();
}
/**
* @dev executed by the upgrader at the end of the upgrade process to handle custom pool logic
*/
function onUpgradeComplete()
external
override
protected
ownerOnly
only(CONVERTER_UPGRADER)
{
(uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2);
_reserveBalancesProduct = reserveBalance0 * reserveBalance1;
}
/**
* @dev returns the number of reserve tokens
* note that prior to version 17, you should use 'connectorTokenCount' instead
*
* @return number of reserve tokens
*/
function reserveTokenCount() public view returns (uint16) {
return uint16(__reserveTokens.length);
}
/**
* @dev returns the array of reserve tokens
*
* @return array of reserve tokens
*/
function reserveTokens() public view returns (IERC20[] memory) {
return __reserveTokens;
}
/**
* @dev defines a new reserve token for the converter
* can only be called by the owner while the converter is inactive
*
* @param _token address of the reserve token
* @param _weight reserve weight, represented in ppm, 1-1000000
*/
function addReserve(IERC20 _token, uint32 _weight)
public
virtual
override
ownerOnly
inactive
validExternalAddress(address(_token))
validReserveWeight(_weight)
{
// validate input
require(address(_token) != address(anchor) && __reserveIds[_token] == 0, "ERR_INVALID_RESERVE");
require(reserveTokenCount() < 2, "ERR_INVALID_RESERVE_COUNT");
__reserveTokens.push(_token);
__reserveIds[_token] = __reserveTokens.length;
}
/**
* @dev returns the reserve's weight
* added in version 28
*
* @param _reserveToken reserve token contract address
*
* @return reserve weight
*/
function reserveWeight(IERC20 _reserveToken) public view validReserve(_reserveToken) returns (uint32) {
return PPM_RESOLUTION / 2;
}
/**
* @dev returns the balance of a given reserve token
*
* @param _reserveToken reserve token contract address
*
* @return the balance of the given reserve token
*/
function reserveBalance(IERC20 _reserveToken) public view override returns (uint256) {
uint256 reserveId = __reserveIds[_reserveToken];
require(reserveId != 0, "ERR_INVALID_RESERVE");
return reserveBalance(reserveId);
}
/**
* @dev returns the balances of both reserve tokens
*
* @return the balances of both reserve tokens
*/
function reserveBalances() public view returns (uint256, uint256) {
return reserveBalances(1, 2);
}
/**
* @dev syncs all stored reserve balances
*/
function syncReserveBalances() external {
syncReserveBalances(0);
}
/**
* @dev calculates the accumulated network fee and transfers it to the network fee wallet
*/
function processNetworkFees() external protected {
(uint256 reserveBalance0, uint256 reserveBalance1) = processNetworkFees(0);
_reserveBalancesProduct = reserveBalance0 * reserveBalance1;
}
/**
* @dev calculates the accumulated network fee and transfers it to the network fee wallet
*
* @param _value amount of ether to exclude from the ether reserve balance (if relevant)
*
* @return new reserve balances
*/
function processNetworkFees(uint256 _value) internal returns (uint256, uint256) {
syncReserveBalances(_value);
(uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2);
(ITokenHolder wallet, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1);
reserveBalance0 -= fee0;
reserveBalance1 -= fee1;
setReserveBalances(1, 2, reserveBalance0, reserveBalance1);
safeTransfer(__reserveTokens[0], address(wallet), fee0);
safeTransfer(__reserveTokens[1], address(wallet), fee1);
return (reserveBalance0, reserveBalance1);
}
/**
* @dev returns the reserve balances of the given reserve tokens minus their corresponding fees
*
* @param _reserveTokens reserve tokens
*
* @return reserve balances minus their corresponding fees
*/
function baseReserveBalances(IERC20[] memory _reserveTokens) internal view returns (uint256[2] memory) {
uint256 reserveId0 = __reserveIds[_reserveTokens[0]];
uint256 reserveId1 = __reserveIds[_reserveTokens[1]];
(uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(reserveId0, reserveId1);
(, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1);
return [reserveBalance0 - fee0, reserveBalance1 - fee1];
}
/**
* @dev converts a specific amount of source tokens to target tokens
* can only be called by the bancor network contract
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader address of the caller who executed the conversion
* @param _beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function convert(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _amount,
address _trader,
address payable _beneficiary
) public payable override protected only(BANCOR_NETWORK) returns (uint256) {
// validate input
require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET");
return doConvert(_sourceToken, _targetToken, _amount, _trader, _beneficiary);
}
/**
* @dev returns the conversion fee for a given target amount
*
* @param _targetAmount target amount
*
* @return conversion fee
*/
function calculateFee(uint256 _targetAmount) internal view returns (uint256) {
return _targetAmount.mul(conversionFee) / PPM_RESOLUTION;
}
/**
* @dev returns the conversion fee taken from a given target amount
*
* @param _targetAmount target amount
*
* @return conversion fee
*/
function calculateFeeInv(uint256 _targetAmount) internal view returns (uint256) {
return _targetAmount.mul(conversionFee).div(PPM_RESOLUTION - conversionFee);
}
/**
* @dev loads the stored reserve balance for a given reserve id
*
* @param _reserveId reserve id
*/
function reserveBalance(uint256 _reserveId) internal view returns (uint256) {
return decodeReserveBalance(__reserveBalances, _reserveId);
}
/**
* @dev loads the stored reserve balances
*
* @param _sourceId source reserve id
* @param _targetId target reserve id
*/
function reserveBalances(uint256 _sourceId, uint256 _targetId) internal view returns (uint256, uint256) {
require((_sourceId == 1 && _targetId == 2) || (_sourceId == 2 && _targetId == 1), "ERR_INVALID_RESERVES");
return decodeReserveBalances(__reserveBalances, _sourceId, _targetId);
}
/**
* @dev stores the stored reserve balance for a given reserve id
*
* @param _reserveId reserve id
* @param _reserveBalance reserve balance
*/
function setReserveBalance(uint256 _reserveId, uint256 _reserveBalance) internal {
require(_reserveBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW");
uint256 otherBalance = decodeReserveBalance(__reserveBalances, 3 - _reserveId);
__reserveBalances = encodeReserveBalances(_reserveBalance, _reserveId, otherBalance, 3 - _reserveId);
}
/**
* @dev stores the stored reserve balances
*
* @param _sourceId source reserve id
* @param _targetId target reserve id
* @param _sourceBalance source reserve balance
* @param _targetBalance target reserve balance
*/
function setReserveBalances(
uint256 _sourceId,
uint256 _targetId,
uint256 _sourceBalance,
uint256 _targetBalance
) internal {
require(_sourceBalance <= MAX_UINT128 && _targetBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW");
__reserveBalances = encodeReserveBalances(_sourceBalance, _sourceId, _targetBalance, _targetId);
}
/**
* @dev syncs the stored reserve balance for a given reserve with the real reserve balance
*
* @param _reserveToken address of the reserve token
*/
function syncReserveBalance(IERC20 _reserveToken) internal {
uint256 reserveId = __reserveIds[_reserveToken];
uint256 balance =
_reserveToken == NATIVE_TOKEN_ADDRESS ? address(this).balance : _reserveToken.balanceOf(address(this));
setReserveBalance(reserveId, balance);
}
/**
* @dev syncs all stored reserve balances, excluding a given amount of ether from the ether reserve balance (if relevant)
*
* @param _value amount of ether to exclude from the ether reserve balance (if relevant)
*/
function syncReserveBalances(uint256 _value) internal {
IERC20 _reserveToken0 = __reserveTokens[0];
IERC20 _reserveToken1 = __reserveTokens[1];
uint256 balance0 =
_reserveToken0 == NATIVE_TOKEN_ADDRESS
? address(this).balance - _value
: _reserveToken0.balanceOf(address(this));
uint256 balance1 =
_reserveToken1 == NATIVE_TOKEN_ADDRESS
? address(this).balance - _value
: _reserveToken1.balanceOf(address(this));
setReserveBalances(1, 2, balance0, balance1);
}
/**
* @dev helper, dispatches the Conversion event
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _trader address of the caller who executed the conversion
* @param _amount amount purchased/sold (in the source token)
* @param _returnAmount amount returned (in the target token)
*/
function dispatchConversionEvent(
IERC20 _sourceToken,
IERC20 _targetToken,
address _trader,
uint256 _amount,
uint256 _returnAmount,
uint256 _feeAmount
) internal {
emit Conversion(_sourceToken, _targetToken, _trader, _amount, _returnAmount, int256(_feeAmount));
}
/**
* @dev returns the expected amount and expected fee for converting one reserve to another
*
* @param _sourceToken address of the source reserve token contract
* @param _targetToken address of the target reserve token contract
* @param _amount amount of source reserve tokens converted
*
* @return expected amount in units of the target reserve token
* @return expected fee in units of the target reserve token
*/
function targetAmountAndFee(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _amount
) public view virtual override active returns (uint256, uint256) {
uint256 sourceId = __reserveIds[_sourceToken];
uint256 targetId = __reserveIds[_targetToken];
(uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
return targetAmountAndFee(_sourceToken, _targetToken, sourceBalance, targetBalance, _amount);
}
/**
* @dev returns the expected amount and expected fee for converting one reserve to another
*
* @param _sourceBalance balance in the source reserve token contract
* @param _targetBalance balance in the target reserve token contract
* @param _amount amount of source reserve tokens converted
*
* @return expected amount in units of the target reserve token
* @return expected fee in units of the target reserve token
*/
function targetAmountAndFee(
IERC20, /* _sourceToken */
IERC20, /* _targetToken */
uint256 _sourceBalance,
uint256 _targetBalance,
uint256 _amount
) internal view virtual returns (uint256, uint256) {
uint256 amount = crossReserveTargetAmount(_sourceBalance, _targetBalance, _amount);
uint256 fee = calculateFee(amount);
return (amount - fee, fee);
}
/**
* @dev returns the required amount and expected fee for converting one reserve to another
*
* @param _sourceToken address of the source reserve token contract
* @param _targetToken address of the target reserve token contract
* @param _amount amount of target reserve tokens desired
*
* @return required amount in units of the source reserve token
* @return expected fee in units of the target reserve token
*/
function sourceAmountAndFee(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _amount
) public view virtual active returns (uint256, uint256) {
uint256 sourceId = __reserveIds[_sourceToken];
uint256 targetId = __reserveIds[_targetToken];
(uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
uint256 fee = calculateFeeInv(_amount);
uint256 amount = crossReserveSourceAmount(sourceBalance, targetBalance, _amount.add(fee));
return (amount, fee);
}
/**
* @dev converts a specific amount of source tokens to target tokens
*
* @param _sourceToken source ERC20 token
* @param _targetToken target ERC20 token
* @param _amount amount of tokens to convert (in units of the source token)
* @param _trader address of the caller who executed the conversion
* @param _beneficiary wallet to receive the conversion result
*
* @return amount of tokens received (in units of the target token)
*/
function doConvert(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _amount,
address _trader,
address payable _beneficiary
) internal returns (uint256) {
// update the recent average rate
updateRecentAverageRate();
uint256 sourceId = __reserveIds[_sourceToken];
uint256 targetId = __reserveIds[_targetToken];
(uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId);
// get the target amount minus the conversion fee and the conversion fee
(uint256 amount, uint256 fee) =
targetAmountAndFee(_sourceToken, _targetToken, sourceBalance, targetBalance, _amount);
// ensure that the trade gives something in return
require(amount != 0, "ERR_ZERO_TARGET_AMOUNT");
// ensure that the trade won't deplete the reserve balance
assert(amount < targetBalance);
// ensure that the input amount was already deposited
uint256 actualSourceBalance;
if (_sourceToken == NATIVE_TOKEN_ADDRESS) {
actualSourceBalance = address(this).balance;
require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH");
} else {
actualSourceBalance = _sourceToken.balanceOf(address(this));
require(msg.value == 0 && actualSourceBalance.sub(sourceBalance) >= _amount, "ERR_INVALID_AMOUNT");
}
// sync the reserve balances
setReserveBalances(sourceId, targetId, actualSourceBalance, targetBalance - amount);
// transfer funds to the beneficiary in the to reserve token
safeTransfer(_targetToken, _beneficiary, amount);
// dispatch the conversion event
dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee);
// dispatch rate updates
dispatchTokenRateUpdateEvents(_sourceToken, _targetToken, actualSourceBalance, targetBalance - amount);
return amount;
}
/**
* @dev returns the recent average rate of 1 `_token` in the other reserve token units
*
* @param _token token to get the rate for
*
* @return recent average rate between the reserves (numerator)
* @return recent average rate between the reserves (denominator)
*/
function recentAverageRate(IERC20 _token) external view validReserve(_token) returns (uint256, uint256) {
// get the recent average rate of reserve 0
uint256 rate = calcRecentAverageRate(averageRateInfo);
uint256 rateN = decodeAverageRateN(rate);
uint256 rateD = decodeAverageRateD(rate);
if (_token == __reserveTokens[0]) {
return (rateN, rateD);
}
return (rateD, rateN);
}
/**
* @dev updates the recent average rate if needed
*/
function updateRecentAverageRate() internal {
uint256 averageRateInfo1 = averageRateInfo;
uint256 averageRateInfo2 = calcRecentAverageRate(averageRateInfo1);
if (averageRateInfo1 != averageRateInfo2) {
averageRateInfo = averageRateInfo2;
}
}
/**
* @dev returns the recent average rate of 1 reserve token 0 in reserve token 1 units
*
* @param _averageRateInfo a local copy of the `averageRateInfo` state-variable
*
* @return recent average rate between the reserves
*/
function calcRecentAverageRate(uint256 _averageRateInfo) internal view returns (uint256) {
// get the previous average rate and its update-time
uint256 prevAverageRateT = decodeAverageRateT(_averageRateInfo);
uint256 prevAverageRateN = decodeAverageRateN(_averageRateInfo);
uint256 prevAverageRateD = decodeAverageRateD(_averageRateInfo);
// get the elapsed time since the previous average rate was calculated
uint256 currentTime = time();
uint256 timeElapsed = currentTime - prevAverageRateT;
// if the previous average rate was calculated in the current block, the average rate remains unchanged
if (timeElapsed == 0) {
return _averageRateInfo;
}
// get the current rate between the reserves
(uint256 currentRateD, uint256 currentRateN) = reserveBalances();
// if the previous average rate was calculated a while ago or never, the average rate is equal to the current rate
if (timeElapsed >= AVERAGE_RATE_PERIOD || prevAverageRateT == 0) {
(currentRateN, currentRateD) = MathEx.reducedRatio(currentRateN, currentRateD, MAX_UINT112);
return encodeAverageRateInfo(currentTime, currentRateN, currentRateD);
}
uint256 x = prevAverageRateD.mul(currentRateN);
uint256 y = prevAverageRateN.mul(currentRateD);
// since we know that timeElapsed < AVERAGE_RATE_PERIOD, we can avoid using SafeMath:
uint256 newRateN = y.mul(AVERAGE_RATE_PERIOD - timeElapsed).add(x.mul(timeElapsed));
uint256 newRateD = prevAverageRateD.mul(currentRateD).mul(AVERAGE_RATE_PERIOD);
(newRateN, newRateD) = MathEx.reducedRatio(newRateN, newRateD, MAX_UINT112);
return encodeAverageRateInfo(currentTime, newRateN, newRateD);
}
/**
* @dev increases the pool's liquidity and mints new shares in the pool to the caller
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
* @param _minReturn token minimum return-amount
*
* @return amount of pool tokens issued
*/
function addLiquidity(
IERC20[] memory _reserveTokens,
uint256[] memory _reserveAmounts,
uint256 _minReturn
) public payable protected active returns (uint256) {
// verify the user input
verifyLiquidityInput(_reserveTokens, _reserveAmounts, _minReturn);
// if one of the reserves is ETH, then verify that the input amount of ETH is equal to the input value of ETH
for (uint256 i = 0; i < 2; i++) {
if (_reserveTokens[i] == NATIVE_TOKEN_ADDRESS) {
require(_reserveAmounts[i] == msg.value, "ERR_ETH_AMOUNT_MISMATCH");
}
}
// if the input value of ETH is larger than zero, then verify that one of the reserves is ETH
if (msg.value > 0) {
require(__reserveIds[NATIVE_TOKEN_ADDRESS] != 0, "ERR_NO_ETH_RESERVE");
}
// save a local copy of the pool token
IDSToken poolToken = IDSToken(address(anchor));
// get the total supply
uint256 totalSupply = poolToken.totalSupply();
uint256[2] memory prevReserveBalances;
uint256[2] memory newReserveBalances;
// process the network fees and get the reserve balances
(prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(msg.value);
uint256 amount;
uint256[2] memory reserveAmounts;
// calculate the amount of pool tokens to mint for the caller
// and the amount of reserve tokens to transfer from the caller
if (totalSupply == 0) {
amount = MathEx.geometricMean(_reserveAmounts);
reserveAmounts[0] = _reserveAmounts[0];
reserveAmounts[1] = _reserveAmounts[1];
} else {
(amount, reserveAmounts) = addLiquidityAmounts(
_reserveTokens,
_reserveAmounts,
prevReserveBalances,
totalSupply
);
}
uint256 newPoolTokenSupply = totalSupply.add(amount);
for (uint256 i = 0; i < 2; i++) {
IERC20 reserveToken = _reserveTokens[i];
uint256 reserveAmount = reserveAmounts[i];
require(reserveAmount > 0, "ERR_ZERO_TARGET_AMOUNT");
assert(reserveAmount <= _reserveAmounts[i]);
// transfer each one of the reserve amounts from the user to the pool
if (reserveToken != NATIVE_TOKEN_ADDRESS) {
// ETH has already been transferred as part of the transaction
reserveToken.safeTransferFrom(msg.sender, address(this), reserveAmount);
} else if (_reserveAmounts[i] > reserveAmount) {
// transfer the extra amount of ETH back to the user
msg.sender.transfer(_reserveAmounts[i] - reserveAmount);
}
// save the new reserve balance
newReserveBalances[i] = prevReserveBalances[i].add(reserveAmount);
emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
emit TokenRateUpdate(poolToken, reserveToken, newReserveBalances[i], newPoolTokenSupply);
}
// set the reserve balances
setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]);
// set the reserve balances product
_reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1];
// verify that the equivalent amount of tokens is equal to or larger than the user's expectation
require(amount >= _minReturn, "ERR_RETURN_TOO_LOW");
// issue the tokens to the user
poolToken.issue(msg.sender, amount);
// return the amount of pool tokens issued
return amount;
}
/**
* @dev get the amount of pool tokens to mint for the caller
* and the amount of reserve tokens to transfer from the caller
*
* @param _reserveAmounts amount of each reserve token
* @param _reserveBalances balance of each reserve token
* @param _totalSupply total supply of pool tokens
*
* @return amount of pool tokens to mint for the caller
* @return amount of reserve tokens to transfer from the caller
*/
function addLiquidityAmounts(
IERC20[] memory, /* _reserveTokens */
uint256[] memory _reserveAmounts,
uint256[2] memory _reserveBalances,
uint256 _totalSupply
) internal view virtual returns (uint256, uint256[2] memory) {
this;
uint256 index =
_reserveAmounts[0].mul(_reserveBalances[1]) < _reserveAmounts[1].mul(_reserveBalances[0]) ? 0 : 1;
uint256 amount = fundSupplyAmount(_totalSupply, _reserveBalances[index], _reserveAmounts[index]);
uint256[2] memory reserveAmounts =
[fundCost(_totalSupply, _reserveBalances[0], amount), fundCost(_totalSupply, _reserveBalances[1], amount)];
return (amount, reserveAmounts);
}
/**
* @dev decreases the pool's liquidity and burns the caller's shares in the pool
*
* @param _amount token amount
* @param _reserveTokens address of each reserve token
* @param _reserveMinReturnAmounts minimum return-amount of each reserve token
*
* @return the amount of each reserve token granted for the given amount of pool tokens
*/
function removeLiquidity(
uint256 _amount,
IERC20[] memory _reserveTokens,
uint256[] memory _reserveMinReturnAmounts
) public protected active returns (uint256[] memory) {
// verify the user input
bool inputRearranged = verifyLiquidityInput(_reserveTokens, _reserveMinReturnAmounts, _amount);
// save a local copy of the pool token
IDSToken poolToken = IDSToken(address(anchor));
// get the total supply BEFORE destroying the user tokens
uint256 totalSupply = poolToken.totalSupply();
// destroy the user tokens
poolToken.destroy(msg.sender, _amount);
uint256 newPoolTokenSupply = totalSupply.sub(_amount);
uint256[2] memory prevReserveBalances;
uint256[2] memory newReserveBalances;
// process the network fees and get the reserve balances
(prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(0);
uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(_amount, totalSupply, prevReserveBalances);
for (uint256 i = 0; i < 2; i++) {
IERC20 reserveToken = _reserveTokens[i];
uint256 reserveAmount = reserveAmounts[i];
require(reserveAmount >= _reserveMinReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT");
// save the new reserve balance
newReserveBalances[i] = prevReserveBalances[i].sub(reserveAmount);
// transfer each one of the reserve amounts from the pool to the user
safeTransfer(reserveToken, msg.sender, reserveAmount);
emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply);
// dispatch the `TokenRateUpdate` event for the pool token
emit TokenRateUpdate(poolToken, reserveToken, newReserveBalances[i], newPoolTokenSupply);
}
// set the reserve balances
setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]);
// set the reserve balances product
_reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1];
if (inputRearranged) {
uint256 tempReserveAmount = reserveAmounts[0];
reserveAmounts[0] = reserveAmounts[1];
reserveAmounts[1] = tempReserveAmount;
}
// return the amount of each reserve token granted for the given amount of pool tokens
return reserveAmounts;
}
/**
* @dev given the amount of one of the reserve tokens to add liquidity of,
* returns the required amount of each one of the other reserve tokens
* since an empty pool can be funded with any list of non-zero input amounts,
* this function assumes that the pool is not empty (has already been funded)
*
* @param _reserveTokens address of each reserve token
* @param _reserveTokenIndex index of the relevant reserve token
* @param _reserveAmount amount of the relevant reserve token
*
* @return the required amount of each one of the reserve tokens
*/
function addLiquidityCost(
IERC20[] memory _reserveTokens,
uint256 _reserveTokenIndex,
uint256 _reserveAmount
) public view returns (uint256[] memory) {
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
uint256 amount = fundSupplyAmount(totalSupply, baseBalances[_reserveTokenIndex], _reserveAmount);
uint256[] memory reserveAmounts = new uint256[](2);
reserveAmounts[0] = fundCost(totalSupply, baseBalances[0], amount);
reserveAmounts[1] = fundCost(totalSupply, baseBalances[1], amount);
return reserveAmounts;
}
/**
* @dev returns the amount of pool tokens entitled for given amounts of reserve tokens
* since an empty pool can be funded with any list of non-zero input amounts,
* this function assumes that the pool is not empty (has already been funded)
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
*
* @return the amount of pool tokens entitled for the given amounts of reserve tokens
*/
function addLiquidityReturn(IERC20[] memory _reserveTokens, uint256[] memory _reserveAmounts)
public
view
returns (uint256)
{
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
(uint256 amount, ) = addLiquidityAmounts(_reserveTokens, _reserveAmounts, baseBalances, totalSupply);
return amount;
}
/**
* @dev returns the amount of each reserve token entitled for a given amount of pool tokens
*
* @param _amount amount of pool tokens
* @param _reserveTokens address of each reserve token
*
* @return the amount of each reserve token entitled for the given amount of pool tokens
*/
function removeLiquidityReturn(uint256 _amount, IERC20[] memory _reserveTokens)
public
view
returns (uint256[] memory)
{
uint256 totalSupply = IDSToken(address(anchor)).totalSupply();
uint256[2] memory baseBalances = baseReserveBalances(_reserveTokens);
return removeLiquidityReserveAmounts(_amount, totalSupply, baseBalances);
}
/**
* @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens
* we take this input in order to allow specifying the corresponding reserve amounts in any order
* this function rearranges the input arrays according to the converter's array of reserve tokens
*
* @param _reserveTokens array of reserve tokens
* @param _reserveAmounts array of reserve amounts
* @param _amount token amount
*
* @return true if the function has rearranged the input arrays; false otherwise
*/
function verifyLiquidityInput(
IERC20[] memory _reserveTokens,
uint256[] memory _reserveAmounts,
uint256 _amount
) private view returns (bool) {
require(validReserveAmounts(_reserveAmounts) && _amount > 0, "ERR_ZERO_AMOUNT");
uint256 reserve0Id = __reserveIds[_reserveTokens[0]];
uint256 reserve1Id = __reserveIds[_reserveTokens[1]];
if (reserve0Id == 2 && reserve1Id == 1) {
IERC20 tempReserveToken = _reserveTokens[0];
_reserveTokens[0] = _reserveTokens[1];
_reserveTokens[1] = tempReserveToken;
uint256 tempReserveAmount = _reserveAmounts[0];
_reserveAmounts[0] = _reserveAmounts[1];
_reserveAmounts[1] = tempReserveAmount;
return true;
}
require(reserve0Id == 1 && reserve1Id == 2, "ERR_INVALID_RESERVE");
return false;
}
/**
* @dev checks whether or not both reserve amounts are larger than zero
*
* @param _reserveAmounts array of reserve amounts
*
* @return true if both reserve amounts are larger than zero; false otherwise
*/
function validReserveAmounts(uint256[] memory _reserveAmounts) internal pure virtual returns (bool) {
return _reserveAmounts[0] > 0 && _reserveAmounts[1] > 0;
}
/**
* @dev returns the amount of each reserve token entitled for a given amount of pool tokens
*
* @param _amount amount of pool tokens
* @param _totalSupply total supply of pool tokens
* @param _reserveBalances balance of each reserve token
*
* @return the amount of each reserve token entitled for the given amount of pool tokens
*/
function removeLiquidityReserveAmounts(
uint256 _amount,
uint256 _totalSupply,
uint256[2] memory _reserveBalances
) private pure returns (uint256[] memory) {
uint256[] memory reserveAmounts = new uint256[](2);
reserveAmounts[0] = liquidateReserveAmount(_totalSupply, _reserveBalances[0], _amount);
reserveAmounts[1] = liquidateReserveAmount(_totalSupply, _reserveBalances[1], _amount);
return reserveAmounts;
}
/**
* @dev dispatches token rate update events for the reserve tokens and the pool token
*
* @param _sourceToken address of the source reserve token
* @param _targetToken address of the target reserve token
* @param _sourceBalance balance of the source reserve token
* @param _targetBalance balance of the target reserve token
*/
function dispatchTokenRateUpdateEvents(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _sourceBalance,
uint256 _targetBalance
) private {
// save a local copy of the pool token
IDSToken poolToken = IDSToken(address(anchor));
// get the total supply of pool tokens
uint256 poolTokenSupply = poolToken.totalSupply();
// dispatch token rate update event for the reserve tokens
emit TokenRateUpdate(_sourceToken, _targetToken, _targetBalance, _sourceBalance);
// dispatch token rate update events for the pool token
emit TokenRateUpdate(poolToken, _sourceToken, _sourceBalance, poolTokenSupply);
emit TokenRateUpdate(poolToken, _targetToken, _targetBalance, poolTokenSupply);
}
function encodeReserveBalance(uint256 _balance, uint256 _id) private pure returns (uint256) {
assert(_balance <= MAX_UINT128 && (_id == 1 || _id == 2));
return _balance << ((_id - 1) * 128);
}
function decodeReserveBalance(uint256 _balances, uint256 _id) private pure returns (uint256) {
assert(_id == 1 || _id == 2);
return (_balances >> ((_id - 1) * 128)) & MAX_UINT128;
}
function encodeReserveBalances(
uint256 _balance0,
uint256 _id0,
uint256 _balance1,
uint256 _id1
) private pure returns (uint256) {
return encodeReserveBalance(_balance0, _id0) | encodeReserveBalance(_balance1, _id1);
}
function decodeReserveBalances(
uint256 _balances,
uint256 _id0,
uint256 _id1
) private pure returns (uint256, uint256) {
return (decodeReserveBalance(_balances, _id0), decodeReserveBalance(_balances, _id1));
}
function encodeAverageRateInfo(
uint256 _averageRateT,
uint256 _averageRateN,
uint256 _averageRateD
) private pure returns (uint256) {
assert(_averageRateT <= MAX_UINT32 && _averageRateN <= MAX_UINT112 && _averageRateD <= MAX_UINT112);
return (_averageRateT << 224) | (_averageRateN << 112) | _averageRateD;
}
function decodeAverageRateT(uint256 _averageRateInfo) private pure returns (uint256) {
return _averageRateInfo >> 224;
}
function decodeAverageRateN(uint256 _averageRateInfo) private pure returns (uint256) {
return (_averageRateInfo >> 112) & MAX_UINT112;
}
function decodeAverageRateD(uint256 _averageRateInfo) private pure returns (uint256) {
return _averageRateInfo & MAX_UINT112;
}
/**
* @dev returns the largest integer smaller than or equal to the square root of a given value
*
* @param x the given value
*
* @return the largest integer smaller than or equal to the square root of the given value
*/
function floorSqrt(uint256 x) private pure returns (uint256) {
return x > 0 ? MathEx.floorSqrt(x) : 0;
}
function crossReserveTargetAmount(
uint256 _sourceReserveBalance,
uint256 _targetReserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_sourceReserveBalance > 0 && _targetReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
return _targetReserveBalance.mul(_amount) / _sourceReserveBalance.add(_amount);
}
function crossReserveSourceAmount(
uint256 _sourceReserveBalance,
uint256 _targetReserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_sourceReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_amount < _targetReserveBalance, "ERR_INVALID_AMOUNT");
if (_amount == 0) {
return 0;
}
return (_sourceReserveBalance.mul(_amount) - 1) / (_targetReserveBalance - _amount) + 1;
}
function fundCost(
uint256 _supply,
uint256 _reserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
// special case for 0 amount
if (_amount == 0) {
return 0;
}
return (_amount.mul(_reserveBalance) - 1) / _supply + 1;
}
function fundSupplyAmount(
uint256 _supply,
uint256 _reserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
// special case for 0 amount
if (_amount == 0) {
return 0;
}
return _amount.mul(_supply) / _reserveBalance;
}
function liquidateReserveAmount(
uint256 _supply,
uint256 _reserveBalance,
uint256 _amount
) private pure returns (uint256) {
// validate input
require(_supply > 0, "ERR_INVALID_SUPPLY");
require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE");
require(_amount <= _supply, "ERR_INVALID_AMOUNT");
// special case for 0 amount
if (_amount == 0) {
return 0;
}
// special case for liquidating the entire supply
if (_amount == _supply) {
return _reserveBalance;
}
return _amount.mul(_reserveBalance) / _supply;
}
/**
* @dev returns the network wallet and fees
*
* @param reserveBalance0 1st reserve balance
* @param reserveBalance1 2nd reserve balance
*
* @return the network wallet
* @return the network fee on the 1st reserve
* @return the network fee on the 2nd reserve
*/
function networkWalletAndFees(uint256 reserveBalance0, uint256 reserveBalance1)
private
view
returns (
ITokenHolder,
uint256,
uint256
)
{
uint256 prevPoint = floorSqrt(_reserveBalancesProduct);
uint256 currPoint = floorSqrt(reserveBalance0 * reserveBalance1);
if (prevPoint >= currPoint) {
return (ITokenHolder(address(0)), 0, 0);
}
(ITokenHolder networkFeeWallet, uint32 networkFee) =
INetworkSettings(addressOf(NETWORK_SETTINGS)).networkFeeParams();
uint256 n = (currPoint - prevPoint) * networkFee;
uint256 d = currPoint * PPM_RESOLUTION;
return (networkFeeWallet, reserveBalance0.mul(n).div(d), reserveBalance1.mul(n).div(d));
}
/**
* @dev transfers funds held by the contract and sends them to an account
*
* @param token ERC20 token contract address
* @param to account to receive the new amount
* @param amount amount to withdraw
*/
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) private {
if (amount == 0) {
return;
}
if (token == NATIVE_TOKEN_ADDRESS) {
payable(to).transfer(amount);
} else {
token.safeTransfer(to, amount);
}
}
/**
* @dev deprecated since version 28, backward compatibility - use only for earlier versions
*/
function token() public view override returns (IConverterAnchor) {
return anchor;
}
/**
* @dev deprecated, backward compatibility
*/
function transferTokenOwnership(address _newOwner) public override ownerOnly {
transferAnchorOwnership(_newOwner);
}
/**
* @dev deprecated, backward compatibility
*/
function acceptTokenOwnership() public override ownerOnly {
acceptAnchorOwnership();
}
/**
* @dev deprecated, backward compatibility
*/
function connectors(IERC20 _address)
public
view
override
returns (
uint256,
uint32,
bool,
bool,
bool
)
{
uint256 reserveId = __reserveIds[_address];
if (reserveId != 0) {
return (reserveBalance(reserveId), PPM_RESOLUTION / 2, false, false, true);
}
return (0, 0, false, false, false);
}
/**
* @dev deprecated, backward compatibility
*/
function connectorTokens(uint256 _index) public view override returns (IERC20) {
return __reserveTokens[_index];
}
/**
* @dev deprecated, backward compatibility
*/
function connectorTokenCount() public view override returns (uint16) {
return reserveTokenCount();
}
/**
* @dev deprecated, backward compatibility
*/
function getConnectorBalance(IERC20 _connectorToken) public view override returns (uint256) {
return reserveBalance(_connectorToken);
}
/**
* @dev deprecated, backward compatibility
*/
function getReturn(
IERC20 _sourceToken,
IERC20 _targetToken,
uint256 _amount
) public view returns (uint256, uint256) {
return targetAmountAndFee(_sourceToken, _targetToken, _amount);
}
}
// File: solidity/contracts/converter/interfaces/ITypedConverterFactory.sol
pragma solidity 0.6.12;
/*
Typed Converter Factory interface
*/
interface ITypedConverterFactory {
function converterType() external pure returns (uint16);
function createConverter(
IConverterAnchor _anchor,
IContractRegistry _registry,
uint32 _maxConversionFee
) external returns (IConverter);
}
// File: solidity/contracts/converter/types/standard-pool/StandardPoolConverterFactory.sol
pragma solidity 0.6.12;
/*
StandardPoolConverter Factory
*/
contract StandardPoolConverterFactory is ITypedConverterFactory {
/**
* @dev returns the converter type the factory is associated with
*
* @return converter type
*/
function converterType() external pure override returns (uint16) {
return 3;
}
/**
* @dev creates a new converter with the given arguments and transfers
* the ownership to the caller
*
* @param _anchor anchor governed by the converter
* @param _registry address of a contract registry contract
* @param _maxConversionFee maximum conversion fee, represented in ppm
*
* @return a new converter
*/
function createConverter(
IConverterAnchor _anchor,
IContractRegistry _registry,
uint32 _maxConversionFee
) external virtual override returns (IConverter) {
IConverter converter = new StandardPoolConverter(IDSToken(address(_anchor)), _registry, _maxConversionFee);
converter.transferOwnership(msg.sender);
return converter;
}
}
|
returns the recent average rate of 1 `_token` in the other reserve token units _token token to get the rate for return recent average rate between the reserves (numerator) return recent average rate between the reserves (denominator)/ get the recent average rate of reserve 0
|
function recentAverageRate(IERC20 _token) external view validReserve(_token) returns (uint256, uint256) {
uint256 rate = calcRecentAverageRate(averageRateInfo);
uint256 rateN = decodeAverageRateN(rate);
uint256 rateD = decodeAverageRateD(rate);
if (_token == __reserveTokens[0]) {
return (rateN, rateD);
}
return (rateD, rateN);
}
| 1,736,018
|
./full_match/4/0x0Cd4aB3C76E1F452d951118c8a3861Ca533cef09/sources/Cryptogotchi.sol
|
revive device excluding prestige and color
|
function revival(uint256 tokenId) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "!o");
require(!alive(tokenId), "x!");
Device storage device = unit[tokenId];
require(TokenInterface(tokenAddress).allowance(msg.sender, address(this)) >= device.tokensToRevive, "!a");
require(TokenInterface(tokenAddress).balanceOf(msg.sender) >= device.tokensToRevive, "!b");
require(device.color > 0, '!c');
require(device.createdAt != MAX_TIMESTAMP, "ie");
require(device.rewards == 0, "r0");
if (device.tokensToRevive != 0) {
TokenInterface(tokenAddress).burn(msg.sender, device.tokensToRevive);
}
device.createdAt = MAX_TIMESTAMP;
device.lastPlayTime = MAX_TIMESTAMP;
device.name = egg;
device.feedLevel = 0;
device.generation = 0;
device.generationTicker = 0;
device.tokensToRevive = 0;
device.revivals = device.revivals.add(1);
emit Revive(tokenId);
}
| 816,983
|
pragma solidity ^0.5.5;
pragma experimental ABIEncoderV2;
contract SafeMath {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(
c / a == b,
"UINT256_OVERFLOW"
);
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(
b <= a,
"UINT256_UNDERFLOW"
);
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
require(
c >= a,
"UINT256_OVERFLOW"
);
return c;
}
function max64(uint64 a, uint64 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
contract LibMath is
SafeMath
{
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function safeGetPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
require(
!isRoundingErrorFloor(
numerator,
denominator,
target
),
"ROUNDING_ERROR"
);
partialAmount = safeDiv(
safeMul(numerator, target),
denominator
);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function safeGetPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
require(
!isRoundingErrorCeil(
numerator,
denominator,
target
),
"ROUNDING_ERROR"
);
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = safeDiv(
safeAdd(
safeMul(numerator, target),
safeSub(denominator, 1)
),
denominator
);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function getPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
partialAmount = safeDiv(
safeMul(numerator, target),
denominator
);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function getPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = safeDiv(
safeAdd(
safeMul(numerator, target),
safeSub(denominator, 1)
),
denominator
);
return partialAmount;
}
/// @dev Checks if rounding error >= 0.1% when rounding down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
// The absolute rounding error is the difference between the rounded
// value and the ideal value. The relative rounding error is the
// absolute rounding error divided by the absolute value of the
// ideal value. This is undefined when the ideal value is zero.
//
// The ideal value is `numerator * target / denominator`.
// Let's call `numerator * target % denominator` the remainder.
// The absolute error is `remainder / denominator`.
//
// When the ideal value is zero, we require the absolute error to
// be zero. Fortunately, this is always the case. The ideal value is
// zero iff `numerator == 0` and/or `target == 0`. In this case the
// remainder and absolute error are also zero.
if (target == 0 || numerator == 0) {
return false;
}
// Otherwise, we want the relative rounding error to be strictly
// less than 0.1%.
// The relative error is `remainder / (numerator * target)`.
// We want the relative error less than 1 / 1000:
// remainder / (numerator * denominator) < 1 / 1000
// or equivalently:
// 1000 * remainder < numerator * target
// so we have a rounding error iff:
// 1000 * remainder >= numerator * target
uint256 remainder = mulmod(
target,
numerator,
denominator
);
isError = safeMul(1000, remainder) >= safeMul(numerator, target);
return isError;
}
/// @dev Checks if rounding error >= 0.1% when rounding up.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
// See the comments in `isRoundingError`.
if (target == 0 || numerator == 0) {
// When either is zero, the ideal value and rounded value are zero
// and there is no rounding error. (Although the relative error
// is undefined.)
return false;
}
// Compute remainder as before
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = safeSub(denominator, remainder) % denominator;
isError = safeMul(1000, remainder) >= safeMul(numerator, target);
return isError;
}
}
contract IExchangeCore {
/// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch
/// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress).
/// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled.
function cancelOrdersUpTo(uint256 targetOrderEpoch)
external;
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
returns (LibFillResults.FillResults memory fillResults);
/// @dev After calling, the order can not be filled anymore.
/// @param order Order struct containing order specifications.
function cancelOrder(LibOrder.Order memory order)
public;
/// @dev Gets information about an order: status, hash, and amount filled.
/// @param order Order to gather information on.
/// @return OrderInfo Information about the order and its state.
/// See LibOrder.OrderInfo for a complete description.
function getOrderInfo(LibOrder.Order memory order)
public
view
returns (LibOrder.OrderInfo memory orderInfo);
}
contract IMatchOrders {
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the left order goes to the taker (who matched the two orders).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders.
function matchOrders(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
returns (LibFillResults.MatchedFillResults memory matchedFillResults);
}
contract ISignatureValidator {
/// @dev Approves a hash on-chain using any valid signature type.
/// After presigning a hash, the preSign signature type will become valid for that hash and signer.
/// @param signerAddress Address that should have signed the given hash.
/// @param signature Proof that the hash has been signed by signer.
function preSign(
bytes32 hash,
address signerAddress,
bytes calldata signature
)
external;
/// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf.
/// @param validatorAddress Address of Validator contract.
/// @param approval Approval or disapproval of Validator contract.
function setSignatureValidatorApproval(
address validatorAddress,
bool approval
)
external;
/// @dev Verifies that a signature is valid.
/// @param hash Message hash that is signed.
/// @param signerAddress Address of signer.
/// @param signature Proof of signing.
/// @return Validity of order signature.
function isValidSignature(
bytes32 hash,
address signerAddress,
bytes memory signature
)
public
view
returns (bool isValid);
}
contract ITransactions {
/// @dev Executes an exchange method call in the context of signer.
/// @param salt Arbitrary number to ensure uniqueness of transaction hash.
/// @param signerAddress Address of transaction signer.
/// @param data AbiV2 encoded calldata.
/// @param signature Proof of signer transaction by signer.
function executeTransaction(
uint256 salt,
address signerAddress,
bytes calldata data,
bytes calldata signature
)
external;
}
contract IAssetProxyDispatcher {
/// @dev Registers an asset proxy to its asset proxy id.
/// Once an asset proxy is registered, it cannot be unregistered.
/// @param assetProxy Address of new asset proxy to register.
function registerAssetProxy(address assetProxy)
external;
/// @dev Gets an asset proxy.
/// @param assetProxyId Id of the asset proxy.
/// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered.
function getAssetProxy(bytes4 assetProxyId)
external
view
returns (address);
}
contract LibFillResults is
SafeMath
{
struct FillResults {
uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled.
uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled.
uint256 makerFeePaid; // Total amount of ZRX paid by maker(s) to feeRecipient(s).
uint256 takerFeePaid; // Total amount of ZRX paid by taker to feeRecipients(s).
}
struct MatchedFillResults {
FillResults left; // Amounts filled and fees paid of left order.
FillResults right; // Amounts filled and fees paid of right order.
uint256 leftMakerAssetSpreadAmount; // Spread between price of left and right order, denominated in the left order's makerAsset, paid to taker.
}
/// @dev Adds properties of both FillResults instances.
/// Modifies the first FillResults instance specified.
/// @param totalFillResults Fill results instance that will be added onto.
/// @param singleFillResults Fill results instance that will be added to totalFillResults.
function addFillResults(FillResults memory totalFillResults, FillResults memory singleFillResults)
internal
pure
{
totalFillResults.makerAssetFilledAmount = safeAdd(totalFillResults.makerAssetFilledAmount, singleFillResults.makerAssetFilledAmount);
totalFillResults.takerAssetFilledAmount = safeAdd(totalFillResults.takerAssetFilledAmount, singleFillResults.takerAssetFilledAmount);
totalFillResults.makerFeePaid = safeAdd(totalFillResults.makerFeePaid, singleFillResults.makerFeePaid);
totalFillResults.takerFeePaid = safeAdd(totalFillResults.takerFeePaid, singleFillResults.takerFeePaid);
}
}
contract IWrapperFunctions {
/// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled.
/// @param order LibOrder.Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
function fillOrKillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
returns (LibFillResults.FillResults memory fillResults);
/// @dev Fills an order with specified parameters and ECDSA signature.
/// Returns false if the transaction would otherwise revert.
/// @param order LibOrder.Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrderNoThrow(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
returns (LibFillResults.FillResults memory fillResults);
/// @dev Synchronously executes multiple calls of fillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Amounts filled and fees paid by makers and taker.
function batchFillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Synchronously executes multiple calls of fillOrKill.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Amounts filled and fees paid by makers and taker.
function batchFillOrKillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Fills an order with specified parameters and ECDSA signature.
/// Returns false if the transaction would otherwise revert.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Amounts filled and fees paid by makers and taker.
function batchFillOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Synchronously executes multiple calls of fillOrder until total amount of takerAsset is sold by taker.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signatures Proofs that orders have been created by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrders(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Synchronously executes multiple calls of fillOrder until total amount of takerAsset is sold by taker.
/// Returns false if the transaction would otherwise revert.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Synchronously executes multiple calls of fillOrder until total amount of makerAsset is bought by taker.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Desired amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrders(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Synchronously executes multiple fill orders in a single transaction until total amount is bought by taker.
/// Returns false if the transaction would otherwise revert.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Desired amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
returns (LibFillResults.FillResults memory totalFillResults);
/// @dev Synchronously cancels multiple orders in a single transaction.
/// @param orders Array of order specifications.
function batchCancelOrders(LibOrder.Order[] memory orders)
public;
/// @dev Fetches information for all passed in orders
/// @param orders Array of order specifications.
/// @return Array of OrderInfo instances that correspond to each order.
function getOrdersInfo(LibOrder.Order[] memory orders)
public
view
returns (LibOrder.OrderInfo[] memory);
}
// solhint-disable no-empty-blocks
contract IExchange is
IExchangeCore,
IMatchOrders,
ISignatureValidator,
ITransactions,
IAssetProxyDispatcher,
IWrapperFunctions
{}
contract LibAssetProxyIds {
// AssetProxy Ids are equiavalent the first 4 bytes of the keccak256 hash of the function signature assigned to each AssetProxy.
// ERC20Token(address)
bytes4 constant public ERC20_PROXY_ID = 0xf47261b0;
// ERC721Token(address,uint256)
bytes4 constant public ERC721_PROXY_ID = 0x02571792;
// ERC1155Assets(address,uint256[],uint256[],bytes)
bytes4 constant public ERC1155_PROXY_ID = 0xa7cb5fb7;
// MultiAsset(uint256[],bytes[])
bytes4 constant public MULTI_ASSET_PROXY_ID = 0x94cfcdd7;
// StaticCall(address,bytes,bytes32)
bytes4 constant public STATIC_CALL_PROXY_ID = 0xc339d10a;
}
contract LibAssetData is
LibAssetProxyIds
{
// 2^256 - 1
uint256 constant internal _MAX_UINT256 = uint256(-1);
// ERC20 selectors
bytes4 constant internal _ERC20_BALANCE_OF_SELECTOR = 0x70a08231;
bytes4 constant internal _ERC20_ALLOWANCE_SELECTOR = 0xdd62ed3e;
// ERC721 selectors
bytes4 constant internal _ERC721_OWNER_OF_SELECTOR = 0x6352211e;
bytes4 constant internal _ERC721_IS_APPROVED_FOR_ALL_SELECTOR = 0xe985e9c5;
bytes4 constant internal _ERC721_GET_APPROVED_SELECTOR = 0x081812fc;
// ERC1155 selectors
bytes4 constant internal _ERC1155_BALANCE_OF_SELECTOR = 0x00fdd58e;
bytes4 constant internal _ERC1155_IS_APPROVED_FOR_ALL_SELECTOR = 0xe985e9c5;
// `transferFrom` selector for all AssetProxy contracts
bytes4 constant internal _ASSET_PROXY_TRANSFER_FROM_SELECTOR = 0xa85e59e4;
using LibBytes for bytes;
// solhint-disable var-name-mixedcase
IExchange internal _EXCHANGE;
address internal _ERC20_PROXY_ADDRESS;
address internal _ERC721_PROXY_ADDRESS;
address internal _ERC1155_PROXY_ADDRESS;
address internal _STATIC_CALL_PROXY_ADDRESS;
// solhint-enable var-name-mixedcase
constructor (address _exchange)
public
{
_EXCHANGE = IExchange(_exchange);
_ERC20_PROXY_ADDRESS = _EXCHANGE.getAssetProxy(ERC20_PROXY_ID);
_ERC721_PROXY_ADDRESS = _EXCHANGE.getAssetProxy(ERC721_PROXY_ID);
_ERC1155_PROXY_ADDRESS = _EXCHANGE.getAssetProxy(ERC1155_PROXY_ID);
_STATIC_CALL_PROXY_ADDRESS = _EXCHANGE.getAssetProxy(STATIC_CALL_PROXY_ID);
}
/// @dev Returns the owner's balance of the assets(s) specified in
/// assetData. When the asset data contains multiple assets (eg in
/// ERC1155 or Multi-Asset), the return value indicates how many
/// complete "baskets" of those assets are owned by owner.
/// @param ownerAddress Owner of the assets specified by assetData.
/// @param assetData Details of asset, encoded per the AssetProxy contract specification.
/// @return Number of assets (or asset baskets) held by owner.
function getBalance(address ownerAddress, bytes memory assetData)
public
view
returns (uint256 balance)
{
// Get id of AssetProxy contract
bytes4 assetProxyId = assetData.readBytes4(0);
if (assetProxyId == ERC20_PROXY_ID) {
// Get ERC20 token address
address tokenAddress = assetData.readAddress(16);
// Encode data for `balanceOf(ownerAddress)`
bytes memory balanceOfData = abi.encodeWithSelector(_ERC20_BALANCE_OF_SELECTOR, ownerAddress);
// Query balance
(bool success, bytes memory returnData) = tokenAddress.staticcall(balanceOfData);
balance = success && returnData.length == 32 ? returnData.readUint256(0) : 0;
} else if (assetProxyId == ERC721_PROXY_ID) {
// Get ERC721 token address and id
(, address tokenAddress, uint256 tokenId) = decodeERC721AssetData(assetData);
// Check if id is owned by ownerAddress
balance = getERC721TokenOwner(tokenAddress, tokenId) == ownerAddress ? 1 : 0;
} else if (assetProxyId == ERC1155_PROXY_ID) {
// Get ERC1155 token address, array of ids, and array of values
(, address tokenAddress, uint256[] memory tokenIds, uint256[] memory tokenValues,) = decodeERC1155AssetData(assetData);
uint256 length = tokenIds.length;
for (uint256 i = 0; i != length; i++) {
// Encode data for `balanceOf(ownerAddress, tokenIds[i])
bytes memory balanceOfData = abi.encodeWithSelector(
_ERC1155_BALANCE_OF_SELECTOR,
ownerAddress,
tokenIds[i]
);
// Query balance
(bool success, bytes memory returnData) = tokenAddress.staticcall(balanceOfData);
uint256 totalBalance = success && returnData.length == 32 ? returnData.readUint256(0) : 0;
// Scale total balance down by corresponding value in assetData
uint256 scaledBalance = totalBalance / tokenValues[i];
if (scaledBalance < balance || balance == 0) {
balance = scaledBalance;
}
}
} else if (assetProxyId == STATIC_CALL_PROXY_ID) {
// Encode data for `staticCallProxy.transferFrom(assetData,...)`
bytes memory transferFromData = abi.encodeWithSelector(
_ASSET_PROXY_TRANSFER_FROM_SELECTOR,
assetData,
address(0), // `from` address is not used
address(0), // `to` address is not used
0 // `amount` is not used
);
// Check if staticcall would be successful
(bool success,) = _STATIC_CALL_PROXY_ADDRESS.staticcall(transferFromData);
// Success means that the staticcall can be made an unlimited amount of times
balance = success ? _MAX_UINT256 : 0;
} else if (assetProxyId == MULTI_ASSET_PROXY_ID) {
// Get array of values and array of assetDatas
(, uint256[] memory assetAmounts, bytes[] memory nestedAssetData) = decodeMultiAssetData(assetData);
uint256 length = nestedAssetData.length;
for (uint256 i = 0; i != length; i++) {
// Query balance of individual assetData
uint256 totalBalance = getBalance(ownerAddress, nestedAssetData[i]);
// Scale total balance down by corresponding value in assetData
uint256 scaledBalance = totalBalance / assetAmounts[i];
if (scaledBalance < balance || balance == 0) {
balance = scaledBalance;
}
}
}
// Balance will be 0 if assetProxyId is unknown
return balance;
}
/// @dev Calls getBalance() for each element of assetData.
/// @param ownerAddress Owner of the assets specified by assetData.
/// @param assetData Array of asset details, each encoded per the AssetProxy contract specification.
/// @return Array of asset balances from getBalance(), with each element
/// corresponding to the same-indexed element in the assetData input.
function getBatchBalances(address ownerAddress, bytes[] memory assetData)
public
view
returns (uint256[] memory balances)
{
uint256 length = assetData.length;
balances = new uint256[](length);
for (uint256 i = 0; i != length; i++) {
balances[i] = getBalance(ownerAddress, assetData[i]);
}
return balances;
}
/// @dev Returns the number of asset(s) (described by assetData) that
/// the corresponding AssetProxy contract is authorized to spend. When the asset data contains
/// multiple assets (eg for Multi-Asset), the return value indicates
/// how many complete "baskets" of those assets may be spent by all of the corresponding
/// AssetProxy contracts.
/// @param ownerAddress Owner of the assets specified by assetData.
/// @param assetData Details of asset, encoded per the AssetProxy contract specification.
/// @return Number of assets (or asset baskets) that the corresponding AssetProxy is authorized to spend.
function getAssetProxyAllowance(address ownerAddress, bytes memory assetData)
public
view
returns (uint256 allowance)
{
// Get id of AssetProxy contract
bytes4 assetProxyId = assetData.readBytes4(0);
if (assetProxyId == MULTI_ASSET_PROXY_ID) {
// Get array of values and array of assetDatas
(, uint256[] memory amounts, bytes[] memory nestedAssetData) = decodeMultiAssetData(assetData);
uint256 length = nestedAssetData.length;
for (uint256 i = 0; i != length; i++) {
// Query allowance of individual assetData
uint256 totalAllowance = getAssetProxyAllowance(ownerAddress, nestedAssetData[i]);
// Scale total allowance down by corresponding value in assetData
uint256 scaledAllowance = totalAllowance / amounts[i];
if (scaledAllowance < allowance || allowance == 0) {
allowance = scaledAllowance;
}
}
return allowance;
}
if (assetProxyId == ERC20_PROXY_ID) {
// Get ERC20 token address
address tokenAddress = assetData.readAddress(16);
// Encode data for `allowance(ownerAddress, _ERC20_PROXY_ADDRESS)`
bytes memory allowanceData = abi.encodeWithSelector(
_ERC20_ALLOWANCE_SELECTOR,
ownerAddress,
_ERC20_PROXY_ADDRESS
);
// Query allowance
(bool success, bytes memory returnData) = tokenAddress.staticcall(allowanceData);
allowance = success && returnData.length == 32 ? returnData.readUint256(0) : 0;
} else if (assetProxyId == ERC721_PROXY_ID) {
// Get ERC721 token address and id
(, address tokenAddress, uint256 tokenId) = decodeERC721AssetData(assetData);
// Encode data for `isApprovedForAll(ownerAddress, _ERC721_PROXY_ADDRESS)`
bytes memory isApprovedForAllData = abi.encodeWithSelector(
_ERC721_IS_APPROVED_FOR_ALL_SELECTOR,
ownerAddress,
_ERC721_PROXY_ADDRESS
);
(bool success, bytes memory returnData) = tokenAddress.staticcall(isApprovedForAllData);
// If not approved for all, call `getApproved(tokenId)`
if (!success || returnData.length != 32 || returnData.readUint256(0) != 1) {
// Encode data for `getApproved(tokenId)`
bytes memory getApprovedData = abi.encodeWithSelector(_ERC721_GET_APPROVED_SELECTOR, tokenId);
(success, returnData) = tokenAddress.staticcall(getApprovedData);
// Allowance is 1 if successful and the approved address is the ERC721Proxy
allowance = success && returnData.length == 32 && returnData.readAddress(12) == _ERC721_PROXY_ADDRESS ? 1 : 0;
} else {
// Allowance is 2^256 - 1 if `isApprovedForAll` returned true
allowance = _MAX_UINT256;
}
} else if (assetProxyId == ERC1155_PROXY_ID) {
// Get ERC1155 token address
(, address tokenAddress, , , ) = decodeERC1155AssetData(assetData);
// Encode data for `isApprovedForAll(ownerAddress, _ERC1155_PROXY_ADDRESS)`
bytes memory isApprovedForAllData = abi.encodeWithSelector(
_ERC1155_IS_APPROVED_FOR_ALL_SELECTOR,
ownerAddress,
_ERC1155_PROXY_ADDRESS
);
// Query allowance
(bool success, bytes memory returnData) = tokenAddress.staticcall(isApprovedForAllData);
allowance = success && returnData.length == 32 && returnData.readUint256(0) == 1 ? _MAX_UINT256 : 0;
} else if (assetProxyId == STATIC_CALL_PROXY_ID) {
// The StaticCallProxy does not require any approvals
allowance = _MAX_UINT256;
}
// Allowance will be 0 if the assetProxyId is unknown
return allowance;
}
/// @dev Calls getAssetProxyAllowance() for each element of assetData.
/// @param ownerAddress Owner of the assets specified by assetData.
/// @param assetData Array of asset details, each encoded per the AssetProxy contract specification.
/// @return An array of asset allowances from getAllowance(), with each
/// element corresponding to the same-indexed element in the assetData input.
function getBatchAssetProxyAllowances(address ownerAddress, bytes[] memory assetData)
public
view
returns (uint256[] memory allowances)
{
uint256 length = assetData.length;
allowances = new uint256[](length);
for (uint256 i = 0; i != length; i++) {
allowances[i] = getAssetProxyAllowance(ownerAddress, assetData[i]);
}
return allowances;
}
/// @dev Calls getBalance() and getAllowance() for assetData.
/// @param ownerAddress Owner of the assets specified by assetData.
/// @param assetData Details of asset, encoded per the AssetProxy contract specification.
/// @return Number of assets (or asset baskets) held by owner, and number
/// of assets (or asset baskets) that the corresponding AssetProxy is authorized to spend.
function getBalanceAndAssetProxyAllowance(address ownerAddress, bytes memory assetData)
public
view
returns (uint256 balance, uint256 allowance)
{
balance = getBalance(ownerAddress, assetData);
allowance = getAssetProxyAllowance(ownerAddress, assetData);
return (balance, allowance);
}
/// @dev Calls getBatchBalances() and getBatchAllowances() for each element of assetData.
/// @param ownerAddress Owner of the assets specified by assetData.
/// @param assetData Array of asset details, each encoded per the AssetProxy contract specification.
/// @return An array of asset balances from getBalance(), and an array of
/// asset allowances from getAllowance(), with each element
/// corresponding to the same-indexed element in the assetData input.
function getBatchBalancesAndAssetProxyAllowances(address ownerAddress, bytes[] memory assetData)
public
view
returns (uint256[] memory balances, uint256[] memory allowances)
{
balances = getBatchBalances(ownerAddress, assetData);
allowances = getBatchAssetProxyAllowances(ownerAddress, assetData);
return (balances, allowances);
}
/// @dev Encode ERC-20 asset data into the format described in the AssetProxy contract specification.
/// @param tokenAddress The address of the ERC-20 contract hosting the asset to be traded.
/// @return AssetProxy-compliant data describing the asset.
function encodeERC20AssetData(address tokenAddress)
public
pure
returns (bytes memory assetData)
{
assetData = abi.encodeWithSelector(ERC20_PROXY_ID, tokenAddress);
return assetData;
}
/// @dev Decode ERC-20 asset data from the format described in the AssetProxy contract specification.
/// @param assetData AssetProxy-compliant asset data describing an ERC-20 asset.
/// @return The ERC-20 AssetProxy identifier, and the address of the ERC-20
/// contract hosting this asset.
function decodeERC20AssetData(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId,
address tokenAddress
)
{
assetProxyId = assetData.readBytes4(0);
require(
assetProxyId == ERC20_PROXY_ID,
"WRONG_PROXY_ID"
);
tokenAddress = assetData.readAddress(16);
return (assetProxyId, tokenAddress);
}
/// @dev Encode ERC-721 asset data into the format described in the AssetProxy specification.
/// @param tokenAddress The address of the ERC-721 contract hosting the asset to be traded.
/// @param tokenId The identifier of the specific asset to be traded.
/// @return AssetProxy-compliant asset data describing the asset.
function encodeERC721AssetData(address tokenAddress, uint256 tokenId)
public
pure
returns (bytes memory assetData)
{
assetData = abi.encodeWithSelector(
ERC721_PROXY_ID,
tokenAddress,
tokenId
);
return assetData;
}
/// @dev Decode ERC-721 asset data from the format described in the AssetProxy contract specification.
/// @param assetData AssetProxy-compliant asset data describing an ERC-721 asset.
/// @return The ERC-721 AssetProxy identifier, the address of the ERC-721
/// contract hosting this asset, and the identifier of the specific
/// asset to be traded.
function decodeERC721AssetData(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId,
address tokenAddress,
uint256 tokenId
)
{
assetProxyId = assetData.readBytes4(0);
require(
assetProxyId == ERC721_PROXY_ID,
"WRONG_PROXY_ID"
);
tokenAddress = assetData.readAddress(16);
tokenId = assetData.readUint256(36);
return (assetProxyId, tokenAddress, tokenId);
}
/// @dev Encode ERC-1155 asset data into the format described in the AssetProxy contract specification.
/// @param tokenAddress The address of the ERC-1155 contract hosting the asset(s) to be traded.
/// @param tokenIds The identifiers of the specific assets to be traded.
/// @param tokenValues The amounts of each asset to be traded.
/// @param callbackData Data to be passed to receiving contracts when a transfer is performed.
/// @return AssetProxy-compliant asset data describing the set of assets.
function encodeERC1155AssetData(
address tokenAddress,
uint256[] memory tokenIds,
uint256[] memory tokenValues,
bytes memory callbackData
)
public
pure
returns (bytes memory assetData)
{
assetData = abi.encodeWithSelector(
ERC1155_PROXY_ID,
tokenAddress,
tokenIds,
tokenValues,
callbackData
);
return assetData;
}
/// @dev Decode ERC-1155 asset data from the format described in the AssetProxy contract specification.
/// @param assetData AssetProxy-compliant asset data describing an ERC-1155 set of assets.
/// @return The ERC-1155 AssetProxy identifier, the address of the ERC-1155
/// contract hosting the assets, an array of the identifiers of the
/// assets to be traded, an array of asset amounts to be traded, and
/// callback data. Each element of the arrays corresponds to the
/// same-indexed element of the other array. Return values specified as
/// `memory` are returned as pointers to locations within the memory of
/// the input parameter `assetData`.
function decodeERC1155AssetData(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId,
address tokenAddress,
uint256[] memory tokenIds,
uint256[] memory tokenValues,
bytes memory callbackData
)
{
assetProxyId = assetData.readBytes4(0);
require(
assetProxyId == ERC1155_PROXY_ID,
"WRONG_PROXY_ID"
);
assembly {
// Skip selector and length to get to the first parameter:
assetData := add(assetData, 36)
// Read the value of the first parameter:
tokenAddress := mload(assetData)
// Point to the next parameter's data:
tokenIds := add(assetData, mload(add(assetData, 32)))
// Point to the next parameter's data:
tokenValues := add(assetData, mload(add(assetData, 64)))
// Point to the next parameter's data:
callbackData := add(assetData, mload(add(assetData, 96)))
}
return (
assetProxyId,
tokenAddress,
tokenIds,
tokenValues,
callbackData
);
}
/// @dev Encode data for multiple assets, per the AssetProxy contract specification.
/// @param amounts The amounts of each asset to be traded.
/// @param nestedAssetData AssetProxy-compliant data describing each asset to be traded.
/// @return AssetProxy-compliant data describing the set of assets.
function encodeMultiAssetData(uint256[] memory amounts, bytes[] memory nestedAssetData)
public
pure
returns (bytes memory assetData)
{
assetData = abi.encodeWithSelector(
MULTI_ASSET_PROXY_ID,
amounts,
nestedAssetData
);
return assetData;
}
/// @dev Decode multi-asset data from the format described in the AssetProxy contract specification.
/// @param assetData AssetProxy-compliant data describing a multi-asset basket.
/// @return The Multi-Asset AssetProxy identifier, an array of the amounts
/// of the assets to be traded, and an array of the
/// AssetProxy-compliant data describing each asset to be traded. Each
/// element of the arrays corresponds to the same-indexed element of the other array.
function decodeMultiAssetData(bytes memory assetData)
public
pure
returns (
bytes4 assetProxyId,
uint256[] memory amounts,
bytes[] memory nestedAssetData
)
{
assetProxyId = assetData.readBytes4(0);
require(
assetProxyId == MULTI_ASSET_PROXY_ID,
"WRONG_PROXY_ID"
);
// solhint-disable indent
(amounts, nestedAssetData) = abi.decode(
assetData.slice(4, assetData.length),
(uint256[], bytes[])
);
// solhint-enable indent
}
/// @dev Calls `asset.ownerOf(tokenId)`, but returns a null owner instead of reverting on an unowned asset.
/// @param tokenAddress Address of ERC721 asset.
/// @param tokenId The identifier for the specific NFT.
/// @return Owner of tokenId or null address if unowned.
function getERC721TokenOwner(address tokenAddress, uint256 tokenId)
public
view
returns (address ownerAddress)
{
bytes memory ownerOfCalldata = abi.encodeWithSelector(
_ERC721_OWNER_OF_SELECTOR,
tokenId
);
(bool success, bytes memory returnData) = tokenAddress.staticcall(ownerOfCalldata);
ownerAddress = (success && returnData.length == 32) ? returnData.readAddress(12) : address(0);
return ownerAddress;
}
}
contract OrderValidationUtils is
LibAssetData,
LibMath
{
using LibBytes for bytes;
// solhint-disable var-name-mixedcase
bytes internal _ZRX_ASSET_DATA;
// solhint-enable var-name-mixedcase
constructor (address _exchange, bytes memory _zrxAssetData)
public
LibAssetData(_exchange)
{
_ZRX_ASSET_DATA = _zrxAssetData;
}
/// @dev Fetches all order-relevant information needed to validate if the supplied order is fillable.
/// @param order The order structure.
/// @param signature Signature provided by maker that proves the order's authenticity.
/// `0x01` can always be provided if the signature does not need to be validated.
/// @return The orderInfo (hash, status, and `takerAssetAmount` already filled for the given order),
/// fillableTakerAssetAmount (amount of the order's `takerAssetAmount` that is fillable given all on-chain state),
/// and isValidSignature (validity of the provided signature).
/// NOTE: If the `takerAssetData` encodes data for multiple assets, `fillableTakerAssetAmount` will represent a "scaled"
/// amount, meaning it must be multiplied by all the individual asset amounts within the `takerAssetData` to get the final
/// amount of each asset that can be filled.
function getOrderRelevantState(LibOrder.Order memory order, bytes memory signature)
public
view
returns (
LibOrder.OrderInfo memory orderInfo,
uint256 fillableTakerAssetAmount,
bool isValidSignature
)
{
// Get info specific to order
orderInfo = _EXCHANGE.getOrderInfo(order);
// Validate the maker's signature
address makerAddress = order.makerAddress;
isValidSignature = _EXCHANGE.isValidSignature(
orderInfo.orderHash,
makerAddress,
signature
);
// Get the transferable amount of the `makerAsset`
uint256 transferableMakerAssetAmount = getTransferableAssetAmount(makerAddress, order.makerAssetData);
// Assign to stack variables to reduce redundant mloads/sloads
uint256 takerAssetAmount = order.takerAssetAmount;
uint256 makerFee = order.makerFee;
bytes memory zrxAssetData = _ZRX_ASSET_DATA;
// Get the amount of `takerAsset` that is transferable to maker given the transferability of `makerAsset`, `makerFeeAsset`,
// and the total amounts specified in the order
uint256 transferableTakerAssetAmount;
if (order.makerAssetData.equals(zrxAssetData)) {
// If `makerAsset` equals `makerFeeAsset`, the % that can be filled is
// transferableMakerAssetAmount / (makerAssetAmount + makerFee)
transferableTakerAssetAmount = getPartialAmountFloor(
transferableMakerAssetAmount,
safeAdd(order.makerAssetAmount, makerFee),
takerAssetAmount
);
} else {
// Get the transferable amount of the `makerFeeAsset`
uint256 transferableMakerFeeAssetAmount = getTransferableAssetAmount(makerAddress, zrxAssetData);
// If `makerFee` is 0, the % that can be filled is (transferableMakerAssetAmount / makerAssetAmount)
if (makerFee == 0) {
transferableTakerAssetAmount = getPartialAmountFloor(
transferableMakerAssetAmount,
order.makerAssetAmount,
takerAssetAmount
);
// If `makerAsset` does not equal `makerFeeAsset`, the % that can be filled is the lower of
// (transferableMakerAssetAmount / makerAssetAmount) and (transferableMakerAssetFeeAmount / makerFee)
} else {
uint256 transferableMakerToTakerAmount = getPartialAmountFloor(
transferableMakerAssetAmount,
order.makerAssetAmount,
takerAssetAmount
);
uint256 transferableMakerFeeToTakerAmount = getPartialAmountFloor(
transferableMakerFeeAssetAmount,
makerFee,
takerAssetAmount
);
transferableTakerAssetAmount = min256(transferableMakerToTakerAmount, transferableMakerFeeToTakerAmount);
}
}
// `fillableTakerAssetAmount` is the lower of the order's remaining `takerAssetAmount` and the `transferableTakerAssetAmount`
fillableTakerAssetAmount = min256(
safeSub(takerAssetAmount, orderInfo.orderTakerAssetFilledAmount),
transferableTakerAssetAmount
);
return (orderInfo, fillableTakerAssetAmount, isValidSignature);
}
/// @dev Fetches all order-relevant information needed to validate if the supplied orders are fillable.
/// @param orders Array of order structures.
/// @param signatures Array of signatures provided by makers that prove the authenticity of the orders.
/// `0x01` can always be provided if a signature does not need to be validated.
/// @return The ordersInfo (array of the hash, status, and `takerAssetAmount` already filled for each order),
/// fillableTakerAssetAmounts (array of amounts for each order's `takerAssetAmount` that is fillable given all on-chain state),
/// and isValidSignature (array containing the validity of each provided signature).
/// NOTE: If the `takerAssetData` encodes data for multiple assets, each element of `fillableTakerAssetAmounts`
/// will represent a "scaled" amount, meaning it must be multiplied by all the individual asset amounts within
/// the `takerAssetData` to get the final amount of each asset that can be filled.
function getOrderRelevantStates(LibOrder.Order[] memory orders, bytes[] memory signatures)
public
view
returns (
LibOrder.OrderInfo[] memory ordersInfo,
uint256[] memory fillableTakerAssetAmounts,
bool[] memory isValidSignature
)
{
uint256 length = orders.length;
ordersInfo = new LibOrder.OrderInfo[](length);
fillableTakerAssetAmounts = new uint256[](length);
isValidSignature = new bool[](length);
for (uint256 i = 0; i != length; i++) {
(ordersInfo[i], fillableTakerAssetAmounts[i], isValidSignature[i]) = getOrderRelevantState(
orders[i],
signatures[i]
);
}
return (ordersInfo, fillableTakerAssetAmounts, isValidSignature);
}
/// @dev Gets the amount of an asset transferable by the owner.
/// @param ownerAddress Address of the owner of the asset.
/// @param assetData Description of tokens, per the AssetProxy contract specification.
/// @return The amount of the asset tranferable by the owner.
/// NOTE: If the `assetData` encodes data for multiple assets, the `transferableAssetAmount`
/// will represent the amount of times the entire `assetData` can be transferred. To calculate
/// the total individual transferable amounts, this scaled `transferableAmount` must be multiplied by
/// the individual asset amounts located within the `assetData`.
function getTransferableAssetAmount(address ownerAddress, bytes memory assetData)
public
view
returns (uint256 transferableAssetAmount)
{
(uint256 balance, uint256 allowance) = getBalanceAndAssetProxyAllowance(ownerAddress, assetData);
transferableAssetAmount = min256(balance, allowance);
return transferableAssetAmount;
}
}
contract LibExchangeSelectors {
// solhint-disable max-line-length
// allowedValidators
bytes4 constant internal ALLOWED_VALIDATORS_SELECTOR = 0x7b8e3514;
bytes4 constant internal ALLOWED_VALIDATORS_SELECTOR_GENERATOR = bytes4(keccak256("allowedValidators(address,address)"));
// assetProxies
bytes4 constant internal ASSET_PROXIES_SELECTOR = 0x3fd3c997;
bytes4 constant internal ASSET_PROXIES_SELECTOR_GENERATOR = bytes4(keccak256("assetProxies(bytes4)"));
// batchCancelOrders
bytes4 constant internal BATCH_CANCEL_ORDERS_SELECTOR = 0x4ac14782;
bytes4 constant internal BATCH_CANCEL_ORDERS_SELECTOR_GENERATOR = bytes4(keccak256("batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[])"));
// batchFillOrKillOrders
bytes4 constant internal BATCH_FILL_OR_KILL_ORDERS_SELECTOR = 0x4d0ae546;
bytes4 constant internal BATCH_FILL_OR_KILL_ORDERS_SELECTOR_GENERATOR = bytes4(keccak256("batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])"));
// batchFillOrders
bytes4 constant internal BATCH_FILL_ORDERS_SELECTOR = 0x297bb70b;
bytes4 constant internal BATCH_FILL_ORDERS_SELECTOR_GENERATOR = bytes4(keccak256("batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])"));
// batchFillOrdersNoThrow
bytes4 constant internal BATCH_FILL_ORDERS_NO_THROW_SELECTOR = 0x50dde190;
bytes4 constant internal BATCH_FILL_ORDERS_NO_THROW_SELECTOR_GENERATOR = bytes4(keccak256("batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256[],bytes[])"));
// cancelOrder
bytes4 constant internal CANCEL_ORDER_SELECTOR = 0xd46b02c3;
bytes4 constant internal CANCEL_ORDER_SELECTOR_GENERATOR = bytes4(keccak256("cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))"));
// cancelOrdersUpTo
bytes4 constant internal CANCEL_ORDERS_UP_TO_SELECTOR = 0x4f9559b1;
bytes4 constant internal CANCEL_ORDERS_UP_TO_SELECTOR_GENERATOR = bytes4(keccak256("cancelOrdersUpTo(uint256)"));
// cancelled
bytes4 constant internal CANCELLED_SELECTOR = 0x2ac12622;
bytes4 constant internal CANCELLED_SELECTOR_GENERATOR = bytes4(keccak256("cancelled(bytes32)"));
// currentContextAddress
bytes4 constant internal CURRENT_CONTEXT_ADDRESS_SELECTOR = 0xeea086ba;
bytes4 constant internal CURRENT_CONTEXT_ADDRESS_SELECTOR_GENERATOR = bytes4(keccak256("currentContextAddress()"));
// executeTransaction
bytes4 constant internal EXECUTE_TRANSACTION_SELECTOR = 0xbfc8bfce;
bytes4 constant internal EXECUTE_TRANSACTION_SELECTOR_GENERATOR = bytes4(keccak256("executeTransaction(uint256,address,bytes,bytes)"));
// fillOrKillOrder
bytes4 constant internal FILL_OR_KILL_ORDER_SELECTOR = 0x64a3bc15;
bytes4 constant internal FILL_OR_KILL_ORDER_SELECTOR_GENERATOR = bytes4(keccak256("fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)"));
// fillOrder
bytes4 constant internal FILL_ORDER_SELECTOR = 0xb4be83d5;
bytes4 constant internal FILL_ORDER_SELECTOR_GENERATOR = bytes4(keccak256("fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)"));
// fillOrderNoThrow
bytes4 constant internal FILL_ORDER_NO_THROW_SELECTOR = 0x3e228bae;
bytes4 constant internal FILL_ORDER_NO_THROW_SELECTOR_GENERATOR = bytes4(keccak256("fillOrderNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),uint256,bytes)"));
// filled
bytes4 constant internal FILLED_SELECTOR = 0x288cdc91;
bytes4 constant internal FILLED_SELECTOR_GENERATOR = bytes4(keccak256("filled(bytes32)"));
// getAssetProxy
bytes4 constant internal GET_ASSET_PROXY_SELECTOR = 0x60704108;
bytes4 constant internal GET_ASSET_PROXY_SELECTOR_GENERATOR = bytes4(keccak256("getAssetProxy(bytes4)"));
// getOrderInfo
bytes4 constant internal GET_ORDER_INFO_SELECTOR = 0xc75e0a81;
bytes4 constant internal GET_ORDER_INFO_SELECTOR_GENERATOR = bytes4(keccak256("getOrderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes))"));
// getOrdersInfo
bytes4 constant internal GET_ORDERS_INFO_SELECTOR = 0x7e9d74dc;
bytes4 constant internal GET_ORDERS_INFO_SELECTOR_GENERATOR = bytes4(keccak256("getOrdersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[])"));
// isValidSignature
bytes4 constant internal IS_VALID_SIGNATURE_SELECTOR = 0x93634702;
bytes4 constant internal IS_VALID_SIGNATURE_SELECTOR_GENERATOR = bytes4(keccak256("isValidSignature(bytes32,address,bytes)"));
// marketBuyOrders
bytes4 constant internal MARKET_BUY_ORDERS_SELECTOR = 0xe5fa431b;
bytes4 constant internal MARKET_BUY_ORDERS_SELECTOR_GENERATOR = bytes4(keccak256("marketBuyOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])"));
// marketBuyOrdersNoThrow
bytes4 constant internal MARKET_BUY_ORDERS_NO_THROW_SELECTOR = 0xa3e20380;
bytes4 constant internal MARKET_BUY_ORDERS_NO_THROW_SELECTOR_GENERATOR = bytes4(keccak256("marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])"));
// marketSellOrders
bytes4 constant internal MARKET_SELL_ORDERS_SELECTOR = 0x7e1d9808;
bytes4 constant internal MARKET_SELL_ORDERS_SELECTOR_GENERATOR = bytes4(keccak256("marketSellOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])"));
// marketSellOrdersNoThrow
bytes4 constant internal MARKET_SELL_ORDERS_NO_THROW_SELECTOR = 0xdd1c7d18;
bytes4 constant internal MARKET_SELL_ORDERS_NO_THROW_SELECTOR_GENERATOR = bytes4(keccak256("marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],uint256,bytes[])"));
// matchOrders
bytes4 constant internal MATCH_ORDERS_SELECTOR = 0x3c28d861;
bytes4 constant internal MATCH_ORDERS_SELECTOR_GENERATOR = bytes4(keccak256("matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),bytes,bytes)"));
// orderEpoch
bytes4 constant internal ORDER_EPOCH_SELECTOR = 0xd9bfa73e;
bytes4 constant internal ORDER_EPOCH_SELECTOR_GENERATOR = bytes4(keccak256("orderEpoch(address,address)"));
// owner
bytes4 constant internal OWNER_SELECTOR = 0x8da5cb5b;
bytes4 constant internal OWNER_SELECTOR_GENERATOR = bytes4(keccak256("owner()"));
// preSign
bytes4 constant internal PRE_SIGN_SELECTOR = 0x3683ef8e;
bytes4 constant internal PRE_SIGN_SELECTOR_GENERATOR = bytes4(keccak256("preSign(bytes32,address,bytes)"));
// preSigned
bytes4 constant internal PRE_SIGNED_SELECTOR = 0x82c174d0;
bytes4 constant internal PRE_SIGNED_SELECTOR_GENERATOR = bytes4(keccak256("preSigned(bytes32,address)"));
// registerAssetProxy
bytes4 constant internal REGISTER_ASSET_PROXY_SELECTOR = 0xc585bb93;
bytes4 constant internal REGISTER_ASSET_PROXY_SELECTOR_GENERATOR = bytes4(keccak256("registerAssetProxy(address)"));
// setSignatureValidatorApproval
bytes4 constant internal SET_SIGNATURE_VALIDATOR_APPROVAL_SELECTOR = 0x77fcce68;
bytes4 constant internal SET_SIGNATURE_VALIDATOR_APPROVAL_SELECTOR_GENERATOR = bytes4(keccak256("setSignatureValidatorApproval(address,bool)"));
// transactions
bytes4 constant internal TRANSACTIONS_SELECTOR = 0x642f2eaf;
bytes4 constant internal TRANSACTIONS_SELECTOR_GENERATOR = bytes4(keccak256("transactions(bytes32)"));
// transferOwnership
bytes4 constant internal TRANSFER_OWNERSHIP_SELECTOR = 0xf2fde38b;
bytes4 constant internal TRANSFER_OWNERSHIP_SELECTOR_GENERATOR = bytes4(keccak256("transferOwnership(address)"));
}
contract LibEIP712 {
// EIP191 header for EIP712 prefix
string constant internal EIP191_HEADER = "\x19\x01";
// EIP712 Domain Name value
string constant internal EIP712_DOMAIN_NAME = "0x Protocol";
// EIP712 Domain Version value
string constant internal EIP712_DOMAIN_VERSION = "2";
// Hash of the EIP712 Domain Separator Schema
bytes32 constant internal EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = keccak256(abi.encodePacked(
"EIP712Domain(",
"string name,",
"string version,",
"address verifyingContract",
")"
));
// Hash of the EIP712 Domain Separator data
// solhint-disable-next-line var-name-mixedcase
bytes32 public EIP712_DOMAIN_HASH;
constructor ()
public
{
EIP712_DOMAIN_HASH = keccak256(abi.encodePacked(
EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
keccak256(bytes(EIP712_DOMAIN_NAME)),
keccak256(bytes(EIP712_DOMAIN_VERSION)),
uint256(address(this))
));
}
/// @dev Calculates EIP712 encoding for a hash struct in this EIP712 Domain.
/// @param hashStruct The EIP712 hash struct.
/// @return EIP712 hash applied to this EIP712 Domain.
function hashEIP712Message(bytes32 hashStruct)
internal
view
returns (bytes32 result)
{
bytes32 eip712DomainHash = EIP712_DOMAIN_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
contract LibOrder is
LibEIP712
{
// Hash for the EIP712 Order Schema
bytes32 constant internal EIP712_ORDER_SCHEMA_HASH = keccak256(abi.encodePacked(
"Order(",
"address makerAddress,",
"address takerAddress,",
"address feeRecipientAddress,",
"address senderAddress,",
"uint256 makerAssetAmount,",
"uint256 takerAssetAmount,",
"uint256 makerFee,",
"uint256 takerFee,",
"uint256 expirationTimeSeconds,",
"uint256 salt,",
"bytes makerAssetData,",
"bytes takerAssetData",
")"
));
// A valid order remains fillable until it is expired, fully filled, or cancelled.
// An order's state is unaffected by external factors, like account balances.
enum OrderStatus {
INVALID, // Default value
INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount
INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount
FILLABLE, // Order is fillable
EXPIRED, // Order has already expired
FULLY_FILLED, // Order is fully filled
CANCELLED // Order has been cancelled
}
// solhint-disable max-line-length
struct Order {
address makerAddress; // Address that created the order.
address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order.
address feeRecipientAddress; // Address that will recieve fees when order is filled.
address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods.
uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0.
uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0.
uint256 makerFee; // Amount of ZRX paid to feeRecipient by maker when order is filled. If set to 0, no transfer of ZRX from maker to feeRecipient will be attempted.
uint256 takerFee; // Amount of ZRX paid to feeRecipient by taker when order is filled. If set to 0, no transfer of ZRX from taker to feeRecipient will be attempted.
uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires.
uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash.
bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The last byte references the id of this proxy.
bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The last byte references the id of this proxy.
}
// solhint-enable max-line-length
struct OrderInfo {
uint8 orderStatus; // Status that describes order's validity and fillability.
bytes32 orderHash; // EIP712 hash of the order (see LibOrder.getOrderHash).
uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled.
}
/// @dev Calculates Keccak-256 hash of the order.
/// @param order The order structure.
/// @return Keccak-256 EIP712 hash of the order.
function getOrderHash(Order memory order)
internal
view
returns (bytes32 orderHash)
{
orderHash = hashEIP712Message(hashOrder(order));
return orderHash;
}
/// @dev Calculates EIP712 hash of the order.
/// @param order The order structure.
/// @return EIP712 hash of the order.
function hashOrder(Order memory order)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = EIP712_ORDER_SCHEMA_HASH;
bytes32 makerAssetDataHash = keccak256(order.makerAssetData);
bytes32 takerAssetDataHash = keccak256(order.takerAssetData);
// Assembly for more efficiently computing:
// keccak256(abi.encodePacked(
// EIP712_ORDER_SCHEMA_HASH,
// bytes32(order.makerAddress),
// bytes32(order.takerAddress),
// bytes32(order.feeRecipientAddress),
// bytes32(order.senderAddress),
// order.makerAssetAmount,
// order.takerAssetAmount,
// order.makerFee,
// order.takerFee,
// order.expirationTimeSeconds,
// order.salt,
// keccak256(order.makerAssetData),
// keccak256(order.takerAssetData)
// ));
assembly {
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(order, 32)
let pos2 := add(order, 320)
let pos3 := add(order, 352)
// Backup
let temp1 := mload(pos1)
let temp2 := mload(pos2)
let temp3 := mload(pos3)
// Hash in place
mstore(pos1, schemaHash)
mstore(pos2, makerAssetDataHash)
mstore(pos3, takerAssetDataHash)
result := keccak256(pos1, 416)
// Restore
mstore(pos1, temp1)
mstore(pos2, temp2)
mstore(pos3, temp3)
}
return result;
}
}
library LibBytes {
using LibBytes for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
require(
from <= to,
"FROM_LESS_THAN_TO_REQUIRED"
);
require(
to <= b.length,
"TO_LESS_THAN_LENGTH_REQUIRED"
);
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
/// @dev When `from == 0`, the original array will match the slice. In other cases its state will be corrupted.
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
require(
from <= to,
"FROM_LESS_THAN_TO_REQUIRED"
);
require(
to <= b.length,
"TO_LESS_THAN_LENGTH_REQUIRED"
);
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
require(
b.length > 0,
"GREATER_THAN_ZERO_LENGTH_REQUIRED"
);
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Pops the last 20 bytes off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The 20 byte address that was popped off.
function popLast20Bytes(bytes memory b)
internal
pure
returns (address result)
{
require(
b.length >= 20,
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Store last 20 bytes.
result = readAddress(b, b.length - 20);
assembly {
// Subtract 20 from byte array length.
let newLen := sub(mload(b), 20)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
require(
b.length >= index + 20, // 20 is length of address
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
require(
b.length >= index + 32,
"GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
require(
b.length >= index + 32,
"GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
require(
b.length >= index + 4,
"GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED"
);
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Reads nested bytes from a specific position.
/// @dev NOTE: the returned value overlaps with the input value.
/// Both should be treated as immutable.
/// @param b Byte array containing nested bytes.
/// @param index Index of nested bytes.
/// @return result Nested bytes.
function readBytesWithLength(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes memory result)
{
// Read length of nested bytes
uint256 nestedBytesLength = readUint256(b, index);
index += 32;
// Assert length of <b> is valid, given
// length of nested bytes
require(
b.length >= index + nestedBytesLength,
"GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"
);
// Return a pointer to the byte array as it exists inside `b`
assembly {
result := add(b, index)
}
return result;
}
/// @dev Inserts bytes at a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes to insert.
function writeBytesWithLength(
bytes memory b,
uint256 index,
bytes memory input
)
internal
pure
{
// Assert length of <b> is valid, given
// length of input
require(
b.length >= index + 32 + input.length, // 32 bytes to store length
"GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED"
);
// Copy <input> into <b>
memCopy(
b.contentAddress() + index,
input.rawAddress(), // includes length of <input>
input.length + 32 // +32 bytes to store <input> length
);
}
/// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length.
/// @param dest Byte array that will be overwritten with source bytes.
/// @param source Byte array to copy onto dest bytes.
function deepCopyBytes(
bytes memory dest,
bytes memory source
)
internal
pure
{
uint256 sourceLen = source.length;
// Dest length must be >= source length, or some bytes would not be copied.
require(
dest.length >= sourceLen,
"GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED"
);
memCopy(
dest.contentAddress(),
source.contentAddress(),
sourceLen
);
}
}
contract LibTransactionDecoder is
LibExchangeSelectors
{
using LibBytes for bytes;
/// @dev Decodes the call data for an Exchange contract method call.
/// @param transactionData ABI-encoded calldata for an Exchange
/// contract method call.
/// @return The name of the function called, and the parameters it was
/// given. For single-order fills and cancels, the arrays will have
/// just one element.
function decodeZeroExTransactionData(bytes memory transactionData)
public
pure
returns(
string memory functionName,
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
{
bytes4 functionSelector = transactionData.readBytes4(0);
if (functionSelector == BATCH_CANCEL_ORDERS_SELECTOR) {
functionName = "batchCancelOrders";
} else if (functionSelector == BATCH_FILL_ORDERS_SELECTOR) {
functionName = "batchFillOrders";
} else if (functionSelector == BATCH_FILL_ORDERS_NO_THROW_SELECTOR) {
functionName = "batchFillOrdersNoThrow";
} else if (functionSelector == BATCH_FILL_OR_KILL_ORDERS_SELECTOR) {
functionName = "batchFillOrKillOrders";
} else if (functionSelector == CANCEL_ORDER_SELECTOR) {
functionName = "cancelOrder";
} else if (functionSelector == FILL_ORDER_SELECTOR) {
functionName = "fillOrder";
} else if (functionSelector == FILL_ORDER_NO_THROW_SELECTOR) {
functionName = "fillOrderNoThrow";
} else if (functionSelector == FILL_OR_KILL_ORDER_SELECTOR) {
functionName = "fillOrKillOrder";
} else if (functionSelector == MARKET_BUY_ORDERS_SELECTOR) {
functionName = "marketBuyOrders";
} else if (functionSelector == MARKET_BUY_ORDERS_NO_THROW_SELECTOR) {
functionName = "marketBuyOrdersNoThrow";
} else if (functionSelector == MARKET_SELL_ORDERS_SELECTOR) {
functionName = "marketSellOrders";
} else if (functionSelector == MARKET_SELL_ORDERS_NO_THROW_SELECTOR) {
functionName = "marketSellOrdersNoThrow";
} else if (functionSelector == MATCH_ORDERS_SELECTOR) {
functionName = "matchOrders";
} else if (
functionSelector == CANCEL_ORDERS_UP_TO_SELECTOR ||
functionSelector == EXECUTE_TRANSACTION_SELECTOR
// TODO: add new noThrow cancel functions when https://github.com/0xProject/ZEIPs/issues/35 is merged.
) {
revert("UNIMPLEMENTED");
} else {
revert("UNKNOWN_FUNCTION_SELECTOR");
}
if (functionSelector == BATCH_CANCEL_ORDERS_SELECTOR) {
// solhint-disable-next-line indent
orders = abi.decode(transactionData.slice(4, transactionData.length), (LibOrder.Order[]));
takerAssetFillAmounts = new uint256[](0);
signatures = new bytes[](0);
} else if (
functionSelector == BATCH_FILL_OR_KILL_ORDERS_SELECTOR ||
functionSelector == BATCH_FILL_ORDERS_NO_THROW_SELECTOR ||
functionSelector == BATCH_FILL_ORDERS_SELECTOR
) {
(orders, takerAssetFillAmounts, signatures) = _makeReturnValuesForBatchFill(transactionData);
} else if (functionSelector == CANCEL_ORDER_SELECTOR) {
orders = new LibOrder.Order[](1);
orders[0] = abi.decode(transactionData.slice(4, transactionData.length), (LibOrder.Order));
takerAssetFillAmounts = new uint256[](0);
signatures = new bytes[](0);
} else if (
functionSelector == FILL_OR_KILL_ORDER_SELECTOR ||
functionSelector == FILL_ORDER_SELECTOR ||
functionSelector == FILL_ORDER_NO_THROW_SELECTOR
) {
(orders, takerAssetFillAmounts, signatures) = _makeReturnValuesForSingleOrderFill(transactionData);
} else if (
functionSelector == MARKET_BUY_ORDERS_SELECTOR ||
functionSelector == MARKET_BUY_ORDERS_NO_THROW_SELECTOR ||
functionSelector == MARKET_SELL_ORDERS_SELECTOR ||
functionSelector == MARKET_SELL_ORDERS_NO_THROW_SELECTOR
) {
(orders, takerAssetFillAmounts, signatures) = _makeReturnValuesForMarketFill(transactionData);
} else if (functionSelector == MATCH_ORDERS_SELECTOR) {
(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
) = abi.decode(
transactionData.slice(4, transactionData.length),
(LibOrder.Order, LibOrder.Order, bytes, bytes)
);
orders = new LibOrder.Order[](2);
orders[0] = leftOrder;
orders[1] = rightOrder;
takerAssetFillAmounts = new uint256[](2);
takerAssetFillAmounts[0] = leftOrder.takerAssetAmount;
takerAssetFillAmounts[1] = rightOrder.takerAssetAmount;
signatures = new bytes[](2);
signatures[0] = leftSignature;
signatures[1] = rightSignature;
}
}
function _makeReturnValuesForSingleOrderFill(bytes memory transactionData)
private
pure
returns(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
{
orders = new LibOrder.Order[](1);
takerAssetFillAmounts = new uint256[](1);
signatures = new bytes[](1);
// solhint-disable-next-line indent
(orders[0], takerAssetFillAmounts[0], signatures[0]) = abi.decode(
transactionData.slice(4, transactionData.length),
(LibOrder.Order, uint256, bytes)
);
}
function _makeReturnValuesForBatchFill(bytes memory transactionData)
private
pure
returns(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
{
// solhint-disable-next-line indent
(orders, takerAssetFillAmounts, signatures) = abi.decode(
transactionData.slice(4, transactionData.length),
// solhint-disable-next-line indent
(LibOrder.Order[], uint256[], bytes[])
);
}
function _makeReturnValuesForMarketFill(bytes memory transactionData)
private
pure
returns(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
{
takerAssetFillAmounts = new uint256[](1);
// solhint-disable-next-line indent
(orders, takerAssetFillAmounts[0], signatures) = abi.decode(
transactionData.slice(4, transactionData.length),
// solhint-disable-next-line indent
(LibOrder.Order[], uint256, bytes[])
);
}
}
contract EthBalanceChecker {
/// @dev Batch fetches ETH balances
/// @param addresses Array of addresses.
/// @return Array of ETH balances.
function getEthBalances(address[] memory addresses)
public
view
returns (uint256[] memory)
{
uint256[] memory balances = new uint256[](addresses.length);
for (uint256 i = 0; i != addresses.length; i++) {
balances[i] = addresses[i].balance;
}
return balances;
}
}
// solhint-disable no-empty-blocks
contract DevUtils is
OrderValidationUtils,
LibTransactionDecoder,
EthBalanceChecker
{
constructor (address _exchange, bytes memory _zrxAssetData)
public
OrderValidationUtils(_exchange, _zrxAssetData)
{}
}
|
Encode ERC-721 asset data into the format described in the AssetProxy specification. tokenAddress The address of the ERC-721 contract hosting the asset to be traded. tokenId The identifier of the specific asset to be traded. return AssetProxy-compliant asset data describing the asset.
|
function encodeERC721AssetData(address tokenAddress, uint256 tokenId)
public
pure
returns (bytes memory assetData)
{
assetData = abi.encodeWithSelector(
ERC721_PROXY_ID,
tokenAddress,
tokenId
);
return assetData;
}
| 5,522,549
|
pragma solidity >=0.4.25 <0.6.0;
pragma experimental ABIEncoderV2;
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Modifiable
* @notice A contract with basic modifiers
*/
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SelfDestructible
* @notice Contract that allows for self-destruction
*/
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Ownable
* @notice A modifiable that has ownership roles
*/
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Servable
* @notice An ownable that contains registered services and their actions
*/
contract Servable is Ownable {
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the service activation timeout
/// @param timeoutInSeconds The set timeout in unit of seconds
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
// Emit event
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
/// @notice Register a service contract whose activation is immediate
/// @param service The address of the service contract to be registered
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
// Emit event
emit RegisterServiceEvent(service);
}
/// @notice Register a service contract whose activation is deferred by the service activation timeout
/// @param service The address of the service contract to be registered
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
// Emit event
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
/// @notice Deregister a service contract
/// @param service The address of the service contract to be deregistered
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
// Emit event
emit DeregisterServiceEvent(service);
}
/// @notice Enable a named action in an already registered service contract
/// @param service The address of the registered service contract
/// @param action The name of the action to be enabled
function enableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
// Emit event
emit EnableServiceActionEvent(service, action);
}
/// @notice Enable a named action in a service contract
/// @param service The address of the service contract
/// @param action The name of the action to be disabled
function disableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
// Emit event
emit DisableServiceActionEvent(service, action);
}
/// @notice Gauge whether a service contract is registered
/// @param service The address of the service contract
/// @return true if service is registered, else false
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
/// @notice Gauge whether a service contract is registered and active
/// @param service The address of the service contract
/// @return true if service is registered and activate, else false
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
/// @notice Gauge whether a service contract action is enabled which implies also registered and active
/// @param service The address of the service contract
/// @param action The name of action
function isEnabledServiceAction(address service, string memory action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string memory _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string memory action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathIntLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
//
//Functions below accept positive and negative integers and result must not overflow.
//
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
// overflow
require(b != - 1 || a != INT256_MIN);
// overflow
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
//
//Functions below only accept positive integers and result must be greater or equal to zero too.
//
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
//
//Conversion and validation functions.
//
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
//
//Clamping functions.
//
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbUintsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
uint256 value;
}
struct BlockNumbUints {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbUints storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (uint256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbUints storage self, uint256 blockNumber, uint256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbUintsLib.sol:62]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbUints storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbUints storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbUintsLib.sol:92]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbIntsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
int256 value;
}
struct BlockNumbInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbInts storage self)
internal
view
returns (int256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbInts storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbInts storage self, uint256 blockNumber, int256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbIntsLib.sol:62]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbInts storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbIntsLib.sol:92]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library ConstantsLib {
// Get the fraction that represents the entirety, equivalent of 100%
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbDisdIntsLib {
using SafeMathIntLib for int256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Discount {
int256 tier;
int256 value;
}
struct Entry {
uint256 blockNumber;
int256 nominal;
Discount[] discounts;
}
struct BlockNumbDisdInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentNominalValue(BlockNumbDisdInts storage self)
internal
view
returns (int256)
{
return nominalValueAt(self, block.number);
}
function currentDiscountedValue(BlockNumbDisdInts storage self, int256 tier)
internal
view
returns (int256)
{
return discountedValueAt(self, block.number, tier);
}
function currentEntry(BlockNumbDisdInts storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function nominalValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).nominal;
}
function discountedValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber, int256 tier)
internal
view
returns (int256)
{
Entry memory entry = entryAt(self, _blockNumber);
if (0 < entry.discounts.length) {
uint256 index = indexByTier(entry.discounts, tier);
if (0 < index)
return entry.nominal.mul(
ConstantsLib.PARTS_PER().sub(entry.discounts[index - 1].value)
).div(
ConstantsLib.PARTS_PER()
);
else
return entry.nominal;
} else
return entry.nominal;
}
function entryAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addNominalEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbDisdIntsLib.sol:101]"
);
self.entries.length++;
Entry storage entry = self.entries[self.entries.length - 1];
entry.blockNumber = blockNumber;
entry.nominal = nominal;
}
function addDiscountedEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal,
int256[] memory discountTiers, int256[] memory discountValues)
internal
{
require(discountTiers.length == discountValues.length, "Parameter array lengths mismatch [BlockNumbDisdIntsLib.sol:118]");
addNominalEntry(self, blockNumber, nominal);
Entry storage entry = self.entries[self.entries.length - 1];
for (uint256 i = 0; i < discountTiers.length; i++)
entry.discounts.push(Discount(discountTiers[i], discountValues[i]));
}
function count(BlockNumbDisdInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbDisdInts storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbDisdInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbDisdIntsLib.sol:148]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
/// @dev The index returned here is 1-based
function indexByTier(Discount[] memory discounts, int256 tier)
internal
pure
returns (uint256)
{
require(0 < discounts.length, "No discounts found [BlockNumbDisdIntsLib.sol:161]");
for (uint256 i = discounts.length; i > 0; i--)
if (tier >= discounts[i - 1].tier)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title MonetaryTypesLib
* @dev Monetary data types
*/
library MonetaryTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbReferenceCurrenciesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Currency currency;
}
struct BlockNumbReferenceCurrencies {
mapping(address => mapping(uint256 => Entry[])) entriesByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return currencyAt(self, referenceCurrency, block.number);
}
function currentEntry(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (Entry storage)
{
return entryAt(self, referenceCurrency, block.number);
}
function currencyAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency,
uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return entryAt(self, referenceCurrency, _blockNumber).currency;
}
function entryAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency,
uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][indexByBlockNumber(self, referenceCurrency, _blockNumber)];
}
function addEntry(BlockNumbReferenceCurrencies storage self, uint256 blockNumber,
MonetaryTypesLib.Currency memory referenceCurrency, MonetaryTypesLib.Currency memory currency)
internal
{
require(
0 == self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length ||
blockNumber > self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1].blockNumber,
"Later entry found for currency [BlockNumbReferenceCurrenciesLib.sol:67]"
);
self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].push(Entry(blockNumber, currency));
}
function count(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (uint256)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length;
}
function entriesByCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (Entry[] storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id];
}
function indexByBlockNumber(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length, "No entries found for currency [BlockNumbReferenceCurrenciesLib.sol:97]");
for (uint256 i = self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1; i >= 0; i--)
if (blockNumber >= self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbFiguresLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Figure value;
}
struct BlockNumbFigures {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbFigures storage self)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbFigures storage self)
internal
view
returns (Entry storage)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbFigures storage self, uint256 blockNumber, MonetaryTypesLib.Figure memory value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbFiguresLib.sol:65]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbFigures storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbFigures storage self)
internal
view
returns (Entry[] storage)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbFigures storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbFiguresLib.sol:95]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Configuration
* @notice An oracle for configurations values
*/
contract Configuration is Modifiable, Ownable, Servable {
using SafeMathIntLib for int256;
using BlockNumbUintsLib for BlockNumbUintsLib.BlockNumbUints;
using BlockNumbIntsLib for BlockNumbIntsLib.BlockNumbInts;
using BlockNumbDisdIntsLib for BlockNumbDisdIntsLib.BlockNumbDisdInts;
using BlockNumbReferenceCurrenciesLib for BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies;
using BlockNumbFiguresLib for BlockNumbFiguresLib.BlockNumbFigures;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public OPERATIONAL_MODE_ACTION = "operational_mode";
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum OperationalMode {Normal, Exit}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
OperationalMode public operationalMode = OperationalMode.Normal;
BlockNumbUintsLib.BlockNumbUints private updateDelayBlocksByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private confirmationBlocksByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeMakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeTakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private paymentFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbDisdIntsLib.BlockNumbDisdInts)) private currencyPaymentFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeMakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeTakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private paymentMinimumFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbIntsLib.BlockNumbInts)) private currencyPaymentMinimumFeeByBlockNumber;
BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies private feeCurrencyByCurrencyBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletLockTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private cancelOrderChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private settlementChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private fraudStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletSettlementStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private operatorSettlementStakeFractionByBlockNumber;
BlockNumbFiguresLib.BlockNumbFigures private operatorSettlementStakeByBlockNumber;
uint256 public earliestSettlementBlockNumber;
bool public earliestSettlementBlockNumberUpdateDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetOperationalModeExitEvent();
event SetUpdateDelayBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetConfirmationBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetTradeMakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetTradeTakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetPaymentFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetCurrencyPaymentFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] discountTiers, int256[] discountValues);
event SetTradeMakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetTradeTakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetPaymentMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetCurrencyPaymentMinimumFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal);
event SetFeeCurrencyEvent(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId);
event SetWalletLockTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetCancelOrderChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetSettlementChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetWalletSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeEvent(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt,
uint256 stakeCurrencyId);
event SetFraudStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetEarliestSettlementBlockNumberEvent(uint256 earliestSettlementBlockNumber);
event DisableEarliestSettlementBlockNumberUpdateEvent();
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
updateDelayBlocksByBlockNumber.addEntry(block.number, 0);
}
//
// Public functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set operational mode to Exit
/// @dev Once operational mode is set to Exit it may not be set back to Normal
function setOperationalModeExit()
public
onlyEnabledServiceAction(OPERATIONAL_MODE_ACTION)
{
operationalMode = OperationalMode.Exit;
emit SetOperationalModeExitEvent();
}
/// @notice Return true if operational mode is Normal
function isOperationalModeNormal()
public
view
returns (bool)
{
return OperationalMode.Normal == operationalMode;
}
/// @notice Return true if operational mode is Exit
function isOperationalModeExit()
public
view
returns (bool)
{
return OperationalMode.Exit == operationalMode;
}
/// @notice Get the current value of update delay blocks
/// @return The value of update delay blocks
function updateDelayBlocks()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of update delay blocks values
/// @return The count of update delay blocks values
function updateDelayBlocksCount()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.count();
}
/// @notice Set the number of update delay blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newUpdateDelayBlocks The new update delay blocks value
function setUpdateDelayBlocks(uint256 fromBlockNumber, uint256 newUpdateDelayBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
updateDelayBlocksByBlockNumber.addEntry(fromBlockNumber, newUpdateDelayBlocks);
emit SetUpdateDelayBlocksEvent(fromBlockNumber, newUpdateDelayBlocks);
}
/// @notice Get the current value of confirmation blocks
/// @return The value of confirmation blocks
function confirmationBlocks()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of confirmation blocks values
/// @return The count of confirmation blocks values
function confirmationBlocksCount()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.count();
}
/// @notice Set the number of confirmation blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newConfirmationBlocks The new confirmation blocks value
function setConfirmationBlocks(uint256 fromBlockNumber, uint256 newConfirmationBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
confirmationBlocksByBlockNumber.addEntry(fromBlockNumber, newConfirmationBlocks);
emit SetConfirmationBlocksEvent(fromBlockNumber, newConfirmationBlocks);
}
/// @notice Get number of trade maker fee block number tiers
function tradeMakerFeesCount()
public
view
returns (uint256)
{
return tradeMakerFeeByBlockNumber.count();
}
/// @notice Get trade maker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeMakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeMakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade maker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeMakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeMakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of trade taker fee block number tiers
function tradeTakerFeesCount()
public
view
returns (uint256)
{
return tradeTakerFeeByBlockNumber.count();
}
/// @notice Get trade taker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeTakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeTakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade taker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeTakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeTakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers
function paymentFeesCount()
public
view
returns (uint256)
{
return paymentFeeByBlockNumber.count();
}
/// @notice Get payment relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function paymentFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return paymentFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setPaymentFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetPaymentFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers of given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment relative fee for given currency at given block number, possibly discounted by
/// discount tier value
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param discountTier The concerned discount tier
function currencyPaymentFee(uint256 blockNumber, address currencyCt, uint256 currencyId, int256 discountTier)
public
view
returns (int256)
{
if (0 < currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].discountedValueAt(
blockNumber, discountTier
);
else
return paymentFee(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values for given currency at given
/// block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setCurrencyPaymentFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentFeeByBlockNumber[currencyCt][currencyId].addDiscountedEntry(
fromBlockNumber, nominal, discountTiers, discountValues
);
emit SetCurrencyPaymentFeeEvent(
fromBlockNumber, currencyCt, currencyId, nominal, discountTiers, discountValues
);
}
/// @notice Get number of minimum trade maker fee block number tiers
function tradeMakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeMakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade maker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeMakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeMakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade maker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeMakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeMakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum trade taker fee block number tiers
function tradeTakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeTakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade taker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeTakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeTakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade taker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeTakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeTakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers
function paymentMinimumFeesCount()
public
view
returns (uint256)
{
return paymentMinimumFeeByBlockNumber.count();
}
/// @notice Get payment minimum relative fee at given block number
/// @param blockNumber The concerned block number
function paymentMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return paymentMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set payment minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setPaymentMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetPaymentMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers for given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment minimum relative fee for given currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFee(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
if (0 < currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].valueAt(blockNumber);
else
return paymentMinimumFee(blockNumber);
}
/// @notice Set payment minimum relative fee for given currency at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Minimum relative fee
function setCurrencyPaymentMinimumFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].addEntry(fromBlockNumber, nominal);
emit SetCurrencyPaymentMinimumFeeEvent(fromBlockNumber, currencyCt, currencyId, nominal);
}
/// @notice Get number of fee currencies for the given reference currency
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrenciesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return feeCurrencyByCurrencyBlockNumber.count(MonetaryTypesLib.Currency(currencyCt, currencyId));
}
/// @notice Get the fee currency for the given reference currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrency(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (address ct, uint256 id)
{
MonetaryTypesLib.Currency storage _feeCurrency = feeCurrencyByCurrencyBlockNumber.currencyAt(
MonetaryTypesLib.Currency(currencyCt, currencyId), blockNumber
);
ct = _feeCurrency.ct;
id = _feeCurrency.id;
}
/// @notice Set the fee currency for the given reference currency at given block number
/// @param fromBlockNumber Block number from which the update applies
/// @param referenceCurrencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param referenceCurrencyId The ID of the concerned reference currency (0 for ETH and ERC20)
/// @param feeCurrencyCt The address of the concerned fee currency contract (address(0) == ETH)
/// @param feeCurrencyId The ID of the concerned fee currency (0 for ETH and ERC20)
function setFeeCurrency(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
feeCurrencyByCurrencyBlockNumber.addEntry(
fromBlockNumber,
MonetaryTypesLib.Currency(referenceCurrencyCt, referenceCurrencyId),
MonetaryTypesLib.Currency(feeCurrencyCt, feeCurrencyId)
);
emit SetFeeCurrencyEvent(fromBlockNumber, referenceCurrencyCt, referenceCurrencyId,
feeCurrencyCt, feeCurrencyId);
}
/// @notice Get the current value of wallet lock timeout
/// @return The value of wallet lock timeout
function walletLockTimeout()
public
view
returns (uint256)
{
return walletLockTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of wallet lock
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setWalletLockTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletLockTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetWalletLockTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of cancel order challenge timeout
/// @return The value of cancel order challenge timeout
function cancelOrderChallengeTimeout()
public
view
returns (uint256)
{
return cancelOrderChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of cancel order challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setCancelOrderChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
cancelOrderChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetCancelOrderChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of settlement challenge timeout
/// @return The value of settlement challenge timeout
function settlementChallengeTimeout()
public
view
returns (uint256)
{
return settlementChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of settlement challenges
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setSettlementChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
settlementChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetSettlementChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of fraud stake fraction
/// @return The value of fraud stake fraction
function fraudStakeFraction()
public
view
returns (uint256)
{
return fraudStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in fraud challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setFraudStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
fraudStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetFraudStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of wallet settlement stake fraction
/// @return The value of wallet settlement stake fraction
function walletSettlementStakeFraction()
public
view
returns (uint256)
{
return walletSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by wallet
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setWalletSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetWalletSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake fraction
/// @return The value of operator settlement stake fraction
function operatorSettlementStakeFraction()
public
view
returns (uint256)
{
return operatorSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
operatorSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetOperatorSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake
/// @return The value of operator settlement stake
function operatorSettlementStake()
public
view
returns (int256 amount, address currencyCt, uint256 currencyId)
{
MonetaryTypesLib.Figure storage stake = operatorSettlementStakeByBlockNumber.currentValue();
amount = stake.amount;
currencyCt = stake.currency.ct;
currencyId = stake.currency.id;
}
/// @notice Set figure of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeAmount The amount gained
/// @param stakeCurrencyCt The address of currency gained
/// @param stakeCurrencyId The ID of currency gained
function setOperatorSettlementStake(uint256 fromBlockNumber, int256 stakeAmount,
address stakeCurrencyCt, uint256 stakeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
MonetaryTypesLib.Figure memory stake = MonetaryTypesLib.Figure(stakeAmount, MonetaryTypesLib.Currency(stakeCurrencyCt, stakeCurrencyId));
operatorSettlementStakeByBlockNumber.addEntry(fromBlockNumber, stake);
emit SetOperatorSettlementStakeEvent(fromBlockNumber, stakeAmount, stakeCurrencyCt, stakeCurrencyId);
}
/// @notice Set the block number of the earliest settlement initiation
/// @param _earliestSettlementBlockNumber The block number of the earliest settlement
function setEarliestSettlementBlockNumber(uint256 _earliestSettlementBlockNumber)
public
onlyOperator
{
require(!earliestSettlementBlockNumberUpdateDisabled, "Earliest settlement block number update disabled [Configuration.sol:715]");
earliestSettlementBlockNumber = _earliestSettlementBlockNumber;
emit SetEarliestSettlementBlockNumberEvent(earliestSettlementBlockNumber);
}
/// @notice Disable further updates to the earliest settlement block number
/// @dev This operation can not be undone
function disableEarliestSettlementBlockNumberUpdate()
public
onlyOperator
{
earliestSettlementBlockNumberUpdateDisabled = true;
emit DisableEarliestSettlementBlockNumberUpdateEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDelayedBlockNumber(uint256 blockNumber) {
require(
0 == updateDelayBlocksByBlockNumber.count() ||
blockNumber >= block.number + updateDelayBlocksByBlockNumber.currentValue(),
"Block number not sufficiently delayed [Configuration.sol:735]"
);
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that has a client fund property
*/
contract Configurable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Configuration public configuration;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetConfigurationEvent(Configuration oldConfiguration, Configuration newConfiguration);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the configuration contract
/// @param newConfiguration The (address of) Configuration contract instance
function setConfiguration(Configuration newConfiguration)
public
onlyDeployer
notNullAddress(address(newConfiguration))
notSameAddresses(address(newConfiguration), address(configuration))
{
// Set new configuration
Configuration oldConfiguration = configuration;
configuration = newConfiguration;
// Emit event
emit SetConfigurationEvent(oldConfiguration, newConfiguration);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier configurationInitialized() {
require(address(configuration) != address(0), "Configuration not initialized [Configurable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title ConfigurableOperational
* @notice A configurable with modifiers for operational mode state validation
*/
contract ConfigurableOperational is Configurable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyOperationalModeNormal() {
require(configuration.isOperationalModeNormal(), "Operational mode is not normal [ConfigurableOperational.sol:22]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathUintLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUintLib {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library CurrenciesLib {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currencies {
MonetaryTypesLib.Currency[] currencies;
mapping(address => mapping(uint256 => uint256)) indexByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function add(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
if (0 == self.indexByCurrency[currencyCt][currencyId]) {
self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId));
self.indexByCurrency[currencyCt][currencyId] = self.currencies.length;
}
}
function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
uint256 index = self.indexByCurrency[currencyCt][currencyId];
if (0 < index)
removeByIndex(self, index - 1);
}
function removeByIndex(Currencies storage self, uint256 index)
internal
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]");
address currencyCt = self.currencies[index].ct;
uint256 currencyId = self.currencies[index].id;
if (index < self.currencies.length - 1) {
self.currencies[index] = self.currencies[self.currencies.length - 1];
self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1;
}
self.currencies.length--;
self.indexByCurrency[currencyCt][currencyId] = 0;
}
function count(Currencies storage self)
internal
view
returns (uint256)
{
return self.currencies.length;
}
function has(Currencies storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 != self.indexByCurrency[currencyCt][currencyId];
}
function getByIndex(Currencies storage self, uint256 index)
internal
view
returns (MonetaryTypesLib.Currency memory)
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]");
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[] memory)
{
require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]");
require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]");
up = up.clampMax(self.currencies.length - 1);
MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_currencies[i - low] = self.currencies[i];
return _currencies;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library FungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256 amount;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256)) amountByCurrency;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256)
{
return self.amountByCurrency[currencyCt][currencyId];
}
function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber);
return amount;
}
function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = amount;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub(_from, amount, currencyCt, currencyId);
add(_to, amount, currencyCt, currencyId);
}
function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer_nn(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub_nn(_from, amount, currencyCt, currencyId);
add_nn(_to, amount, currencyCt, currencyId);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.amount, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.amount, record.blockNumber);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library NonFungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256[] ids;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256[])) idsByCurrency;
mapping(address => mapping(uint256 => mapping(int256 => uint256))) idIndexById;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[] memory)
{
return self.idsByCurrency[currencyCt][currencyId];
}
function getByIndices(Balance storage self, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp)
internal
view
returns (int256[] memory)
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length)
return new int256[](0);
indexUp = indexUp.clampMax(self.idsByCurrency[currencyCt][currencyId].length - 1);
int256[] memory idsByCurrency = new int256[](indexUp - indexLow + 1);
for (uint256 i = indexLow; i < indexUp; i++)
idsByCurrency[i - indexLow] = self.idsByCurrency[currencyCt][currencyId][i];
return idsByCurrency;
}
function idsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.idsByCurrency[currencyCt][currencyId].length;
}
function hasId(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 < self.idIndexById[currencyCt][currencyId][id];
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256[] memory, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (new int256[](0), 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256[] memory, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.ids, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[] memory, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.ids, record.blockNumber);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function set(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
{
int256[] memory ids = new int256[](1);
ids[0] = id;
set(self, ids, currencyCt, currencyId);
}
function set(Balance storage self, int256[] memory ids, address currencyCt, uint256 currencyId)
internal
{
uint256 i;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId] = ids;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = i + 1;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function reset(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
for (uint256 i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId].length = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
if (0 < self.idIndexById[currencyCt][currencyId][id])
return false;
self.idsByCurrency[currencyCt][currencyId].push(id);
self.idIndexById[currencyCt][currencyId][id] = self.idsByCurrency[currencyCt][currencyId].length;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function sub(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
uint256 index = self.idIndexById[currencyCt][currencyId][id];
if (0 == index)
return false;
if (index < self.idsByCurrency[currencyCt][currencyId].length) {
self.idsByCurrency[currencyCt][currencyId][index - 1] = self.idsByCurrency[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId].length - 1];
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][index - 1]] = index;
}
self.idsByCurrency[currencyCt][currencyId].length--;
self.idIndexById[currencyCt][currencyId][id] = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function transfer(Balance storage _from, Balance storage _to, int256 id,
address currencyCt, uint256 currencyId)
internal
returns (bool)
{
return sub(_from, id, currencyCt, currencyId) && add(_to, id, currencyCt, currencyId);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateInUseCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Balance tracker
* @notice An ownable to track balances of generic types
*/
contract BalanceTracker is Ownable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public DEPOSITED_BALANCE_TYPE = "deposited";
string constant public SETTLED_BALANCE_TYPE = "settled";
string constant public STAGED_BALANCE_TYPE = "staged";
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Wallet {
mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType;
mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bytes32 public depositedBalanceType;
bytes32 public settledBalanceType;
bytes32 public stagedBalanceType;
bytes32[] public _allBalanceTypes;
bytes32[] public _activeBalanceTypes;
bytes32[] public trackedBalanceTypes;
mapping(bytes32 => bool) public trackedBalanceTypeMap;
mapping(address => Wallet) private walletMap;
address[] public trackedWallets;
mapping(address => uint256) public trackedWalletIndexByWallet;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE));
settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE));
stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE));
_allBalanceTypes.push(settledBalanceType);
_allBalanceTypes.push(depositedBalanceType);
_allBalanceTypes.push(stagedBalanceType);
_activeBalanceTypes.push(settledBalanceType);
_activeBalanceTypes.push(depositedBalanceType);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the fungible balance (amount) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance (IDs) of the given wallet, type, currency and index range
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param indexLow The lower index of IDs
/// @param indexUp The upper index of IDs
/// @return The stored balance
function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 indexLow, uint256 indexUp)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices(
currencyCt, currencyId, indexLow, indexUp
);
}
/// @notice Get all the non-fungible balance (IDs) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].get(
currencyCt, currencyId
);
}
/// @notice Get the count of non-fungible IDs of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of IDs
function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount(
currencyCt, currencyId
);
}
/// @notice Gauge whether the ID is included in the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param id The ID of the concerned unit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if ID is included, else false
function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].hasId(
id, currencyCt, currencyId
);
}
/// @notice Set the balance of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if setting fungible balance, else false
function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Set the non-fungible balance IDs of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param ids The ids of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function setIds(address wallet, bytes32 _type, int256[] memory ids, address currencyCt, uint256 currencyId)
public
onlyActiveService
{
// Update the balance
walletMap[wallet].nonFungibleBalanceByType[_type].set(
ids, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Add the given value to the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to add
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if adding fungible balance, else false
function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Subtract the given value from the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to subtract
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if subtracting fungible balance, else false
function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Gauge whether this tracker has in-use data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId);
}
/// @notice Gauge whether this tracker has ever-used data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId);
}
/// @notice Get the count of fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the fungible balance record for the given wallet, type, currency
/// log entry index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of non-fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and record index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of tracked balance types
/// @return The count of tracked balance types
function trackedBalanceTypesCount()
public
view
returns (uint256)
{
return trackedBalanceTypes.length;
}
/// @notice Get the count of tracked wallets
/// @return The count of tracked wallets
function trackedWalletsCount()
public
view
returns (uint256)
{
return trackedWallets.length;
}
/// @notice Get the default full set of balance types
/// @return The set of all balance types
function allBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _allBalanceTypes;
}
/// @notice Get the default set of active balance types
/// @return The set of active balance types
function activeBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _activeBalanceTypes;
}
/// @notice Get the subset of tracked wallets in the given index range
/// @param low The lower index
/// @param up The upper index
/// @return The subset of tracked wallets
function trackedWalletsByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < trackedWallets.length, "No tracked wallets found [BalanceTracker.sol:473]");
require(low <= up, "Bounds parameters mismatch [BalanceTracker.sol:474]");
up = up.clampMax(trackedWallets.length - 1);
address[] memory _trackedWallets = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_trackedWallets[i - low] = trackedWallets[i];
return _trackedWallets;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _updateTrackedBalanceTypes(bytes32 _type)
private
{
if (!trackedBalanceTypeMap[_type]) {
trackedBalanceTypeMap[_type] = true;
trackedBalanceTypes.push(_type);
}
}
function _updateTrackedWallets(address wallet)
private
{
if (0 == trackedWalletIndexByWallet[wallet]) {
trackedWallets.push(wallet);
trackedWalletIndexByWallet[wallet] = trackedWallets.length;
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title BalanceTrackable
* @notice An ownable that has a balance tracker property
*/
contract BalanceTrackable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
BalanceTracker public balanceTracker;
bool public balanceTrackerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetBalanceTrackerEvent(BalanceTracker oldBalanceTracker, BalanceTracker newBalanceTracker);
event FreezeBalanceTrackerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the balance tracker contract
/// @param newBalanceTracker The (address of) BalanceTracker contract instance
function setBalanceTracker(BalanceTracker newBalanceTracker)
public
onlyDeployer
notNullAddress(address(newBalanceTracker))
notSameAddresses(address(newBalanceTracker), address(balanceTracker))
{
// Require that this contract has not been frozen
require(!balanceTrackerFrozen, "Balance tracker frozen [BalanceTrackable.sol:43]");
// Update fields
BalanceTracker oldBalanceTracker = balanceTracker;
balanceTracker = newBalanceTracker;
// Emit event
emit SetBalanceTrackerEvent(oldBalanceTracker, newBalanceTracker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeBalanceTracker()
public
onlyDeployer
{
balanceTrackerFrozen = true;
// Emit event
emit FreezeBalanceTrackerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier balanceTrackerInitialized() {
require(address(balanceTracker) != address(0), "Balance tracker not initialized [BalanceTrackable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AuthorizableServable
* @notice A servable that may be authorized and unauthorized
*/
contract AuthorizableServable is Servable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public initialServiceAuthorizationDisabled;
mapping(address => bool) public initialServiceAuthorizedMap;
mapping(address => mapping(address => bool)) public initialServiceWalletUnauthorizedMap;
mapping(address => mapping(address => bool)) public serviceWalletAuthorizedMap;
mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletAuthorizedMap;
mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletTouchedMap;
mapping(address => mapping(address => bytes32[])) public serviceWalletActionList;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event AuthorizeInitialServiceEvent(address wallet, address service);
event AuthorizeRegisteredServiceEvent(address wallet, address service);
event AuthorizeRegisteredServiceActionEvent(address wallet, address service, string action);
event UnauthorizeRegisteredServiceEvent(address wallet, address service);
event UnauthorizeRegisteredServiceActionEvent(address wallet, address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Add service to initial whitelist of services
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function authorizeInitialService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(!initialServiceAuthorizationDisabled);
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// Enable all actions for given wallet
initialServiceAuthorizedMap[service] = true;
// Emit event
emit AuthorizeInitialServiceEvent(msg.sender, service);
}
/// @notice Disable further initial authorization of services
/// @dev This operation can not be undone
function disableInitialServiceAuthorization()
public
onlyDeployer
{
initialServiceAuthorizationDisabled = true;
}
/// @notice Authorize the given registered service by enabling all of actions
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function authorizeRegisteredService(address service)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// Ensure service is not initial. Initial services are not authorized per action.
require(!initialServiceAuthorizedMap[service]);
// Enable all actions for given wallet
serviceWalletAuthorizedMap[service][msg.sender] = true;
// Emit event
emit AuthorizeRegisteredServiceEvent(msg.sender, service);
}
/// @notice Unauthorize the given registered service by enabling all of actions
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function unauthorizeRegisteredService(address service)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// If initial service then disable it
if (initialServiceAuthorizedMap[service])
initialServiceWalletUnauthorizedMap[service][msg.sender] = true;
// Else disable all actions for given wallet
else {
serviceWalletAuthorizedMap[service][msg.sender] = false;
for (uint256 i = 0; i < serviceWalletActionList[service][msg.sender].length; i++)
serviceActionWalletAuthorizedMap[service][serviceWalletActionList[service][msg.sender][i]][msg.sender] = true;
}
// Emit event
emit UnauthorizeRegisteredServiceEvent(msg.sender, service);
}
/// @notice Gauge whether the given service is authorized for the given wallet
/// @param service The address of the concerned registered service
/// @param wallet The address of the concerned wallet
/// @return true if service is authorized for the given wallet, else false
function isAuthorizedRegisteredService(address service, address wallet)
public
view
returns (bool)
{
return isRegisteredActiveService(service) &&
(isInitialServiceAuthorizedForWallet(service, wallet) || serviceWalletAuthorizedMap[service][wallet]);
}
/// @notice Authorize the given registered service action
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
/// @param action The concerned service action
function authorizeRegisteredServiceAction(address service, string memory action)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
bytes32 actionHash = hashString(action);
// Ensure service action is registered
require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]);
// Ensure service is not initial
require(!initialServiceAuthorizedMap[service]);
// Enable service action for given wallet
serviceWalletAuthorizedMap[service][msg.sender] = false;
serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = true;
if (!serviceActionWalletTouchedMap[service][actionHash][msg.sender]) {
serviceActionWalletTouchedMap[service][actionHash][msg.sender] = true;
serviceWalletActionList[service][msg.sender].push(actionHash);
}
// Emit event
emit AuthorizeRegisteredServiceActionEvent(msg.sender, service, action);
}
/// @notice Unauthorize the given registered service action
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
/// @param action The concerned service action
function unauthorizeRegisteredServiceAction(address service, string memory action)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
bytes32 actionHash = hashString(action);
// Ensure service is registered and action enabled
require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]);
// Ensure service is not initial as it can not be unauthorized per action
require(!initialServiceAuthorizedMap[service]);
// Disable service action for given wallet
serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = false;
// Emit event
emit UnauthorizeRegisteredServiceActionEvent(msg.sender, service, action);
}
/// @notice Gauge whether the given service action is authorized for the given wallet
/// @param service The address of the concerned registered service
/// @param action The concerned service action
/// @param wallet The address of the concerned wallet
/// @return true if service action is authorized for the given wallet, else false
function isAuthorizedRegisteredServiceAction(address service, string memory action, address wallet)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isEnabledServiceAction(service, action) &&
(
isInitialServiceAuthorizedForWallet(service, wallet) ||
serviceWalletAuthorizedMap[service][wallet] ||
serviceActionWalletAuthorizedMap[service][actionHash][wallet]
);
}
function isInitialServiceAuthorizedForWallet(address service, address wallet)
private
view
returns (bool)
{
return initialServiceAuthorizedMap[service] ? !initialServiceWalletUnauthorizedMap[service][wallet] : false;
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyAuthorizedService(address wallet) {
require(isAuthorizedRegisteredService(msg.sender, wallet));
_;
}
modifier onlyAuthorizedServiceAction(string memory action, address wallet) {
require(isAuthorizedRegisteredServiceAction(msg.sender, action, wallet));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Wallet locker
* @notice An ownable to lock and unlock wallets' balance holdings of specific currency(ies)
*/
contract WalletLocker is Ownable, Configurable, AuthorizableServable {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct FungibleLock {
address locker;
address currencyCt;
uint256 currencyId;
int256 amount;
uint256 visibleTime;
uint256 unlockTime;
}
struct NonFungibleLock {
address locker;
address currencyCt;
uint256 currencyId;
int256[] ids;
uint256 visibleTime;
uint256 unlockTime;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => FungibleLock[]) public walletFungibleLocks;
mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerFungibleLockIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyFungibleLockCount;
mapping(address => NonFungibleLock[]) public walletNonFungibleLocks;
mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerNonFungibleLockIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyNonFungibleLockCount;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event LockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds);
event LockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds);
event UnlockFungibleEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt,
uint256 currencyId);
event UnlockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt,
uint256 currencyId);
event UnlockNonFungibleEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt,
uint256 currencyId);
event UnlockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt,
uint256 currencyId);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Lock the given locked wallet's fungible amount of currency on behalf of the given locker wallet
/// @param lockedWallet The address of wallet that will be locked
/// @param lockerWallet The address of wallet that locks
/// @param amount The amount to be locked
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param visibleTimeoutInSeconds The number of seconds until the locked amount is visible, a.o. for seizure
function lockFungibleByProxy(address lockedWallet, address lockerWallet, int256 amount,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds)
public
onlyAuthorizedService(lockedWallet)
{
// Require that locked and locker wallets are not identical
require(lockedWallet != lockerWallet);
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet];
// Require that there is no existing conflicting lock
require(
(0 == lockIndex) ||
(block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime)
);
// Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist
if (0 == lockIndex) {
lockIndex = ++(walletFungibleLocks[lockedWallet].length);
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex;
walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]++;
}
// Update lock parameters
walletFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet;
walletFungibleLocks[lockedWallet][lockIndex - 1].amount = amount;
walletFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt;
walletFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId;
walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime =
block.timestamp.add(visibleTimeoutInSeconds);
walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime =
block.timestamp.add(configuration.walletLockTimeout());
// Emit event
emit LockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId, visibleTimeoutInSeconds);
}
/// @notice Lock the given locked wallet's non-fungible IDs of currency on behalf of the given locker wallet
/// @param lockedWallet The address of wallet that will be locked
/// @param lockerWallet The address of wallet that locks
/// @param ids The IDs to be locked
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param visibleTimeoutInSeconds The number of seconds until the locked ids are visible, a.o. for seizure
function lockNonFungibleByProxy(address lockedWallet, address lockerWallet, int256[] memory ids,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds)
public
onlyAuthorizedService(lockedWallet)
{
// Require that locked and locker wallets are not identical
require(lockedWallet != lockerWallet);
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet];
// Require that there is no existing conflicting lock
require(
(0 == lockIndex) ||
(block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime)
);
// Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist
if (0 == lockIndex) {
lockIndex = ++(walletNonFungibleLocks[lockedWallet].length);
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex;
walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]++;
}
// Update lock parameters
walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids = ids;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime =
block.timestamp.add(visibleTimeoutInSeconds);
walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime =
block.timestamp.add(configuration.walletLockTimeout());
// Emit event
emit LockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId, visibleTimeoutInSeconds);
}
/// @notice Unlock the given locked wallet's fungible amount of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Require that unlock timeout has expired
require(
block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime
);
// Unlock
int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockFungibleEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
/// @notice Unlock by proxy the given locked wallet's fungible amount of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
onlyAuthorizedService(lockedWallet)
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Unlock
int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
/// @notice Unlock the given locked wallet's non-fungible IDs of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Require that unlock timeout has expired
require(
block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime
);
// Unlock
int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockNonFungibleEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId);
}
/// @notice Unlock by proxy the given locked wallet's non-fungible IDs of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockNonFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
onlyAuthorizedService(lockedWallet)
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Unlock
int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId);
}
/// @notice Get the number of fungible locks for the given wallet
/// @param wallet The address of the locked wallet
/// @return The number of fungible locks
function fungibleLocksCount(address wallet)
public
view
returns (uint256)
{
return walletFungibleLocks[wallet].length;
}
/// @notice Get the number of non-fungible locks for the given wallet
/// @param wallet The address of the locked wallet
/// @return The number of non-fungible locks
function nonFungibleLocksCount(address wallet)
public
view
returns (uint256)
{
return walletNonFungibleLocks[wallet].length;
}
/// @notice Get the fungible amount of the given currency held by locked wallet that is
/// locked by locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function lockedAmount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return 0;
return walletFungibleLocks[lockedWallet][lockIndex - 1].amount;
}
/// @notice Get the count of non-fungible IDs of the given currency held by locked wallet that is
/// locked by locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function lockedIdsCount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return 0;
return walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids.length;
}
/// @notice Get the set of non-fungible IDs of the given currency held by locked wallet that is
/// locked by locker wallet and whose indices are in the given range of indices
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param low The lower ID index
/// @param up The upper ID index
function lockedIdsByIndices(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId,
uint256 low, uint256 up)
public
view
returns (int256[] memory)
{
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return new int256[](0);
NonFungibleLock storage lock = walletNonFungibleLocks[lockedWallet][lockIndex - 1];
if (0 == lock.ids.length)
return new int256[](0);
up = up.clampMax(lock.ids.length - 1);
int256[] memory _ids = new int256[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_ids[i - low] = lock.ids[i];
return _ids;
}
/// @notice Gauge whether the given wallet is locked
/// @param wallet The address of the concerned wallet
/// @return true if wallet is locked, else false
function isLocked(address wallet)
public
view
returns (bool)
{
return 0 < walletFungibleLocks[wallet].length ||
0 < walletNonFungibleLocks[wallet].length;
}
/// @notice Gauge whether the given wallet and currency is locked
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if wallet/currency pair is locked, else false
function isLocked(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return 0 < walletCurrencyFungibleLockCount[wallet][currencyCt][currencyId] ||
0 < walletCurrencyNonFungibleLockCount[wallet][currencyCt][currencyId];
}
/// @notice Gauge whether the given locked wallet and currency is locked by the given locker wallet
/// @param lockedWallet The address of the concerned locked wallet
/// @param lockerWallet The address of the concerned locker wallet
/// @return true if lockedWallet is locked by lockerWallet, else false
function isLocked(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return 0 < lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] ||
0 < lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
}
//
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex)
private
returns (int256)
{
int256 amount = walletFungibleLocks[lockedWallet][lockIndex - 1].amount;
if (lockIndex < walletFungibleLocks[lockedWallet].length) {
walletFungibleLocks[lockedWallet][lockIndex - 1] =
walletFungibleLocks[lockedWallet][walletFungibleLocks[lockedWallet].length - 1];
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex;
}
walletFungibleLocks[lockedWallet].length--;
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0;
walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]--;
return amount;
}
function _unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex)
private
returns (int256[] memory)
{
int256[] memory ids = walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids;
if (lockIndex < walletNonFungibleLocks[lockedWallet].length) {
walletNonFungibleLocks[lockedWallet][lockIndex - 1] =
walletNonFungibleLocks[lockedWallet][walletNonFungibleLocks[lockedWallet].length - 1];
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex;
}
walletNonFungibleLocks[lockedWallet].length--;
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0;
walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]--;
return ids;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title WalletLockable
* @notice An ownable that has a wallet locker property
*/
contract WalletLockable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
WalletLocker public walletLocker;
bool public walletLockerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetWalletLockerEvent(WalletLocker oldWalletLocker, WalletLocker newWalletLocker);
event FreezeWalletLockerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the wallet locker contract
/// @param newWalletLocker The (address of) WalletLocker contract instance
function setWalletLocker(WalletLocker newWalletLocker)
public
onlyDeployer
notNullAddress(address(newWalletLocker))
notSameAddresses(address(newWalletLocker), address(walletLocker))
{
// Require that this contract has not been frozen
require(!walletLockerFrozen, "Wallet locker frozen [WalletLockable.sol:43]");
// Update fields
WalletLocker oldWalletLocker = walletLocker;
walletLocker = newWalletLocker;
// Emit event
emit SetWalletLockerEvent(oldWalletLocker, newWalletLocker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeWalletLocker()
public
onlyDeployer
{
walletLockerFrozen = true;
// Emit event
emit FreezeWalletLockerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier walletLockerInitialized() {
require(address(walletLocker) != address(0), "Wallet locker not initialized [WalletLockable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NahmiiTypesLib
* @dev Data types of general nahmii character
*/
library NahmiiTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum ChallengePhase {Dispute, Closed}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OriginFigure {
uint256 originId;
MonetaryTypesLib.Figure figure;
}
struct IntendedConjugateCurrency {
MonetaryTypesLib.Currency intended;
MonetaryTypesLib.Currency conjugate;
}
struct SingleFigureTotalOriginFigures {
MonetaryTypesLib.Figure single;
OriginFigure[] total;
}
struct TotalOriginFigures {
OriginFigure[] total;
}
struct CurrentPreviousInt256 {
int256 current;
int256 previous;
}
struct SingleTotalInt256 {
int256 single;
int256 total;
}
struct IntendedConjugateCurrentPreviousInt256 {
CurrentPreviousInt256 intended;
CurrentPreviousInt256 conjugate;
}
struct IntendedConjugateSingleTotalInt256 {
SingleTotalInt256 intended;
SingleTotalInt256 conjugate;
}
struct WalletOperatorHashes {
bytes32 wallet;
bytes32 operator;
}
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
struct Seal {
bytes32 hash;
Signature signature;
}
struct WalletOperatorSeal {
Seal wallet;
Seal operator;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentTypesLib
* @dev Data types centered around payment
*/
library PaymentTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum PaymentPartyRole {Sender, Recipient}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct PaymentSenderParty {
uint256 nonce;
address wallet;
NahmiiTypesLib.CurrentPreviousInt256 balances;
NahmiiTypesLib.SingleFigureTotalOriginFigures fees;
string data;
}
struct PaymentRecipientParty {
uint256 nonce;
address wallet;
NahmiiTypesLib.CurrentPreviousInt256 balances;
NahmiiTypesLib.TotalOriginFigures fees;
}
struct Operator {
uint256 id;
string data;
}
struct Payment {
int256 amount;
MonetaryTypesLib.Currency currency;
PaymentSenderParty sender;
PaymentRecipientParty recipient;
// Positive transfer is always in direction from sender to recipient
NahmiiTypesLib.SingleTotalInt256 transfers;
NahmiiTypesLib.WalletOperatorSeal seals;
uint256 blockNumber;
Operator operator;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function PAYMENT_KIND()
public
pure
returns (string memory)
{
return "payment";
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentHasher
* @notice Contract that hashes types related to payment
*/
contract PaymentHasher is Ownable {
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function hashPaymentAsWallet(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
bytes32 amountCurrencyHash = hashPaymentAmountCurrency(payment);
bytes32 senderHash = hashPaymentSenderPartyAsWallet(payment.sender);
bytes32 recipientHash = hashAddress(payment.recipient.wallet);
return keccak256(abi.encodePacked(amountCurrencyHash, senderHash, recipientHash));
}
function hashPaymentAsOperator(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
bytes32 walletSignatureHash = hashSignature(payment.seals.wallet.signature);
bytes32 senderHash = hashPaymentSenderPartyAsOperator(payment.sender);
bytes32 recipientHash = hashPaymentRecipientPartyAsOperator(payment.recipient);
bytes32 transfersHash = hashSingleTotalInt256(payment.transfers);
bytes32 operatorHash = hashString(payment.operator.data);
return keccak256(abi.encodePacked(
walletSignatureHash, senderHash, recipientHash, transfersHash, operatorHash
));
}
function hashPaymentAmountCurrency(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
payment.amount,
payment.currency.ct,
payment.currency.id
));
}
function hashPaymentSenderPartyAsWallet(
PaymentTypesLib.PaymentSenderParty memory paymentSenderParty)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
paymentSenderParty.wallet,
paymentSenderParty.data
));
}
function hashPaymentSenderPartyAsOperator(
PaymentTypesLib.PaymentSenderParty memory paymentSenderParty)
public
pure
returns (bytes32)
{
bytes32 rootHash = hashUint256(paymentSenderParty.nonce);
bytes32 balancesHash = hashCurrentPreviousInt256(paymentSenderParty.balances);
bytes32 singleFeeHash = hashFigure(paymentSenderParty.fees.single);
bytes32 totalFeesHash = hashOriginFigures(paymentSenderParty.fees.total);
return keccak256(abi.encodePacked(
rootHash, balancesHash, singleFeeHash, totalFeesHash
));
}
function hashPaymentRecipientPartyAsOperator(
PaymentTypesLib.PaymentRecipientParty memory paymentRecipientParty)
public
pure
returns (bytes32)
{
bytes32 rootHash = hashUint256(paymentRecipientParty.nonce);
bytes32 balancesHash = hashCurrentPreviousInt256(paymentRecipientParty.balances);
bytes32 totalFeesHash = hashOriginFigures(paymentRecipientParty.fees.total);
return keccak256(abi.encodePacked(
rootHash, balancesHash, totalFeesHash
));
}
function hashCurrentPreviousInt256(
NahmiiTypesLib.CurrentPreviousInt256 memory currentPreviousInt256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
currentPreviousInt256.current,
currentPreviousInt256.previous
));
}
function hashSingleTotalInt256(
NahmiiTypesLib.SingleTotalInt256 memory singleTotalInt256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
singleTotalInt256.single,
singleTotalInt256.total
));
}
function hashFigure(MonetaryTypesLib.Figure memory figure)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
figure.amount,
figure.currency.ct,
figure.currency.id
));
}
function hashOriginFigures(NahmiiTypesLib.OriginFigure[] memory originFigures)
public
pure
returns (bytes32)
{
bytes32 hash;
for (uint256 i = 0; i < originFigures.length; i++) {
hash = keccak256(abi.encodePacked(
hash,
originFigures[i].originId,
originFigures[i].figure.amount,
originFigures[i].figure.currency.ct,
originFigures[i].figure.currency.id
)
);
}
return hash;
}
function hashUint256(uint256 _uint256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_uint256));
}
function hashString(string memory _string)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
function hashAddress(address _address)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_address));
}
function hashSignature(NahmiiTypesLib.Signature memory signature)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
signature.v,
signature.r,
signature.s
));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentHashable
* @notice An ownable that has a payment hasher property
*/
contract PaymentHashable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
PaymentHasher public paymentHasher;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetPaymentHasherEvent(PaymentHasher oldPaymentHasher, PaymentHasher newPaymentHasher);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the payment hasher contract
/// @param newPaymentHasher The (address of) PaymentHasher contract instance
function setPaymentHasher(PaymentHasher newPaymentHasher)
public
onlyDeployer
notNullAddress(address(newPaymentHasher))
notSameAddresses(address(newPaymentHasher), address(paymentHasher))
{
// Set new payment hasher
PaymentHasher oldPaymentHasher = paymentHasher;
paymentHasher = newPaymentHasher;
// Emit event
emit SetPaymentHasherEvent(oldPaymentHasher, newPaymentHasher);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier paymentHasherInitialized() {
require(address(paymentHasher) != address(0), "Payment hasher not initialized [PaymentHashable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SignerManager
* @notice A contract to control who can execute some specific actions
*/
contract SignerManager is Ownable {
using SafeMathUintLib for uint256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => uint256) public signerIndicesMap; // 1 based internally
address[] public signers;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterSignerEvent(address signer);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
registerSigner(deployer);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Gauge whether an address is registered signer
/// @param _address The concerned address
/// @return true if address is registered signer, else false
function isSigner(address _address)
public
view
returns (bool)
{
return 0 < signerIndicesMap[_address];
}
/// @notice Get the count of registered signers
/// @return The count of registered signers
function signersCount()
public
view
returns (uint256)
{
return signers.length;
}
/// @notice Get the 0 based index of the given address in the list of signers
/// @param _address The concerned address
/// @return The index of the signer address
function signerIndex(address _address)
public
view
returns (uint256)
{
require(isSigner(_address), "Address not signer [SignerManager.sol:71]");
return signerIndicesMap[_address] - 1;
}
/// @notice Registers a signer
/// @param newSigner The address of the signer to register
function registerSigner(address newSigner)
public
onlyOperator
notNullOrThisAddress(newSigner)
{
if (0 == signerIndicesMap[newSigner]) {
// Set new operator
signers.push(newSigner);
signerIndicesMap[newSigner] = signers.length;
// Emit event
emit RegisterSignerEvent(newSigner);
}
}
/// @notice Get the subset of registered signers in the given 0 based index range
/// @param low The lower inclusive index
/// @param up The upper inclusive index
/// @return The subset of registered signers
function signersByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < signers.length, "No signers found [SignerManager.sol:101]");
require(low <= up, "Bounds parameters mismatch [SignerManager.sol:102]");
up = up.clampMax(signers.length - 1);
address[] memory _signers = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_signers[i - low] = signers[i];
return _signers;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SignerManageable
* @notice A contract to interface ACL
*/
contract SignerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SignerManager public signerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetSignerManagerEvent(address oldSignerManager, address newSignerManager);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address manager) public notNullAddress(manager) {
signerManager = SignerManager(manager);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the signer manager of this contract
/// @param newSignerManager The address of the new signer
function setSignerManager(address newSignerManager)
public
onlyDeployer
notNullOrThisAddress(newSignerManager)
{
if (newSignerManager != address(signerManager)) {
//set new signer
address oldSignerManager = address(signerManager);
signerManager = SignerManager(newSignerManager);
// Emit event
emit SetSignerManagerEvent(oldSignerManager, newSignerManager);
}
}
/// @notice Prefix input hash and do ecrecover on prefixed hash
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @return The address recovered
function ethrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
pure
returns (address)
{
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
return ecrecover(prefixedHash, v, r, s);
}
/// @notice Gauge whether a signature of a hash has been signed by a registered signer
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @return true if the recovered signer is one of the registered signers, else false
function isSignedByRegisteredSigner(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
view
returns (bool)
{
return signerManager.isSigner(ethrecover(hash, v, r, s));
}
/// @notice Gauge whether a signature of a hash has been signed by the claimed signer
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @param signer The claimed signer
/// @return true if the recovered signer equals the input signer, else false
function isSignedBy(bytes32 hash, uint8 v, bytes32 r, bytes32 s, address signer)
public
pure
returns (bool)
{
return signer == ethrecover(hash, v, r, s);
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier signerManagerInitialized() {
require(address(signerManager) != address(0), "Signer manager not initialized [SignerManageable.sol:105]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Validator
* @notice An ownable that validates valuable types (e.g. payment)
*/
contract Validator is Ownable, SignerManageable, Configurable, PaymentHashable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer, address signerManager) Ownable(deployer) SignerManageable(signerManager) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isGenuineOperatorSignature(bytes32 hash, NahmiiTypesLib.Signature memory signature)
public
view
returns (bool)
{
return isSignedByRegisteredSigner(hash, signature.v, signature.r, signature.s);
}
function isGenuineWalletSignature(bytes32 hash, NahmiiTypesLib.Signature memory signature, address wallet)
public
pure
returns (bool)
{
return isSignedBy(hash, signature.v, signature.r, signature.s, wallet);
}
function isGenuinePaymentWalletHash(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return paymentHasher.hashPaymentAsWallet(payment) == payment.seals.wallet.hash;
}
function isGenuinePaymentOperatorHash(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return paymentHasher.hashPaymentAsOperator(payment) == payment.seals.operator.hash;
}
function isGenuinePaymentWalletSeal(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentWalletHash(payment)
&& isGenuineWalletSignature(payment.seals.wallet.hash, payment.seals.wallet.signature, payment.sender.wallet);
}
function isGenuinePaymentOperatorSeal(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentOperatorHash(payment)
&& isGenuineOperatorSignature(payment.seals.operator.hash, payment.seals.operator.signature);
}
function isGenuinePaymentSeals(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentWalletSeal(payment) && isGenuinePaymentOperatorSeal(payment);
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentFeeOfFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
int256 feePartsPer = int256(ConstantsLib.PARTS_PER());
int256 feeAmount = payment.amount
.mul(
configuration.currencyPaymentFee(
payment.blockNumber, payment.currency.ct, payment.currency.id, payment.amount
)
).div(feePartsPer);
if (1 > feeAmount)
feeAmount = 1;
return (payment.sender.fees.single.amount == feeAmount);
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentFeeOfNonFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
(address feeCurrencyCt, uint256 feeCurrencyId) = configuration.feeCurrency(
payment.blockNumber, payment.currency.ct, payment.currency.id
);
return feeCurrencyCt == payment.sender.fees.single.currency.ct
&& feeCurrencyId == payment.sender.fees.single.currency.id;
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentSenderOfFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (!signerManager.isSigner(payment.sender.wallet))
&& (payment.sender.balances.current == payment.sender.balances.previous.sub(payment.transfers.single).sub(payment.sender.fees.single.amount));
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentRecipientOfFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (payment.recipient.balances.current == payment.recipient.balances.previous.add(payment.transfers.single));
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentSenderOfNonFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (!signerManager.isSigner(payment.sender.wallet));
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentRecipientOfNonFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet);
}
function isSuccessivePaymentsPartyNonces(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.PaymentPartyRole firstPaymentPartyRole,
PaymentTypesLib.Payment memory lastPayment,
PaymentTypesLib.PaymentPartyRole lastPaymentPartyRole
)
public
pure
returns (bool)
{
uint256 firstNonce = (PaymentTypesLib.PaymentPartyRole.Sender == firstPaymentPartyRole ? firstPayment.sender.nonce : firstPayment.recipient.nonce);
uint256 lastNonce = (PaymentTypesLib.PaymentPartyRole.Sender == lastPaymentPartyRole ? lastPayment.sender.nonce : lastPayment.recipient.nonce);
return lastNonce == firstNonce.add(1);
}
function isGenuineSuccessivePaymentsBalances(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.PaymentPartyRole firstPaymentPartyRole,
PaymentTypesLib.Payment memory lastPayment,
PaymentTypesLib.PaymentPartyRole lastPaymentPartyRole,
int256 delta
)
public
pure
returns (bool)
{
NahmiiTypesLib.CurrentPreviousInt256 memory firstCurrentPreviousBalances = (PaymentTypesLib.PaymentPartyRole.Sender == firstPaymentPartyRole ? firstPayment.sender.balances : firstPayment.recipient.balances);
NahmiiTypesLib.CurrentPreviousInt256 memory lastCurrentPreviousBalances = (PaymentTypesLib.PaymentPartyRole.Sender == lastPaymentPartyRole ? lastPayment.sender.balances : lastPayment.recipient.balances);
return lastCurrentPreviousBalances.previous == firstCurrentPreviousBalances.current.add(delta);
}
function isGenuineSuccessivePaymentsTotalFees(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.Payment memory lastPayment
)
public
pure
returns (bool)
{
MonetaryTypesLib.Figure memory firstTotalFee = getProtocolFigureByCurrency(firstPayment.sender.fees.total, lastPayment.sender.fees.single.currency);
MonetaryTypesLib.Figure memory lastTotalFee = getProtocolFigureByCurrency(lastPayment.sender.fees.total, lastPayment.sender.fees.single.currency);
return lastTotalFee.amount == firstTotalFee.amount.add(lastPayment.sender.fees.single.amount);
}
function isPaymentParty(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.sender.wallet || wallet == payment.recipient.wallet;
}
function isPaymentSender(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.sender.wallet;
}
function isPaymentRecipient(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.recipient.wallet;
}
function isPaymentCurrency(PaymentTypesLib.Payment memory payment, MonetaryTypesLib.Currency memory currency)
public
pure
returns (bool)
{
return currency.ct == payment.currency.ct && currency.id == payment.currency.id;
}
function isPaymentCurrencyNonFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return payment.currency.ct != payment.sender.fees.single.currency.ct
|| payment.currency.id != payment.sender.fees.single.currency.id;
}
//
// Private unctions
// -----------------------------------------------------------------------------------------------------------------
function getProtocolFigureByCurrency(NahmiiTypesLib.OriginFigure[] memory originFigures, MonetaryTypesLib.Currency memory currency)
private
pure
returns (MonetaryTypesLib.Figure memory) {
for (uint256 i = 0; i < originFigures.length; i++)
if (originFigures[i].figure.currency.ct == currency.ct && originFigures[i].figure.currency.id == currency.id
&& originFigures[i].originId == 0)
return originFigures[i].figure;
return MonetaryTypesLib.Figure(0, currency);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TradeTypesLib
* @dev Data types centered around trade
*/
library TradeTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum CurrencyRole {Intended, Conjugate}
enum LiquidityRole {Maker, Taker}
enum Intention {Buy, Sell}
enum TradePartyRole {Buyer, Seller}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OrderPlacement {
Intention intention;
int256 amount;
NahmiiTypesLib.IntendedConjugateCurrency currencies;
int256 rate;
NahmiiTypesLib.CurrentPreviousInt256 residuals;
}
struct Order {
uint256 nonce;
address wallet;
OrderPlacement placement;
NahmiiTypesLib.WalletOperatorSeal seals;
uint256 blockNumber;
uint256 operatorId;
}
struct TradeOrder {
int256 amount;
NahmiiTypesLib.WalletOperatorHashes hashes;
NahmiiTypesLib.CurrentPreviousInt256 residuals;
}
struct TradeParty {
uint256 nonce;
address wallet;
uint256 rollingVolume;
LiquidityRole liquidityRole;
TradeOrder order;
NahmiiTypesLib.IntendedConjugateCurrentPreviousInt256 balances;
NahmiiTypesLib.SingleFigureTotalOriginFigures fees;
}
struct Trade {
uint256 nonce;
int256 amount;
NahmiiTypesLib.IntendedConjugateCurrency currencies;
int256 rate;
TradeParty buyer;
TradeParty seller;
// Positive intended transfer is always in direction from seller to buyer
// Positive conjugate transfer is always in direction from buyer to seller
NahmiiTypesLib.IntendedConjugateSingleTotalInt256 transfers;
NahmiiTypesLib.Seal seal;
uint256 blockNumber;
uint256 operatorId;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function TRADE_KIND()
public
pure
returns (string memory)
{
return "trade";
}
function ORDER_KIND()
public
pure
returns (string memory)
{
return "order";
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Validatable
* @notice An ownable that has a validator property
*/
contract Validatable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Validator public validator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetValidatorEvent(Validator oldValidator, Validator newValidator);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the validator contract
/// @param newValidator The (address of) Validator contract instance
function setValidator(Validator newValidator)
public
onlyDeployer
notNullAddress(address(newValidator))
notSameAddresses(address(newValidator), address(validator))
{
//set new validator
Validator oldValidator = validator;
validator = newValidator;
// Emit event
emit SetValidatorEvent(oldValidator, newValidator);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier validatorInitialized() {
require(address(validator) != address(0), "Validator not initialized [Validatable.sol:55]");
_;
}
modifier onlyOperatorSealedPayment(PaymentTypesLib.Payment memory payment) {
require(validator.isGenuinePaymentOperatorSeal(payment), "Payment operator seal not genuine [Validatable.sol:60]");
_;
}
modifier onlySealedPayment(PaymentTypesLib.Payment memory payment) {
require(validator.isGenuinePaymentSeals(payment), "Payment seals not genuine [Validatable.sol:65]");
_;
}
modifier onlyPaymentParty(PaymentTypesLib.Payment memory payment, address wallet) {
require(validator.isPaymentParty(payment, wallet), "Wallet not payment party [Validatable.sol:70]");
_;
}
modifier onlyPaymentSender(PaymentTypesLib.Payment memory payment, address wallet) {
require(validator.isPaymentSender(payment, wallet), "Wallet not payment sender [Validatable.sol:75]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Beneficiary
* @notice A recipient of ethers and tokens
*/
contract Beneficiary {
/// @notice Receive ethers to the given wallet's given balance type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
function receiveEthersTo(address wallet, string memory balanceType)
public
payable;
/// @notice Receive token to the given wallet's given balance type
/// @dev The wallet must approve of the token transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
/// @param amount The amount to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public;
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBeneficiary
* @notice A beneficiary of accruals
*/
contract AccrualBeneficiary is Beneficiary {
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
event CloseAccrualPeriodEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory)
public
{
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferController
* @notice A base contract to handle transfers of different currency types
*/
contract TransferController {
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event CurrencyTransferred(address from, address to, uint256 value,
address currencyCt, uint256 currencyId);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isFungible()
public
view
returns (bool);
function standard()
public
view
returns (string memory);
/// @notice MUST be called with DELEGATECALL
function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function approve(address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
//----------------------------------------
function getReceiveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("receive(address,address,uint256,address,uint256)"));
}
function getApproveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("approve(address,uint256,address,uint256)"));
}
function getDispatchSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)"));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManager
* @notice Handles the management of transfer controllers
*/
contract TransferControllerManager is Ownable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
struct CurrencyInfo {
bytes32 standard;
bool blacklisted;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(bytes32 => address) public registeredTransferControllers;
mapping(address => CurrencyInfo) public registeredCurrencies;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterTransferControllerEvent(string standard, address controller);
event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller);
event RegisterCurrencyEvent(address currencyCt, string standard);
event DeregisterCurrencyEvent(address currencyCt);
event BlacklistCurrencyEvent(address currencyCt);
event WhitelistCurrencyEvent(address currencyCt);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function registerTransferController(string calldata standard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
registeredTransferControllers[standardHash] = controller;
// Emit event
emit RegisterTransferControllerEvent(standard, controller);
}
function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]");
bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard));
bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard));
require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]");
require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]");
registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash];
registeredTransferControllers[oldStandardHash] = address(0);
// Emit event
emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller);
}
function registerCurrency(address currencyCt, string calldata standard)
external
onlyOperator
notNullAddress(currencyCt)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]");
registeredCurrencies[currencyCt].standard = standardHash;
// Emit event
emit RegisterCurrencyEvent(currencyCt, standard);
}
function deregisterCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]");
registeredCurrencies[currencyCt].standard = bytes32(0);
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit DeregisterCurrencyEvent(currencyCt);
}
function blacklistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]");
registeredCurrencies[currencyCt].blacklisted = true;
// Emit event
emit BlacklistCurrencyEvent(currencyCt);
}
function whitelistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]");
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit WhitelistCurrencyEvent(currencyCt);
}
/**
@notice The provided standard takes priority over assigned interface to currency
*/
function transferController(address currencyCt, string memory standard)
public
view
returns (TransferController)
{
if (bytes(standard).length > 0) {
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]");
return TransferController(registeredTransferControllers[standardHash]);
}
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]");
require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]");
address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];
require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]");
return TransferController(controllerAddress);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManageable
* @notice An ownable with a transfer controller manager
*/
contract TransferControllerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransferControllerManager public transferControllerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager,
TransferControllerManager newTransferControllerManager);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the currency manager contract
/// @param newTransferControllerManager The (address of) TransferControllerManager contract instance
function setTransferControllerManager(TransferControllerManager newTransferControllerManager)
public
onlyDeployer
notNullAddress(address(newTransferControllerManager))
notSameAddresses(address(newTransferControllerManager), address(transferControllerManager))
{
//set new currency manager
TransferControllerManager oldTransferControllerManager = transferControllerManager;
transferControllerManager = newTransferControllerManager;
// Emit event
emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager);
}
/// @notice Get the transfer controller of the given currency contract address and standard
function transferController(address currencyCt, string memory standard)
internal
view
returns (TransferController)
{
return transferControllerManager.transferController(currencyCt, standard);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transferControllerManagerInitialized() {
require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library TxHistoryLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct AssetEntry {
int256 amount;
uint256 blockNumber;
address currencyCt; //0 for ethers
uint256 currencyId;
}
struct TxHistory {
AssetEntry[] deposits;
mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits;
AssetEntry[] withdrawals;
mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId);
self.deposits.push(deposit);
self.currencyDeposits[currencyCt][currencyId].push(deposit);
}
function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId);
self.withdrawals.push(withdrawal);
self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal);
}
//----
function deposit(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]");
amount = self.deposits[index].amount;
blockNumber = self.deposits[index].blockNumber;
currencyCt = self.deposits[index].currencyCt;
currencyId = self.deposits[index].currencyId;
}
function depositsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.deposits.length;
}
function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]");
amount = self.currencyDeposits[currencyCt][currencyId][index].amount;
blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber;
}
function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyDeposits[currencyCt][currencyId].length;
}
//----
function withdrawal(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]");
amount = self.withdrawals[index].amount;
blockNumber = self.withdrawals[index].blockNumber;
currencyCt = self.withdrawals[index].currencyCt;
currencyId = self.withdrawals[index].currencyId;
}
function withdrawalsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.withdrawals.length;
}
function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]");
amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount;
blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber;
}
function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyWithdrawals[currencyCt][currencyId].length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SecurityBond
* @notice Fund that contains crypto incentive for challenging operator fraud.
*/
contract SecurityBond is Ownable, Configurable, AccrualBeneficiary, Servable, TransferControllerManageable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public REWARD_ACTION = "reward";
string constant public DEPRIVE_ACTION = "deprive";
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct FractionalReward {
uint256 fraction;
uint256 nonce;
uint256 unlockTime;
}
struct AbsoluteReward {
int256 amount;
uint256 nonce;
uint256 unlockTime;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FungibleBalanceLib.Balance private deposited;
TxHistoryLib.TxHistory private txHistory;
CurrenciesLib.Currencies private inUseCurrencies;
mapping(address => FractionalReward) public fractionalRewardByWallet;
mapping(address => mapping(address => mapping(uint256 => AbsoluteReward))) public absoluteRewardByWallet;
mapping(address => mapping(address => mapping(uint256 => uint256))) public claimNonceByWalletCurrency;
mapping(address => FungibleBalanceLib.Balance) private stagedByWallet;
mapping(address => uint256) public nonceByWallet;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event RewardFractionalEvent(address wallet, uint256 fraction, uint256 unlockTimeoutInSeconds);
event RewardAbsoluteEvent(address wallet, int256 amount, address currencyCt, uint256 currencyId,
uint256 unlockTimeoutInSeconds);
event DepriveFractionalEvent(address wallet);
event DepriveAbsoluteEvent(address wallet, address currencyCt, uint256 currencyId);
event ClaimAndTransferToBeneficiaryEvent(address from, Beneficiary beneficiary, string balanceType, int256 amount,
address currencyCt, uint256 currencyId, string standard);
event ClaimAndStageEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event WithdrawEvent(address from, int256 amount, address currencyCt, uint256 currencyId, string standard);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) Servable() public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balance
deposited.add(amount, address(0), 0);
txHistory.addDeposit(amount, address(0), 0);
// Add currency to in-use list
inUseCurrencies.add(address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
receiveTokensTo(msg.sender, "", amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [SecurityBond.sol:145]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Reception by controller failed [SecurityBond.sol:154]");
// Add to balance
deposited.add(amount, currencyCt, currencyId);
txHistory.addDeposit(amount, currencyCt, currencyId);
// Add currency to in-use list
inUseCurrencies.add(currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Get the deposited balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The deposited balance
function depositedBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return deposited.get(currencyCt, currencyId);
}
/// @notice Get the fractional amount deposited balance of the given currency
/// @param currencyCt The contract address of the currency that the wallet is deprived
/// @param currencyId The ID of the currency that the wallet is deprived
/// @param fraction The fraction of sums that the wallet is rewarded
/// @return The fractional amount of deposited balance
function depositedFractionalBalance(address currencyCt, uint256 currencyId, uint256 fraction)
public
view
returns (int256)
{
return deposited.get(currencyCt, currencyId)
.mul(SafeMathIntLib.toInt256(fraction))
.div(ConstantsLib.PARTS_PER());
}
/// @notice Get the staged balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The deposited balance
function stagedBalance(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return stagedByWallet[wallet].get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded
/// @return The number of currencies
function inUseCurrenciesCount()
public
view
returns (uint256)
{
return inUseCurrencies.count();
}
/// @notice Get the currencies recorded with indices in the given range
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range
function inUseCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return inUseCurrencies.getByIndices(low, up);
}
/// @notice Reward the given wallet the given fraction of funds, where the reward is locked
/// for the given number of seconds
/// @param wallet The concerned wallet
/// @param fraction The fraction of sums that the wallet is rewarded
/// @param unlockTimeoutInSeconds The number of seconds for which the reward is locked and should
/// be claimed
function rewardFractional(address wallet, uint256 fraction, uint256 unlockTimeoutInSeconds)
public
notNullAddress(wallet)
onlyEnabledServiceAction(REWARD_ACTION)
{
// Update fractional reward
fractionalRewardByWallet[wallet].fraction = fraction.clampMax(uint256(ConstantsLib.PARTS_PER()));
fractionalRewardByWallet[wallet].nonce = ++nonceByWallet[wallet];
fractionalRewardByWallet[wallet].unlockTime = block.timestamp.add(unlockTimeoutInSeconds);
// Emit event
emit RewardFractionalEvent(wallet, fraction, unlockTimeoutInSeconds);
}
/// @notice Reward the given wallet the given amount of funds, where the reward is locked
/// for the given number of seconds
/// @param wallet The concerned wallet
/// @param amount The amount that the wallet is rewarded
/// @param currencyCt The contract address of the currency that the wallet is rewarded
/// @param currencyId The ID of the currency that the wallet is rewarded
/// @param unlockTimeoutInSeconds The number of seconds for which the reward is locked and should
/// be claimed
function rewardAbsolute(address wallet, int256 amount, address currencyCt, uint256 currencyId,
uint256 unlockTimeoutInSeconds)
public
notNullAddress(wallet)
onlyEnabledServiceAction(REWARD_ACTION)
{
// Update absolute reward
absoluteRewardByWallet[wallet][currencyCt][currencyId].amount = amount;
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce = ++nonceByWallet[wallet];
absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime = block.timestamp.add(unlockTimeoutInSeconds);
// Emit event
emit RewardAbsoluteEvent(wallet, amount, currencyCt, currencyId, unlockTimeoutInSeconds);
}
/// @notice Deprive the given wallet of any fractional reward it has been granted
/// @param wallet The concerned wallet
function depriveFractional(address wallet)
public
onlyEnabledServiceAction(DEPRIVE_ACTION)
{
// Update fractional reward
fractionalRewardByWallet[wallet].fraction = 0;
fractionalRewardByWallet[wallet].nonce = ++nonceByWallet[wallet];
fractionalRewardByWallet[wallet].unlockTime = 0;
// Emit event
emit DepriveFractionalEvent(wallet);
}
/// @notice Deprive the given wallet of any absolute reward it has been granted in the given currency
/// @param wallet The concerned wallet
/// @param currencyCt The contract address of the currency that the wallet is deprived
/// @param currencyId The ID of the currency that the wallet is deprived
function depriveAbsolute(address wallet, address currencyCt, uint256 currencyId)
public
onlyEnabledServiceAction(DEPRIVE_ACTION)
{
// Update absolute reward
absoluteRewardByWallet[wallet][currencyCt][currencyId].amount = 0;
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce = ++nonceByWallet[wallet];
absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime = 0;
// Emit event
emit DepriveAbsoluteEvent(wallet, currencyCt, currencyId);
}
/// @notice Claim reward and transfer to beneficiary
/// @param beneficiary The concerned beneficiary
/// @param balanceType The target balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function claimAndTransferToBeneficiary(Beneficiary beneficiary, string memory balanceType, address currencyCt,
uint256 currencyId, string memory standard)
public
{
// Claim reward
int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId);
// Subtract from deposited balance
deposited.sub(claimedAmount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
beneficiary.receiveEthersTo.value(uint256(claimedAmount))(msg.sender, balanceType);
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(claimedAmount), currencyCt, currencyId
)
);
require(success, "Approval by controller failed [SecurityBond.sol:350]");
beneficiary.receiveTokensTo(msg.sender, balanceType, claimedAmount, currencyCt, currencyId, standard);
}
// Emit event
emit ClaimAndTransferToBeneficiaryEvent(msg.sender, beneficiary, balanceType, claimedAmount, currencyCt, currencyId, standard);
}
/// @notice Claim reward and stage for later withdrawal
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function claimAndStage(address currencyCt, uint256 currencyId)
public
{
// Claim reward
int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId);
// Subtract from deposited balance
deposited.sub(claimedAmount, currencyCt, currencyId);
// Add to staged balance
stagedByWallet[msg.sender].add(claimedAmount, currencyCt, currencyId);
// Emit event
emit ClaimAndStageEvent(msg.sender, claimedAmount, currencyCt, currencyId);
}
/// @notice Withdraw from staged balance of msg.sender
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard)
public
{
// Require that amount is strictly positive
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [SecurityBond.sol:386]");
// Clamp amount to the max given by staged balance
amount = amount.clampMax(stagedByWallet[msg.sender].get(currencyCt, currencyId));
// Subtract to per-wallet staged balance
stagedByWallet[msg.sender].sub(amount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
msg.sender.transfer(uint256(amount));
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId
)
);
require(success, "Dispatch by controller failed [SecurityBond.sol:405]");
}
// Emit event
emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId, standard);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _claim(address wallet, address currencyCt, uint256 currencyId)
private
returns (int256)
{
// Combine claim nonce from rewards
uint256 claimNonce = fractionalRewardByWallet[wallet].nonce.clampMin(
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce
);
// Require that new claim nonce is strictly greater than current stored one
require(
claimNonce > claimNonceByWalletCurrency[wallet][currencyCt][currencyId],
"Claim nonce not strictly greater than previously claimed nonce [SecurityBond.sol:425]"
);
// Combine claim amount from rewards
int256 claimAmount = _fractionalRewardAmountByWalletCurrency(wallet, currencyCt, currencyId).add(
_absoluteRewardAmountByWalletCurrency(wallet, currencyCt, currencyId)
).clampMax(
deposited.get(currencyCt, currencyId)
);
// Require that claim amount is strictly positive, indicating that there is an amount to claim
require(claimAmount.isNonZeroPositiveInt256(), "Claim amount not strictly positive [SecurityBond.sol:438]");
// Update stored claim nonce for wallet and currency
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] = claimNonce;
return claimAmount;
}
function _fractionalRewardAmountByWalletCurrency(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
if (
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] < fractionalRewardByWallet[wallet].nonce &&
block.timestamp >= fractionalRewardByWallet[wallet].unlockTime
)
return deposited.get(currencyCt, currencyId)
.mul(SafeMathIntLib.toInt256(fractionalRewardByWallet[wallet].fraction))
.div(ConstantsLib.PARTS_PER());
else
return 0;
}
function _absoluteRewardAmountByWalletCurrency(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
if (
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] < absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce &&
block.timestamp >= absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime
)
return absoluteRewardByWallet[wallet][currencyCt][currencyId].amount.clampMax(
deposited.get(currencyCt, currencyId)
);
else
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SecurityBondable
* @notice An ownable that has a security bond property
*/
contract SecurityBondable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SecurityBond public securityBond;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetSecurityBondEvent(SecurityBond oldSecurityBond, SecurityBond newSecurityBond);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the security bond contract
/// @param newSecurityBond The (address of) SecurityBond contract instance
function setSecurityBond(SecurityBond newSecurityBond)
public
onlyDeployer
notNullAddress(address(newSecurityBond))
notSameAddresses(address(newSecurityBond), address(securityBond))
{
//set new security bond
SecurityBond oldSecurityBond = securityBond;
securityBond = newSecurityBond;
// Emit event
emit SetSecurityBondEvent(oldSecurityBond, newSecurityBond);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier securityBondInitialized() {
require(address(securityBond) != address(0), "Security bond not initialized [SecurityBondable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title FraudChallenge
* @notice Where fraud challenge results are found
*/
contract FraudChallenge is Ownable, Servable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public ADD_SEIZED_WALLET_ACTION = "add_seized_wallet";
string constant public ADD_DOUBLE_SPENDER_WALLET_ACTION = "add_double_spender_wallet";
string constant public ADD_FRAUDULENT_ORDER_ACTION = "add_fraudulent_order";
string constant public ADD_FRAUDULENT_TRADE_ACTION = "add_fraudulent_trade";
string constant public ADD_FRAUDULENT_PAYMENT_ACTION = "add_fraudulent_payment";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address[] public doubleSpenderWallets;
mapping(address => bool) public doubleSpenderByWallet;
bytes32[] public fraudulentOrderHashes;
mapping(bytes32 => bool) public fraudulentByOrderHash;
bytes32[] public fraudulentTradeHashes;
mapping(bytes32 => bool) public fraudulentByTradeHash;
bytes32[] public fraudulentPaymentHashes;
mapping(bytes32 => bool) public fraudulentByPaymentHash;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event AddDoubleSpenderWalletEvent(address wallet);
event AddFraudulentOrderHashEvent(bytes32 hash);
event AddFraudulentTradeHashEvent(bytes32 hash);
event AddFraudulentPaymentHashEvent(bytes32 hash);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the double spender status of given wallet
/// @param wallet The wallet address for which to check double spender status
/// @return true if wallet is double spender, false otherwise
function isDoubleSpenderWallet(address wallet)
public
view
returns (bool)
{
return doubleSpenderByWallet[wallet];
}
/// @notice Get the number of wallets tagged as double spenders
/// @return Number of double spender wallets
function doubleSpenderWalletsCount()
public
view
returns (uint256)
{
return doubleSpenderWallets.length;
}
/// @notice Add given wallets to store of double spender wallets if not already present
/// @param wallet The first wallet to add
function addDoubleSpenderWallet(address wallet)
public
onlyEnabledServiceAction(ADD_DOUBLE_SPENDER_WALLET_ACTION) {
if (!doubleSpenderByWallet[wallet]) {
doubleSpenderWallets.push(wallet);
doubleSpenderByWallet[wallet] = true;
emit AddDoubleSpenderWalletEvent(wallet);
}
}
/// @notice Get the number of fraudulent order hashes
function fraudulentOrderHashesCount()
public
view
returns (uint256)
{
return fraudulentOrderHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent order
/// @param hash The hash to be tested
function isFraudulentOrderHash(bytes32 hash)
public
view returns (bool) {
return fraudulentByOrderHash[hash];
}
/// @notice Add given order hash to store of fraudulent order hashes if not already present
function addFraudulentOrderHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_ORDER_ACTION)
{
if (!fraudulentByOrderHash[hash]) {
fraudulentByOrderHash[hash] = true;
fraudulentOrderHashes.push(hash);
emit AddFraudulentOrderHashEvent(hash);
}
}
/// @notice Get the number of fraudulent trade hashes
function fraudulentTradeHashesCount()
public
view
returns (uint256)
{
return fraudulentTradeHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent trade
/// @param hash The hash to be tested
/// @return true if hash is the one of a fraudulent trade, else false
function isFraudulentTradeHash(bytes32 hash)
public
view
returns (bool)
{
return fraudulentByTradeHash[hash];
}
/// @notice Add given trade hash to store of fraudulent trade hashes if not already present
function addFraudulentTradeHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_TRADE_ACTION)
{
if (!fraudulentByTradeHash[hash]) {
fraudulentByTradeHash[hash] = true;
fraudulentTradeHashes.push(hash);
emit AddFraudulentTradeHashEvent(hash);
}
}
/// @notice Get the number of fraudulent payment hashes
function fraudulentPaymentHashesCount()
public
view
returns (uint256)
{
return fraudulentPaymentHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent payment
/// @param hash The hash to be tested
/// @return true if hash is the one of a fraudulent payment, else null
function isFraudulentPaymentHash(bytes32 hash)
public
view
returns (bool)
{
return fraudulentByPaymentHash[hash];
}
/// @notice Add given payment hash to store of fraudulent payment hashes if not already present
function addFraudulentPaymentHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_PAYMENT_ACTION)
{
if (!fraudulentByPaymentHash[hash]) {
fraudulentByPaymentHash[hash] = true;
fraudulentPaymentHashes.push(hash);
emit AddFraudulentPaymentHashEvent(hash);
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title FraudChallengable
* @notice An ownable that has a fraud challenge property
*/
contract FraudChallengable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FraudChallenge public fraudChallenge;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetFraudChallengeEvent(FraudChallenge oldFraudChallenge, FraudChallenge newFraudChallenge);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the fraud challenge contract
/// @param newFraudChallenge The (address of) FraudChallenge contract instance
function setFraudChallenge(FraudChallenge newFraudChallenge)
public
onlyDeployer
notNullAddress(address(newFraudChallenge))
notSameAddresses(address(newFraudChallenge), address(fraudChallenge))
{
// Set new fraud challenge
FraudChallenge oldFraudChallenge = fraudChallenge;
fraudChallenge = newFraudChallenge;
// Emit event
emit SetFraudChallengeEvent(oldFraudChallenge, newFraudChallenge);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier fraudChallengeInitialized() {
require(address(fraudChallenge) != address(0), "Fraud challenge not initialized [FraudChallengable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SettlementChallengeTypesLib
* @dev Types for settlement challenges
*/
library SettlementChallengeTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
enum Status {Qualified, Disqualified}
struct Proposal {
address wallet;
uint256 nonce;
uint256 referenceBlockNumber;
uint256 definitionBlockNumber;
uint256 expirationTime;
// Status
Status status;
// Amounts
Amounts amounts;
// Currency
MonetaryTypesLib.Currency currency;
// Info on challenged driip
Driip challenged;
// True is equivalent to reward coming from wallet's balance
bool walletInitiated;
// True if proposal has been terminated
bool terminated;
// Disqualification
Disqualification disqualification;
}
struct Amounts {
// Cumulative (relative) transfer info
int256 cumulativeTransfer;
// Stage info
int256 stage;
// Balances after amounts have been staged
int256 targetBalance;
}
struct Driip {
// Kind ("payment", "trade", ...)
string kind;
// Hash (of operator)
bytes32 hash;
}
struct Disqualification {
// Challenger
address challenger;
uint256 nonce;
uint256 blockNumber;
// Info on candidate driip
Driip candidate;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementChallengeState
* @notice Where null settlements challenge state is managed
*/
contract NullSettlementChallengeState is Ownable, Servable, Configurable, BalanceTrackable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event DisqualifyProposalEvent(address challengedWallet, uint256 challangedNonce, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
address challengerWallet, uint256 candidateNonce, bytes32 candidateHash, string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if initiated by the concerned challenged wallet
function initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:143]");
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:197]");
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index, "No settlement found for wallet and currency [NullSettlementChallengeState.sol:226]");
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber,
proposals[index - 1].walletInitiated, challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:269]");
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:284]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal challenge nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:298]");
return proposals[index - 1].nonce;
}
/// @notice Get the settlement proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:312]");
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the settlement proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:326]");
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the settlement proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:340]");
return proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:354]");
return proposals[index - 1].status;
}
/// @notice Get the settlement proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:368]");
return proposals[index - 1].amounts.stage;
}
/// @notice Get the settlement proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:382]");
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the settlement proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:396]");
return proposals[index - 1].walletInitiated;
}
/// @notice Get the settlement proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:410]");
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the settlement proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:424]");
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the settlement proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:438]");
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the settlement proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:452]");
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the settlement proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:466]");
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated)
private
{
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256(), "Stage amount not positive [NullSettlementChallengeState.sol:478]");
require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [NullSettlementChallengeState.sol:479]");
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
}
function _removeProposal(uint256 index)
private
returns (bool)
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
function _activeBalanceLogEntry(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256 amount, uint256 blockNumber)
{
// Get last log record of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId
);
(int256 settledAmount, uint256 settledBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.settledBalanceType(), currencyCt, currencyId
);
// Set amount as the sum of deposited and settled
amount = depositedAmount.add(settledAmount);
// Set block number as the latest of deposited and settled
blockNumber = depositedBlockNumber > settledBlockNumber ? depositedBlockNumber : settledBlockNumber;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BalanceTrackerLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
function fungibleActiveRecordByBlockNumber(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 _blockNumber)
internal
view
returns (int256 amount, uint256 blockNumber)
{
// Get log records of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = self.fungibleRecordByBlockNumber(
wallet, self.depositedBalanceType(), currency.ct, currency.id, _blockNumber
);
(int256 settledAmount, uint256 settledBlockNumber) = self.fungibleRecordByBlockNumber(
wallet, self.settledBalanceType(), currency.ct, currency.id, _blockNumber
);
// Return the sum of amounts and highest of block numbers
amount = depositedAmount.add(settledAmount);
blockNumber = depositedBlockNumber.clampMin(settledBlockNumber);
}
function fungibleActiveBalanceAmountByBlockNumber(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = fungibleActiveRecordByBlockNumber(self, wallet, currency, blockNumber);
return amount;
}
function fungibleActiveDeltaBalanceAmountByBlockNumbers(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 fromBlockNumber, uint256 toBlockNumber)
internal
view
returns (int256)
{
return fungibleActiveBalanceAmountByBlockNumber(self, wallet, currency, toBlockNumber) -
fungibleActiveBalanceAmountByBlockNumber(self, wallet, currency, fromBlockNumber);
}
// TODO Rename?
function fungibleActiveRecord(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency)
internal
view
returns (int256 amount, uint256 blockNumber)
{
// Get last log records of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = self.lastFungibleRecord(
wallet, self.depositedBalanceType(), currency.ct, currency.id
);
(int256 settledAmount, uint256 settledBlockNumber) = self.lastFungibleRecord(
wallet, self.settledBalanceType(), currency.ct, currency.id
);
// Return the sum of amounts and highest of block numbers
amount = depositedAmount.add(settledAmount);
blockNumber = depositedBlockNumber.clampMin(settledBlockNumber);
}
// TODO Rename?
function fungibleActiveBalanceAmount(BalanceTracker self, address wallet, MonetaryTypesLib.Currency memory currency)
internal
view
returns (int256)
{
return self.get(wallet, self.depositedBalanceType(), currency.ct, currency.id).add(
self.get(wallet, self.settledBalanceType(), currency.ct, currency.id)
);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementDisputeByPayment
* @notice The where payment related disputes of null settlement challenge happens
*/
contract NullSettlementDisputeByPayment is Ownable, Configurable, Validatable, SecurityBondable, WalletLockable,
BalanceTrackable, FraudChallengable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using BalanceTrackerLib for BalanceTracker;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public CHALLENGE_BY_PAYMENT_ACTION = "challenge_by_payment";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
NullSettlementChallengeState public nullSettlementChallengeState;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetNullSettlementChallengeStateEvent(NullSettlementChallengeState oldNullSettlementChallengeState,
NullSettlementChallengeState newNullSettlementChallengeState);
event ChallengeByPaymentEvent(address wallet, uint256 nonce, PaymentTypesLib.Payment payment,
address challenger);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
/// @notice Set the settlement challenge state contract
/// @param newNullSettlementChallengeState The (address of) NullSettlementChallengeState contract instance
function setNullSettlementChallengeState(NullSettlementChallengeState newNullSettlementChallengeState) public
onlyDeployer
notNullAddress(address(newNullSettlementChallengeState))
{
NullSettlementChallengeState oldNullSettlementChallengeState = nullSettlementChallengeState;
nullSettlementChallengeState = newNullSettlementChallengeState;
emit SetNullSettlementChallengeStateEvent(oldNullSettlementChallengeState, nullSettlementChallengeState);
}
/// @notice Challenge the settlement by providing payment candidate
/// @dev This challenges the payment sender's side of things
/// @param wallet The wallet whose settlement is being challenged
/// @param payment The payment candidate that challenges
/// @param challenger The address of the challenger
function challengeByPayment(address wallet, PaymentTypesLib.Payment memory payment, address challenger)
public
onlyEnabledServiceAction(CHALLENGE_BY_PAYMENT_ACTION)
onlySealedPayment(payment)
onlyPaymentSender(payment, wallet)
{
// Require that payment candidate is not labelled fraudulent
require(!fraudChallenge.isFraudulentPaymentHash(payment.seals.operator.hash), "Payment deemed fraudulent [NullSettlementDisputeByPayment.sol:86]");
// Require that proposal has been initiated
require(nullSettlementChallengeState.hasProposal(wallet, payment.currency), "No proposal found [NullSettlementDisputeByPayment.sol:89]");
// Require that proposal has not expired
require(!nullSettlementChallengeState.hasProposalExpired(wallet, payment.currency), "Proposal found expired [NullSettlementDisputeByPayment.sol:92]");
// Require that payment party's nonce is strictly greater than proposal's nonce and its current
// disqualification nonce
require(payment.sender.nonce > nullSettlementChallengeState.proposalNonce(
wallet, payment.currency
), "Payment nonce not strictly greater than proposal nonce [NullSettlementDisputeByPayment.sol:96]");
require(payment.sender.nonce > nullSettlementChallengeState.proposalDisqualificationNonce(
wallet, payment.currency
), "Payment nonce not strictly greater than proposal disqualification nonce [NullSettlementDisputeByPayment.sol:99]");
// Require overrun for this payment to be a valid challenge candidate
require(_overrun(wallet, payment), "No overrun found [NullSettlementDisputeByPayment.sol:104]");
// Reward challenger
_settleRewards(wallet, payment.sender.balances.current, payment.currency, challenger);
// Disqualify proposal, effectively overriding any previous disqualification
nullSettlementChallengeState.disqualifyProposal(
wallet, payment.currency, challenger, payment.blockNumber,
payment.sender.nonce, payment.seals.operator.hash, PaymentTypesLib.PAYMENT_KIND()
);
// Emit event
emit ChallengeByPaymentEvent(
wallet, nullSettlementChallengeState.proposalNonce(wallet, payment.currency), payment, challenger
);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _overrun(address wallet, PaymentTypesLib.Payment memory payment)
private
view
returns (bool)
{
// Get the target balance amount from the proposal
int targetBalanceAmount = nullSettlementChallengeState.proposalTargetBalanceAmount(
wallet, payment.currency
);
// Get the change in active balance since the start of the challenge
int256 deltaBalanceSinceStart = balanceTracker.fungibleActiveBalanceAmount(
wallet, payment.currency
).sub(
balanceTracker.fungibleActiveBalanceAmountByBlockNumber(
wallet, payment.currency,
nullSettlementChallengeState.proposalReferenceBlockNumber(wallet, payment.currency)
)
);
// Get the cumulative transfer of the payment
int256 cumulativeTransfer = balanceTracker.fungibleActiveBalanceAmountByBlockNumber(
wallet, payment.currency, payment.blockNumber
).sub(payment.sender.balances.current);
return targetBalanceAmount.add(deltaBalanceSinceStart) < cumulativeTransfer;
}
// Lock wallet's balances or reward challenger by stake fraction
function _settleRewards(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
if (nullSettlementChallengeState.proposalWalletInitiated(wallet, currency))
_settleBalanceReward(wallet, walletAmount, currency, challenger);
else
_settleSecurityBondReward(wallet, walletAmount, currency, challenger);
}
function _settleBalanceReward(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
// Unlock wallet/currency for existing challenger if previously locked
if (SettlementChallengeTypesLib.Status.Disqualified == nullSettlementChallengeState.proposalStatus(
wallet, currency
))
walletLocker.unlockFungibleByProxy(
wallet,
nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, currency
),
currency.ct, currency.id
);
// Lock wallet for new challenger
walletLocker.lockFungibleByProxy(
wallet, challenger, walletAmount, currency.ct, currency.id, configuration.settlementChallengeTimeout()
);
}
// Settle the two-component reward from security bond.
// The first component is flat figure as obtained from Configuration
// The second component is progressive and calculated as
// min(walletAmount, fraction of SecurityBond's deposited balance)
// both amounts for the given currency
function _settleSecurityBondReward(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
// Deprive existing challenger of reward if previously locked
if (SettlementChallengeTypesLib.Status.Disqualified == nullSettlementChallengeState.proposalStatus(
wallet, currency
))
securityBond.depriveAbsolute(
nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, currency
),
currency.ct, currency.id
);
// Reward the flat component
MonetaryTypesLib.Figure memory flatReward = _flatReward();
securityBond.rewardAbsolute(
challenger, flatReward.amount, flatReward.currency.ct, flatReward.currency.id, 0
);
// Reward the progressive component
int256 progressiveRewardAmount = walletAmount.clampMax(
securityBond.depositedFractionalBalance(
currency.ct, currency.id, configuration.operatorSettlementStakeFraction()
)
);
securityBond.rewardAbsolute(
challenger, progressiveRewardAmount, currency.ct, currency.id, 0
);
}
function _flatReward()
private
view
returns (MonetaryTypesLib.Figure memory)
{
(int256 amount, address currencyCt, uint256 currencyId) = configuration.operatorSettlementStake();
return MonetaryTypesLib.Figure(amount, MonetaryTypesLib.Currency(currencyCt, currencyId));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementChallengeState
* @notice Where driip settlement challenge state is managed
*/
contract DriipSettlementChallengeState is Ownable, Servable, Configurable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
string constant public QUALIFY_PROPOSAL_ACTION = "qualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
mapping(address => mapping(uint256 => mapping(address => mapping(uint256 => uint256)))) public proposalIndexByWalletNonceCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event DisqualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount,
int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber,
bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash,
string candidateKind);
event QualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount,
int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber,
bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash,
string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param cumulativeTransferAmount The proposal cumulative transfer amount
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if reward from candidate balance
/// @param challengedHash The candidate driip hash
/// @param challengedKind The candidate driip kind
function initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string memory challengedKind)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated, challengedHash, challengedKind
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated, challengedHash, challengedKind
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet
if (clearNonce)
proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param clearNonce Clear wallet-nonce-currency triplet entry
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce,
bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:163]");
// Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet
if (clearNonce)
proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:223]");
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:253]");
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance,
currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice (Re)Qualify a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function qualifyProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(QUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:282]");
// Emit event
emit QualifyProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].disqualification.challenger,
proposals[index - 1].disqualification.nonce,
proposals[index - 1].disqualification.candidate.hash,
proposals[index - 1].disqualification.candidate.kind
);
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
delete proposals[index - 1].disqualification;
}
/// @notice Gauge whether a driip settlement challenge for the given wallet-nonce-currency
/// triplet has been proposed and not later removed
/// @param wallet The address of the concerned wallet
/// @param nonce The wallet nonce
/// @param currency The concerned currency
/// @return true if driip settlement challenge has been, else false
function hasProposal(address wallet, uint256 nonce, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:340]");
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:355]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the proposal nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:369]");
return proposals[index - 1].nonce;
}
/// @notice Get the proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:383]");
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal definition block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:397]");
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:411]");
return proposals[index - 1].expirationTime;
}
/// @notice Get the proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:425]");
return proposals[index - 1].status;
}
/// @notice Get the proposal cumulative transfer amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal cumulative transfer amount
function proposalCumulativeTransferAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:439]");
return proposals[index - 1].amounts.cumulativeTransfer;
}
/// @notice Get the proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:453]");
return proposals[index - 1].amounts.stage;
}
/// @notice Get the proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:467]");
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the proposal challenged hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal challenged hash
function proposalChallengedHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:481]");
return proposals[index - 1].challenged.hash;
}
/// @notice Get the proposal challenged kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal challenged kind
function proposalChallengedKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:495]");
return proposals[index - 1].challenged.kind;
}
/// @notice Get the proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:509]");
return proposals[index - 1].walletInitiated;
}
/// @notice Get the proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:523]");
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:537]");
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:551]");
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:565]");
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:579]");
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated,
bytes32 challengedHash, string memory challengedKind)
private
{
// Require that there is no other proposal on the given wallet-nonce-currency triplet
require(
0 == proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id],
"Existing proposal found for wallet, nonce and currency [DriipSettlementChallengeState.sol:592]"
);
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256(), "Stage amount not positive [DriipSettlementChallengeState.sol:598]");
require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [DriipSettlementChallengeState.sol:599]");
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.cumulativeTransfer = cumulativeTransferAmount;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
proposals[index - 1].challenged.hash = challengedHash;
proposals[index - 1].challenged.kind = challengedKind;
// Update index of wallet-nonce-currency triplet
proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id] = index;
}
function _removeProposal(uint256 index)
private
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementChallengeByPayment
* @notice Where null settlements pertaining to payments are started and disputed
*/
contract NullSettlementChallengeByPayment is Ownable, ConfigurableOperational, BalanceTrackable, WalletLockable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using BalanceTrackerLib for BalanceTracker;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
NullSettlementDisputeByPayment public nullSettlementDisputeByPayment;
NullSettlementChallengeState public nullSettlementChallengeState;
DriipSettlementChallengeState public driipSettlementChallengeState;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetNullSettlementDisputeByPaymentEvent(NullSettlementDisputeByPayment oldNullSettlementDisputeByPayment,
NullSettlementDisputeByPayment newNullSettlementDisputeByPayment);
event SetNullSettlementChallengeStateEvent(NullSettlementChallengeState oldNullSettlementChallengeState,
NullSettlementChallengeState newNullSettlementChallengeState);
event SetDriipSettlementChallengeStateEvent(DriipSettlementChallengeState oldDriipSettlementChallengeState,
DriipSettlementChallengeState newDriipSettlementChallengeState);
event StartChallengeEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint currencyId);
event StartChallengeByProxyEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint currencyId, address proxy);
event StopChallengeEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId);
event StopChallengeByProxyEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId, address proxy);
event ChallengeByPaymentEvent(address challengedWallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId, address challengerWallet);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the settlement dispute contract
/// @param newNullSettlementDisputeByPayment The (address of) NullSettlementDisputeByPayment contract instance
function setNullSettlementDisputeByPayment(NullSettlementDisputeByPayment newNullSettlementDisputeByPayment)
public
onlyDeployer
notNullAddress(address(newNullSettlementDisputeByPayment))
{
NullSettlementDisputeByPayment oldNullSettlementDisputeByPayment = nullSettlementDisputeByPayment;
nullSettlementDisputeByPayment = newNullSettlementDisputeByPayment;
emit SetNullSettlementDisputeByPaymentEvent(oldNullSettlementDisputeByPayment, nullSettlementDisputeByPayment);
}
/// @notice Set the null settlement challenge state contract
/// @param newNullSettlementChallengeState The (address of) NullSettlementChallengeState contract instance
function setNullSettlementChallengeState(NullSettlementChallengeState newNullSettlementChallengeState)
public
onlyDeployer
notNullAddress(address(newNullSettlementChallengeState))
{
NullSettlementChallengeState oldNullSettlementChallengeState = nullSettlementChallengeState;
nullSettlementChallengeState = newNullSettlementChallengeState;
emit SetNullSettlementChallengeStateEvent(oldNullSettlementChallengeState, nullSettlementChallengeState);
}
/// @notice Set the driip settlement challenge state contract
/// @param newDriipSettlementChallengeState The (address of) DriipSettlementChallengeState contract instance
function setDriipSettlementChallengeState(DriipSettlementChallengeState newDriipSettlementChallengeState)
public
onlyDeployer
notNullAddress(address(newDriipSettlementChallengeState))
{
DriipSettlementChallengeState oldDriipSettlementChallengeState = driipSettlementChallengeState;
driipSettlementChallengeState = newDriipSettlementChallengeState;
emit SetDriipSettlementChallengeStateEvent(oldDriipSettlementChallengeState, driipSettlementChallengeState);
}
/// @notice Start settlement challenge
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function startChallenge(int256 amount, address currencyCt, uint256 currencyId)
public
{
// Require that wallet is not locked
require(!walletLocker.isLocked(msg.sender), "Wallet found locked [NullSettlementChallengeByPayment.sol:116]");
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Start challenge for wallet
_startChallenge(msg.sender, amount, currency, true);
// Emit event
emit StartChallengeEvent(
msg.sender,
nullSettlementChallengeState.proposalNonce(msg.sender, currency),
amount,
nullSettlementChallengeState.proposalTargetBalanceAmount(msg.sender, currency),
currencyCt, currencyId
);
}
/// @notice Start settlement challenge for the given wallet
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function startChallengeByProxy(address wallet, int256 amount, address currencyCt, uint256 currencyId)
public
onlyOperator
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Start challenge for wallet
_startChallenge(wallet, amount, currency, false);
// Emit event
emit StartChallengeByProxyEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, currency),
amount,
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, currency),
currencyCt, currencyId, msg.sender
);
}
/// @notice Stop settlement challenge
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stopChallenge(address currencyCt, uint256 currencyId)
public
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Stop challenge
_stopChallenge(msg.sender, currency, true);
// Emit event
emit StopChallengeEvent(
msg.sender,
nullSettlementChallengeState.proposalNonce(msg.sender, currency),
nullSettlementChallengeState.proposalStageAmount(msg.sender, currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(msg.sender, currency),
currencyCt, currencyId
);
}
/// @notice Stop settlement challenge
/// @param wallet The concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stopChallengeByProxy(address wallet, address currencyCt, uint256 currencyId)
public
onlyOperator
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Stop challenge
_stopChallenge(wallet, currency, false);
// Emit event
emit StopChallengeByProxyEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, currency),
nullSettlementChallengeState.proposalStageAmount(wallet, currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, currency),
currencyCt, currencyId, msg.sender
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has been defined
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has been initiated, else false
function hasProposal(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposal(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposalTerminated(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposalExpired(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the challenge nonce of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenge nonce
function proposalNonce(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalNonce(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal block number of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal block number
function proposalReferenceBlockNumber(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalReferenceBlockNumber(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal end time of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal end time
function proposalExpirationTime(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalExpirationTime(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the challenge status of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenge status
function proposalStatus(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (SettlementChallengeTypesLib.Status)
{
return nullSettlementChallengeState.proposalStatus(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return nullSettlementChallengeState.proposalStageAmount(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return nullSettlementChallengeState.proposalTargetBalanceAmount(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the balance reward of the given wallet's settlement proposal
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The balance reward of the settlement proposal
function proposalWalletInitiated(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.proposalWalletInitiated(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenger of the settlement disqualification
function proposalDisqualificationChallenger(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (address)
{
return nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The block number of the settlement disqualification
function proposalDisqualificationBlockNumber(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalDisqualificationBlockNumber(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The candidate kind of the settlement disqualification
function proposalDisqualificationCandidateKind(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (string memory)
{
return nullSettlementChallengeState.proposalDisqualificationCandidateKind(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The candidate hash of the settlement disqualification
function proposalDisqualificationCandidateHash(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bytes32)
{
return nullSettlementChallengeState.proposalDisqualificationCandidateHash(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Challenge the settlement by providing payment candidate
/// @param wallet The wallet whose settlement is being challenged
/// @param payment The payment candidate that challenges the null
function challengeByPayment(address wallet, PaymentTypesLib.Payment memory payment)
public
onlyOperationalModeNormal
{
// Challenge by payment
nullSettlementDisputeByPayment.challengeByPayment(wallet, payment, msg.sender);
// Emit event
emit ChallengeByPaymentEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, payment.currency),
nullSettlementChallengeState.proposalStageAmount(wallet, payment.currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, payment.currency),
payment.currency.ct, payment.currency.id, msg.sender
);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _startChallenge(address wallet, int256 stageAmount, MonetaryTypesLib.Currency memory currency,
bool walletInitiated)
private
{
// Require that current block number is beyond the earliest settlement challenge block number
require(
block.number >= configuration.earliestSettlementBlockNumber(),
"Current block number below earliest settlement block number [NullSettlementChallengeByPayment.sol:443]"
);
// Require that there is no ongoing overlapping null settlement challenge
require(
!nullSettlementChallengeState.hasProposal(wallet, currency) ||
nullSettlementChallengeState.hasProposalExpired(wallet, currency),
"Overlapping null settlement challenge proposal found [NullSettlementChallengeByPayment.sol:449]"
);
// Get the last logged active balance amount and block number, properties of overlapping DSC
// and the baseline nonce
(
int256 activeBalanceAmount, uint256 activeBalanceBlockNumber,
int256 dscCumulativeTransferAmount, int256 dscStageAmount,
uint256 nonce
) = _externalProperties(
wallet, currency
);
// Initiate proposal, including assurance that there is no overlap with active proposal
// Target balance amount is calculated as current balance - DSC cumulativeTransferAmount - DSC stage amount - NSC stageAmount
nullSettlementChallengeState.initiateProposal(
wallet, nonce, stageAmount,
activeBalanceAmount.sub(
dscCumulativeTransferAmount.add(dscStageAmount).add(stageAmount)
),
currency,
activeBalanceBlockNumber, walletInitiated
);
}
function _stopChallenge(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
private
{
// Require that there is an unterminated driip settlement challenge proposal
require(nullSettlementChallengeState.hasProposal(wallet, currency), "No proposal found [NullSettlementChallengeByPayment.sol:481]");
require(!nullSettlementChallengeState.hasProposalTerminated(wallet, currency), "Proposal found terminated [NullSettlementChallengeByPayment.sol:482]");
// Terminate driip settlement challenge proposal
nullSettlementChallengeState.terminateProposal(
wallet, currency, walletTerminated
);
}
function _externalProperties(address wallet, MonetaryTypesLib.Currency memory currency)
private
view
returns (
int256 activeBalanceAmount, uint256 activeBalanceBlockNumber,
int256 dscCumulativeTransferAmount, int256 dscStageAmount,
uint256 nonce
) {
(activeBalanceAmount, activeBalanceBlockNumber) = balanceTracker.fungibleActiveRecord(
wallet, currency
);
if (driipSettlementChallengeState.hasProposal(wallet, currency)) {
if (!driipSettlementChallengeState.hasProposalTerminated(wallet, currency)) {
dscCumulativeTransferAmount = driipSettlementChallengeState.proposalCumulativeTransferAmount(wallet, currency);
dscStageAmount = driipSettlementChallengeState.proposalStageAmount(wallet, currency);
}
nonce = driipSettlementChallengeState.proposalNonce(wallet, currency);
}
if (nullSettlementChallengeState.hasProposal(wallet, currency))
nonce = nonce.clampMin(nullSettlementChallengeState.proposalNonce(wallet, currency));
}
}
|
Start settlement challenge for the given wallet wallet The address of the concerned wallet amount The concerned amount to stage currencyCt The address of the concerned currency contract (address(0) == ETH) currencyId The ID of the concerned currency (0 for ETH and ERC20) Define currency Start challenge for wallet Emit event
|
function startChallengeByProxy(address wallet, int256 amount, address currencyCt, uint256 currencyId)
public
onlyOperator
{
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
_startChallenge(wallet, amount, currency, false);
emit StartChallengeByProxyEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, currency),
amount,
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, currency),
currencyCt, currencyId, msg.sender
);
}
| 12,574,784
|
// File: contracts/interfaces/IBridgeValidators.sol
pragma solidity 0.4.24;
interface IBridgeValidators {
function isValidator(address _validator) external view returns (bool);
function requiredSignatures() external view returns (uint256);
function owner() external view returns (address);
}
// File: contracts/libraries/Message.sol
pragma solidity 0.4.24;
library Message {
function addressArrayContains(address[] array, address value) internal pure returns (bool) {
for (uint256 i = 0; i < array.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
// layout of message :: bytes:
// offset 0: 32 bytes :: uint256 - message length
// offset 32: 20 bytes :: address - recipient address
// offset 52: 32 bytes :: uint256 - value
// offset 84: 32 bytes :: bytes32 - transaction hash
// offset 104: 20 bytes :: address - contract address to prevent double spending
// mload always reads 32 bytes.
// so we can and have to start reading recipient at offset 20 instead of 32.
// if we were to read at 32 the address would contain part of value and be corrupted.
// when reading from offset 20 mload will read 12 bytes (most of them zeros) followed
// by the 20 recipient address bytes and correctly convert it into an address.
// this saves some storage/gas over the alternative solution
// which is padding address to 32 bytes and reading recipient at offset 32.
// for more details see discussion in:
// https://github.com/paritytech/parity-bridge/issues/61
function parseMessage(bytes message)
internal
pure
returns (address recipient, uint256 amount, bytes32 txHash, address contractAddress)
{
require(isMessageValid(message));
assembly {
recipient := mload(add(message, 20))
amount := mload(add(message, 52))
txHash := mload(add(message, 84))
contractAddress := mload(add(message, 104))
}
}
function isMessageValid(bytes _msg) internal pure returns (bool) {
return _msg.length == requiredMessageLength();
}
function requiredMessageLength() internal pure returns (uint256) {
return 104;
}
function recoverAddressFromSignedMessage(bytes signature, bytes message, bool isAMBMessage)
internal
pure
returns (address)
{
require(signature.length == 65);
bytes32 r;
bytes32 s;
bytes1 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := mload(add(signature, 0x60))
}
require(uint8(v) == 27 || uint8(v) == 28);
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0);
return ecrecover(hashMessage(message, isAMBMessage), uint8(v), r, s);
}
function hashMessage(bytes message, bool isAMBMessage) internal pure returns (bytes32) {
bytes memory prefix = "\x19Ethereum Signed Message:\n";
if (isAMBMessage) {
return keccak256(abi.encodePacked(prefix, uintToString(message.length), message));
} else {
string memory msgLength = "104";
return keccak256(abi.encodePacked(prefix, msgLength, message));
}
}
/**
* @dev Validates provided signatures, only first requiredSignatures() number
* of signatures are going to be validated, these signatures should be from different validators.
* @param _message bytes message used to generate signatures
* @param _signatures bytes blob with signatures to be validated.
* First byte X is a number of signatures in a blob,
* next X bytes are v components of signatures,
* next 32 * X bytes are r components of signatures,
* next 32 * X bytes are s components of signatures.
* @param _validatorContract contract, which conforms to the IBridgeValidators interface,
* where info about current validators and required signatures is stored.
* @param isAMBMessage true if _message is an AMB message with arbitrary length.
*/
function hasEnoughValidSignatures(
bytes _message,
bytes _signatures,
IBridgeValidators _validatorContract,
bool isAMBMessage
) internal view {
require(isAMBMessage || isMessageValid(_message));
uint256 requiredSignatures = _validatorContract.requiredSignatures();
uint256 amount;
assembly {
amount := and(mload(add(_signatures, 1)), 0xff)
}
require(amount >= requiredSignatures);
bytes32 hash = hashMessage(_message, isAMBMessage);
address[] memory encounteredAddresses = new address[](requiredSignatures);
for (uint256 i = 0; i < requiredSignatures; i++) {
uint8 v;
bytes32 r;
bytes32 s;
uint256 posr = 33 + amount + 32 * i;
uint256 poss = posr + 32 * amount;
assembly {
v := mload(add(_signatures, add(2, i)))
r := mload(add(_signatures, posr))
s := mload(add(_signatures, poss))
}
address recoveredAddress = ecrecover(hash, v, r, s);
require(_validatorContract.isValidator(recoveredAddress));
require(!addressArrayContains(encounteredAddresses, recoveredAddress));
encounteredAddresses[i] = recoveredAddress;
}
}
function uintToString(uint256 i) internal pure returns (string) {
if (i == 0) return "0";
uint256 j = i;
uint256 length;
while (j != 0) {
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint256 k = length - 1;
while (i != 0) {
bstr[k--] = bytes1(48 + (i % 10));
i /= 10;
}
return string(bstr);
}
}
// File: contracts/libraries/ArbitraryMessage.sol
pragma solidity 0.4.24;
library ArbitraryMessage {
/**
* @dev Unpacks data fields from AMB message
* layout of message :: bytes:
* offset 0 : 32 bytes :: uint256 - message length
* offset 32 : 32 bytes :: bytes32 - messageId
* offset 64 : 20 bytes :: address - sender address
* offset 84 : 20 bytes :: address - executor contract
* offset 104 : 4 bytes :: uint32 - gasLimit
* offset 108 : 1 bytes :: uint8 - source chain id length (X)
* offset 109 : 1 bytes :: uint8 - destination chain id length (Y)
* offset 110 : 1 bytes :: uint8 - dataType
* offset 111 : X bytes :: bytes - source chain id
* offset 111 + X : Y bytes :: bytes - destination chain id
* NOTE: when message structure is changed, make sure that MESSAGE_PACKING_VERSION from VersionableAMB is updated as well
* NOTE: assembly code uses calldatacopy, make sure that message is passed as the first argument in the calldata
* @param _data encoded message
*/
function unpackData(bytes _data)
internal
pure
returns (
bytes32 messageId,
address sender,
address executor,
uint32 gasLimit,
uint8 dataType,
uint256[2] chainIds,
bytes memory data
)
{
// 32 (message id) + 20 (sender) + 20 (executor) + 4 (gasLimit) + 1 (source chain id length) + 1 (destination chain id length) + 1 (dataType)
uint256 srcdataptr = 32 + 20 + 20 + 4 + 1 + 1 + 1;
uint256 datasize;
assembly {
messageId := mload(add(_data, 32)) // 32 bytes
sender := and(mload(add(_data, 52)), 0xffffffffffffffffffffffffffffffffffffffff) // 20 bytes
// executor (20 bytes) + gasLimit (4 bytes) + srcChainIdLength (1 byte) + dstChainIdLength (1 bytes) + dataType (1 byte) + remainder (5 bytes)
let blob := mload(add(_data, 84))
// after bit shift left 12 bytes are zeros automatically
executor := shr(96, blob)
gasLimit := and(shr(64, blob), 0xffffffff)
dataType := byte(26, blob)
if gt(dataType, 0) {
// for now, only 0 datatype is supported - regular AMB calls
// other dataType values are kept reserved for future use
revert(0, 0)
}
// load source chain id length
let chainIdLength := byte(24, blob)
// at this moment srcdataptr points to sourceChainId
// mask for sourceChainId
// e.g. length X -> (1 << (X * 8)) - 1
let mask := sub(shl(shl(3, chainIdLength), 1), 1)
// increase payload offset by length of source chain id
srcdataptr := add(srcdataptr, chainIdLength)
// write sourceChainId
mstore(chainIds, and(mload(add(_data, srcdataptr)), mask))
// at this moment srcdataptr points to destinationChainId
// load destination chain id length
chainIdLength := byte(25, blob)
// mask for destinationChainId
// e.g. length X -> (1 << (X * 8)) - 1
mask := sub(shl(shl(3, chainIdLength), 1), 1)
// increase payload offset by length of destination chain id
srcdataptr := add(srcdataptr, chainIdLength)
// write destinationChainId
mstore(add(chainIds, 32), and(mload(add(_data, srcdataptr)), mask))
// at this moment srcdataptr points to payload
// datasize = message length - payload offset
datasize := sub(mload(_data), srcdataptr)
}
data = new bytes(datasize);
assembly {
// 36 = 4 (selector) + 32 (bytes length header)
srcdataptr := add(srcdataptr, 36)
// calldataload(4) - offset of first bytes argument in the calldata
calldatacopy(add(data, 32), add(calldataload(4), srcdataptr), datasize)
}
}
}
// File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol
pragma solidity 0.4.24;
interface IUpgradeabilityOwnerStorage {
function upgradeabilityOwner() external view returns (address);
}
// File: contracts/upgradeable_contracts/Upgradeable.sol
pragma solidity 0.4.24;
contract Upgradeable {
// Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract
modifier onlyIfUpgradeabilityOwner() {
require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner());
/* solcov ignore next */
_;
}
}
// File: contracts/upgradeability/EternalStorage.sol
pragma solidity 0.4.24;
/**
* @title EternalStorage
* @dev This contract holds all the necessary state variables to carry out the storage of any contract.
*/
contract EternalStorage {
mapping(bytes32 => uint256) internal uintStorage;
mapping(bytes32 => string) internal stringStorage;
mapping(bytes32 => address) internal addressStorage;
mapping(bytes32 => bytes) internal bytesStorage;
mapping(bytes32 => bool) internal boolStorage;
mapping(bytes32 => int256) internal intStorage;
}
// File: contracts/upgradeable_contracts/Initializable.sol
pragma solidity 0.4.24;
contract Initializable is EternalStorage {
bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized"))
function setInitialize() internal {
boolStorage[INITIALIZED] = true;
}
function isInitialized() public view returns (bool) {
return boolStorage[INITIALIZED];
}
}
// File: contracts/upgradeable_contracts/InitializableBridge.sol
pragma solidity 0.4.24;
contract InitializableBridge is Initializable {
bytes32 internal constant DEPLOYED_AT_BLOCK = 0xb120ceec05576ad0c710bc6e85f1768535e27554458f05dcbb5c65b8c7a749b0; // keccak256(abi.encodePacked("deployedAtBlock"))
function deployedAtBlock() external view returns (uint256) {
return uintStorage[DEPLOYED_AT_BLOCK];
}
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
pragma solidity ^0.4.24;
/**
* 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/upgradeable_contracts/ValidatorStorage.sol
pragma solidity 0.4.24;
contract ValidatorStorage {
bytes32 internal constant VALIDATOR_CONTRACT = 0x5a74bb7e202fb8e4bf311841c7d64ec19df195fee77d7e7ae749b27921b6ddfe; // keccak256(abi.encodePacked("validatorContract"))
}
// File: contracts/upgradeable_contracts/Validatable.sol
pragma solidity 0.4.24;
contract Validatable is EternalStorage, ValidatorStorage {
function validatorContract() public view returns (IBridgeValidators) {
return IBridgeValidators(addressStorage[VALIDATOR_CONTRACT]);
}
modifier onlyValidator() {
require(validatorContract().isValidator(msg.sender));
/* solcov ignore next */
_;
}
function requiredSignatures() public view returns (uint256) {
return validatorContract().requiredSignatures();
}
}
// File: contracts/upgradeable_contracts/Ownable.sol
pragma solidity 0.4.24;
/**
* @title Ownable
* @dev This contract has an owner address providing basic authorization control
*/
contract Ownable is EternalStorage {
bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner()
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event OwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner());
/* solcov ignore next */
_;
}
/**
* @dev Throws if called by any account other than contract itself or owner.
*/
modifier onlyRelevantSender() {
// proxy owner if used through proxy, address(0) otherwise
require(
!address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy
msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls
msg.sender == address(this) // covers calls through upgradeAndCall proxy method
);
/* solcov ignore next */
_;
}
bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner"))
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function owner() public view returns (address) {
return addressStorage[OWNER];
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner the address to transfer ownership to.
*/
function transferOwnership(address newOwner) external onlyOwner {
_setOwner(newOwner);
}
/**
* @dev Sets a new owner address
*/
function _setOwner(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(owner(), newOwner);
addressStorage[OWNER] = newOwner;
}
}
// File: contracts/upgradeable_contracts/Sacrifice.sol
pragma solidity 0.4.24;
contract Sacrifice {
constructor(address _recipient) public payable {
selfdestruct(_recipient);
}
}
// File: contracts/libraries/Address.sol
pragma solidity 0.4.24;
/**
* @title Address
* @dev Helper methods for Address type.
*/
library Address {
/**
* @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract
* @param _receiver address that will receive the native tokens
* @param _value the amount of native tokens to send
*/
function safeSendValue(address _receiver, uint256 _value) internal {
if (!_receiver.send(_value)) {
(new Sacrifice).value(_value)(_receiver);
}
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: contracts/interfaces/ERC677.sol
pragma solidity 0.4.24;
contract ERC677 is ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
function transferAndCall(address, uint256, bytes) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) public returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool);
}
contract LegacyERC20 {
function transfer(address _spender, uint256 _value) public; // returns (bool);
function transferFrom(address _owner, address _spender, uint256 _value) public; // returns (bool);
}
// File: contracts/libraries/SafeERC20.sol
pragma solidity 0.4.24;
/**
* @title SafeERC20
* @dev Helper methods for safe token transfers.
* Functions perform additional checks to be sure that token transfer really happened.
*/
library SafeERC20 {
using SafeMath for uint256;
/**
* @dev Same as ERC20.transfer(address,uint256) but with extra consistency checks.
* @param _token address of the token contract
* @param _to address of the receiver
* @param _value amount of tokens to send
*/
function safeTransfer(address _token, address _to, uint256 _value) internal {
LegacyERC20(_token).transfer(_to, _value);
assembly {
if returndatasize {
returndatacopy(0, 0, 32)
if iszero(mload(0)) {
revert(0, 0)
}
}
}
}
/**
* @dev Same as ERC20.transferFrom(address,address,uint256) but with extra consistency checks.
* @param _token address of the token contract
* @param _from address of the sender
* @param _value amount of tokens to send
*/
function safeTransferFrom(address _token, address _from, uint256 _value) internal {
LegacyERC20(_token).transferFrom(_from, address(this), _value);
assembly {
if returndatasize {
returndatacopy(0, 0, 32)
if iszero(mload(0)) {
revert(0, 0)
}
}
}
}
}
// File: contracts/upgradeable_contracts/Claimable.sol
pragma solidity 0.4.24;
/**
* @title Claimable
* @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations.
*/
contract Claimable {
using SafeERC20 for address;
/**
* Throws if a given address is equal to address(0)
*/
modifier validAddress(address _to) {
require(_to != address(0));
/* solcov ignore next */
_;
}
/**
* @dev Withdraws the erc20 tokens or native coins from this contract.
* Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()).
* @param _token address of the claimed token or address(0) for native coins.
* @param _to address of the tokens/coins receiver.
*/
function claimValues(address _token, address _to) internal validAddress(_to) {
if (_token == address(0)) {
claimNativeCoins(_to);
} else {
claimErc20Tokens(_token, _to);
}
}
/**
* @dev Internal function for withdrawing all native coins from the contract.
* @param _to address of the coins receiver.
*/
function claimNativeCoins(address _to) internal {
uint256 value = address(this).balance;
Address.safeSendValue(_to, value);
}
/**
* @dev Internal function for withdrawing all tokens of ssome particular ERC20 contract from this contract.
* @param _token address of the claimed ERC20 token.
* @param _to address of the tokens receiver.
*/
function claimErc20Tokens(address _token, address _to) internal {
ERC20Basic token = ERC20Basic(_token);
uint256 balance = token.balanceOf(this);
_token.safeTransfer(_to, balance);
}
}
// File: contracts/upgradeable_contracts/VersionableBridge.sol
pragma solidity 0.4.24;
contract VersionableBridge {
function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) {
return (5, 2, 0);
}
/* solcov ignore next */
function getBridgeMode() external pure returns (bytes4);
}
// File: contracts/upgradeable_contracts/DecimalShiftBridge.sol
pragma solidity 0.4.24;
contract DecimalShiftBridge is EternalStorage {
using SafeMath for uint256;
bytes32 internal constant DECIMAL_SHIFT = 0x1e8ecaafaddea96ed9ac6d2642dcdfe1bebe58a930b1085842d8fc122b371ee5; // keccak256(abi.encodePacked("decimalShift"))
/**
* @dev Internal function for setting the decimal shift for bridge operations.
* Decimal shift can be positive, negative, or equal to zero.
* It has the following meaning: N tokens in the foreign chain are equivalent to N * pow(10, shift) tokens on the home side.
* @param _shift new value of decimal shift.
*/
function _setDecimalShift(int256 _shift) internal {
// since 1 wei * 10**77 > 2**255, it does not make any sense to use higher values
require(_shift > -77 && _shift < 77);
uintStorage[DECIMAL_SHIFT] = uint256(_shift);
}
/**
* @dev Returns the value of foreign-to-home decimal shift.
* @return decimal shift.
*/
function decimalShift() public view returns (int256) {
return int256(uintStorage[DECIMAL_SHIFT]);
}
/**
* @dev Converts the amount of home tokens into the equivalent amount of foreign tokens.
* @param _value amount of home tokens.
* @return equivalent amount of foreign tokens.
*/
function _unshiftValue(uint256 _value) internal view returns (uint256) {
return _shiftUint(_value, -decimalShift());
}
/**
* @dev Converts the amount of foreign tokens into the equivalent amount of home tokens.
* @param _value amount of foreign tokens.
* @return equivalent amount of home tokens.
*/
function _shiftValue(uint256 _value) internal view returns (uint256) {
return _shiftUint(_value, decimalShift());
}
/**
* @dev Calculates _value * pow(10, _shift).
* @param _value amount of tokens.
* @param _shift decimal shift to apply.
* @return shifted value.
*/
function _shiftUint(uint256 _value, int256 _shift) private pure returns (uint256) {
if (_shift == 0) {
return _value;
}
if (_shift > 0) {
return _value.mul(10**uint256(_shift));
}
return _value.div(10**uint256(-_shift));
}
}
// File: contracts/upgradeable_contracts/BasicBridge.sol
pragma solidity 0.4.24;
contract BasicBridge is
InitializableBridge,
Validatable,
Ownable,
Upgradeable,
Claimable,
VersionableBridge,
DecimalShiftBridge
{
event GasPriceChanged(uint256 gasPrice);
event RequiredBlockConfirmationChanged(uint256 requiredBlockConfirmations);
bytes32 internal constant GAS_PRICE = 0x55b3774520b5993024893d303890baa4e84b1244a43c60034d1ced2d3cf2b04b; // keccak256(abi.encodePacked("gasPrice"))
bytes32 internal constant REQUIRED_BLOCK_CONFIRMATIONS = 0x916daedf6915000ff68ced2f0b6773fe6f2582237f92c3c95bb4d79407230071; // keccak256(abi.encodePacked("requiredBlockConfirmations"))
/**
* @dev Public setter for fallback gas price value. Only bridge owner can call this method.
* @param _gasPrice new value for the gas price.
*/
function setGasPrice(uint256 _gasPrice) external onlyOwner {
_setGasPrice(_gasPrice);
}
function gasPrice() external view returns (uint256) {
return uintStorage[GAS_PRICE];
}
function setRequiredBlockConfirmations(uint256 _blockConfirmations) external onlyOwner {
_setRequiredBlockConfirmations(_blockConfirmations);
}
function _setRequiredBlockConfirmations(uint256 _blockConfirmations) internal {
require(_blockConfirmations > 0);
uintStorage[REQUIRED_BLOCK_CONFIRMATIONS] = _blockConfirmations;
emit RequiredBlockConfirmationChanged(_blockConfirmations);
}
function requiredBlockConfirmations() external view returns (uint256) {
return uintStorage[REQUIRED_BLOCK_CONFIRMATIONS];
}
/**
* @dev Internal function for updating fallback gas price value.
* @param _gasPrice new value for the gas price, zero gas price is allowed.
*/
function _setGasPrice(uint256 _gasPrice) internal {
uintStorage[GAS_PRICE] = _gasPrice;
emit GasPriceChanged(_gasPrice);
}
}
// File: contracts/upgradeable_contracts/arbitrary_message/VersionableAMB.sol
pragma solidity 0.4.24;
contract VersionableAMB is VersionableBridge {
// message format version as a single 4-bytes number padded to 32-bytes
// value, included into every outgoing relay request
//
// the message version should be updated every time when
// - new field appears
// - some field removed
// - fields order is changed
bytes32 internal constant MESSAGE_PACKING_VERSION = 0x00050000 << 224;
/**
* Returns currently used bridge version
* @return (major, minor, patch) version triple
*/
function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) {
return (5, 4, 0);
}
}
// File: contracts/upgradeable_contracts/arbitrary_message/BasicAMB.sol
pragma solidity 0.4.24;
contract BasicAMB is BasicBridge, VersionableAMB {
bytes32 internal constant MAX_GAS_PER_TX = 0x2670ecc91ec356e32067fd27b36614132d727b84a1e03e08f412a4f2cf075974; // keccak256(abi.encodePacked("maxGasPerTx"))
bytes32 internal constant NONCE = 0x7ab1577440dd7bedf920cb6de2f9fc6bf7ba98c78c85a3fa1f8311aac95e1759; // keccak256(abi.encodePacked("nonce"))
bytes32 internal constant SOURCE_CHAIN_ID = 0x67d6f42a1ed69c62022f2d160ddc6f2f0acd37ad1db0c24f4702d7d3343a4add; // keccak256(abi.encodePacked("sourceChainId"))
bytes32 internal constant SOURCE_CHAIN_ID_LENGTH = 0xe504ae1fd6471eea80f18b8532a61a9bb91fba4f5b837f80a1cfb6752350af44; // keccak256(abi.encodePacked("sourceChainIdLength"))
bytes32 internal constant DESTINATION_CHAIN_ID = 0xbbd454018e72a3f6c02bbd785bacc49e46292744f3f6761276723823aa332320; // keccak256(abi.encodePacked("destinationChainId"))
bytes32 internal constant DESTINATION_CHAIN_ID_LENGTH = 0xfb792ae4ad11102b93f26a51b3749c2b3667f8b561566a4806d4989692811594; // keccak256(abi.encodePacked("destinationChainIdLength"))
/**
* Initializes AMB contract
* @param _sourceChainId chain id of a network where this contract is deployed
* @param _destinationChainId chain id of a network where all outgoing messages are directed
* @param _validatorContract address of the validators contract
* @param _maxGasPerTx maximum amount of gas per one message execution
* @param _gasPrice default gas price used by oracles for sending transactions in this network
* @param _requiredBlockConfirmations number of block confirmations oracle will wait before processing passed messages
* @param _owner address of new bridge owner
*/
function initialize(
uint256 _sourceChainId,
uint256 _destinationChainId,
address _validatorContract,
uint256 _maxGasPerTx,
uint256 _gasPrice,
uint256 _requiredBlockConfirmations,
address _owner
) external onlyRelevantSender returns (bool) {
require(!isInitialized());
require(AddressUtils.isContract(_validatorContract));
_setChainIds(_sourceChainId, _destinationChainId);
addressStorage[VALIDATOR_CONTRACT] = _validatorContract;
uintStorage[DEPLOYED_AT_BLOCK] = block.number;
uintStorage[MAX_GAS_PER_TX] = _maxGasPerTx;
_setGasPrice(_gasPrice);
_setRequiredBlockConfirmations(_requiredBlockConfirmations);
_setOwner(_owner);
setInitialize();
return isInitialized();
}
function getBridgeMode() external pure returns (bytes4 _data) {
return 0x2544fbb9; // bytes4(keccak256(abi.encodePacked("arbitrary-message-bridge-core")))
}
function maxGasPerTx() public view returns (uint256) {
return uintStorage[MAX_GAS_PER_TX];
}
function setMaxGasPerTx(uint256 _maxGasPerTx) external onlyOwner {
uintStorage[MAX_GAS_PER_TX] = _maxGasPerTx;
}
/**
* Internal function for retrieving chain id for the source network
* @return chain id for the current network
*/
function sourceChainId() public view returns (uint256) {
return uintStorage[SOURCE_CHAIN_ID];
}
/**
* Internal function for retrieving chain id for the destination network
* @return chain id for the destination network
*/
function destinationChainId() public view returns (uint256) {
return uintStorage[DESTINATION_CHAIN_ID];
}
/**
* Updates chain ids of used networks
* @param _sourceChainId chain id for current network
* @param _destinationChainId chain id for opposite network
*/
function setChainIds(uint256 _sourceChainId, uint256 _destinationChainId) external onlyOwner {
_setChainIds(_sourceChainId, _destinationChainId);
}
/**
* Internal function for retrieving current nonce value
* @return nonce value
*/
function _nonce() internal view returns (uint64) {
return uint64(uintStorage[NONCE]);
}
/**
* Internal function for updating nonce value
* @param _nonce new nonce value
*/
function _setNonce(uint64 _nonce) internal {
uintStorage[NONCE] = uint256(_nonce);
}
/**
* Internal function for updating chain ids of used networks
* @param _sourceChainId chain id for current network
* @param _destinationChainId chain id for opposite network
*/
function _setChainIds(uint256 _sourceChainId, uint256 _destinationChainId) internal {
require(_sourceChainId > 0 && _destinationChainId > 0);
require(_sourceChainId != _destinationChainId);
// Length fields are needed further when encoding the message.
// Chain ids are compressed, so that leading zero bytes are not preserved.
// In order to save some gas during calls to MessageDelivery.c,
// lengths of chain ids are precalculated and being saved in the storage.
uint256 sourceChainIdLength = 0;
uint256 destinationChainIdLength = 0;
uint256 mask = 0xff;
for (uint256 i = 1; sourceChainIdLength == 0 || destinationChainIdLength == 0; i++) {
if (sourceChainIdLength == 0 && _sourceChainId & mask == _sourceChainId) {
sourceChainIdLength = i;
}
if (destinationChainIdLength == 0 && _destinationChainId & mask == _destinationChainId) {
destinationChainIdLength = i;
}
mask = (mask << 8) | 0xff;
}
uintStorage[SOURCE_CHAIN_ID] = _sourceChainId;
uintStorage[SOURCE_CHAIN_ID_LENGTH] = sourceChainIdLength;
uintStorage[DESTINATION_CHAIN_ID] = _destinationChainId;
uintStorage[DESTINATION_CHAIN_ID_LENGTH] = destinationChainIdLength;
}
/**
* Internal function for retrieving chain id length for the source network
* @return chain id for the current network
*/
function _sourceChainIdLength() internal view returns (uint256) {
return uintStorage[SOURCE_CHAIN_ID_LENGTH];
}
/**
* Internal function for retrieving chain id length for the destination network
* @return chain id for the destination network
*/
function _destinationChainIdLength() internal view returns (uint256) {
return uintStorage[DESTINATION_CHAIN_ID_LENGTH];
}
/**
* Internal function for validating version of the received message
* @param _messageId id of the received message
*/
function _isMessageVersionValid(bytes32 _messageId) internal returns (bool) {
return
_messageId & 0xffffffff00000000000000000000000000000000000000000000000000000000 == MESSAGE_PACKING_VERSION;
}
/**
* Internal function for validating destination chain id of the received message
* @param _chainId destination chain id of the received message
*/
function _isDestinationChainIdValid(uint256 _chainId) internal returns (bool res) {
return _chainId == sourceChainId();
}
}
// File: contracts/libraries/Bytes.sol
pragma solidity 0.4.24;
/**
* @title Bytes
* @dev Helper methods to transform bytes to other solidity types.
*/
library Bytes {
/**
* @dev Converts bytes array to bytes32.
* Truncates bytes array if its size is more than 32 bytes.
* NOTE: This function does not perform any checks on the received parameter.
* Make sure that the _bytes argument has a correct length, not less than 32 bytes.
* A case when _bytes has length less than 32 will lead to the undefined behaviour,
* since assembly will read data from memory that is not related to the _bytes argument.
* @param _bytes to be converted to bytes32 type
* @return bytes32 type of the firsts 32 bytes array in parameter.
*/
function bytesToBytes32(bytes _bytes) internal pure returns (bytes32 result) {
assembly {
result := mload(add(_bytes, 32))
}
}
/**
* @dev Truncate bytes array if its size is more than 20 bytes.
* NOTE: Similar to the bytesToBytes32 function, make sure that _bytes is not shorter than 20 bytes.
* @param _bytes to be converted to address type
* @return address included in the firsts 20 bytes of the bytes array in parameter.
*/
function bytesToAddress(bytes _bytes) internal pure returns (address addr) {
assembly {
addr := mload(add(_bytes, 20))
}
}
}
// File: contracts/upgradeable_contracts/arbitrary_message/MessageProcessor.sol
pragma solidity 0.4.24;
contract MessageProcessor is EternalStorage {
bytes32 internal constant MESSAGE_SENDER = 0x7b58b2a669d8e0992eae9eaef641092c0f686fd31070e7236865557fa1571b5b; // keccak256(abi.encodePacked("messageSender"))
bytes32 internal constant MESSAGE_ID = 0xe34bb2103dc34f2c144cc216c132d6ffb55dac57575c22e089161bbe65083304; // keccak256(abi.encodePacked("messageId"))
bytes32 internal constant MESSAGE_SOURCE_CHAIN_ID = 0x7f0fcd9e49860f055dd0c1682d635d309ecb5e3011654c716d9eb59a7ddec7d2; // keccak256(abi.encodePacked("messageSourceChainId"))
/**
* @dev Returns a status of the message that came from the other side.
* @param _messageId id of the message from the other side that triggered a call.
* @return true if call executed successfully.
*/
function messageCallStatus(bytes32 _messageId) external view returns (bool) {
return boolStorage[keccak256(abi.encodePacked("messageCallStatus", _messageId))];
}
/**
* @dev Sets a status of the message that came from the other side.
* @param _messageId id of the message from the other side that triggered a call.
* @param _status execution status, true if executed successfully.
*/
function setMessageCallStatus(bytes32 _messageId, bool _status) internal {
boolStorage[keccak256(abi.encodePacked("messageCallStatus", _messageId))] = _status;
}
/**
* @dev Returns a data hash of the failed message that came from the other side.
* NOTE: dataHash was used previously to identify outgoing message before AMB message id was introduced.
* It is kept for backwards compatibility with old mediators contracts.
* @param _messageId id of the message from the other side that triggered a call.
* @return keccak256 hash of message data.
*/
function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32) {
return bytes32(uintStorage[keccak256(abi.encodePacked("failedMessageDataHash", _messageId))]);
}
/**
* @dev Sets a data hash of the failed message that came from the other side.
* NOTE: dataHash was used previously to identify outgoing message before AMB message id was introduced.
* It is kept for backwards compatibility with old mediators contracts.
* @param _messageId id of the message from the other side that triggered a call.
* @param data of the processed message.
*/
function setFailedMessageDataHash(bytes32 _messageId, bytes data) internal {
uintStorage[keccak256(abi.encodePacked("failedMessageDataHash", _messageId))] = uint256(keccak256(data));
}
/**
* @dev Returns a receiver address of the failed message that came from the other side.
* @param _messageId id of the message from the other side that triggered a call.
* @return receiver address.
*/
function failedMessageReceiver(bytes32 _messageId) external view returns (address) {
return addressStorage[keccak256(abi.encodePacked("failedMessageReceiver", _messageId))];
}
/**
* @dev Sets a sender address of the failed message that came from the other side.
* @param _messageId id of the message from the other side that triggered a call.
* @param _receiver address of the receiver.
*/
function setFailedMessageReceiver(bytes32 _messageId, address _receiver) internal {
addressStorage[keccak256(abi.encodePacked("failedMessageReceiver", _messageId))] = _receiver;
}
/**
* @dev Returns a sender address of the failed message that came from the other side.
* @param _messageId id of the message from the other side that triggered a call.
* @return sender address on the other side.
*/
function failedMessageSender(bytes32 _messageId) external view returns (address) {
return addressStorage[keccak256(abi.encodePacked("failedMessageSender", _messageId))];
}
/**
* @dev Sets a sender address of the failed message that came from the other side.
* @param _messageId id of the message from the other side that triggered a call.
* @param _sender address of the sender on the other side.
*/
function setFailedMessageSender(bytes32 _messageId, address _sender) internal {
addressStorage[keccak256(abi.encodePacked("failedMessageSender", _messageId))] = _sender;
}
/**
* @dev Returns an address of the sender on the other side for the currently processed message.
* Can be used by executors for getting other side caller address.
* @return address of the sender on the other side.
*/
function messageSender() external view returns (address) {
return addressStorage[MESSAGE_SENDER];
}
/**
* @dev Sets an address of the sender on the other side for the currently processed message.
* @param _sender address of the sender on the other side.
*/
function setMessageSender(address _sender) internal {
addressStorage[MESSAGE_SENDER] = _sender;
}
/**
* @dev Returns an id of the currently processed message.
* @return id of the message that originated on the other side.
*/
function messageId() public view returns (bytes32) {
return bytes32(uintStorage[MESSAGE_ID]);
}
/**
* @dev Returns an id of the currently processed message.
* NOTE: transactionHash was used previously to identify incoming message before AMB message id was introduced.
* It is kept for backwards compatibility with old mediators contracts, although it doesn't return txHash anymore.
* @return id of the message that originated on the other side.
*/
function transactionHash() external view returns (bytes32) {
return messageId();
}
/**
* @dev Sets a message id of the currently processed message.
* @param _messageId id of the message that originated on the other side.
*/
function setMessageId(bytes32 _messageId) internal {
uintStorage[MESSAGE_ID] = uint256(_messageId);
}
/**
* @dev Returns an originating chain id of the currently processed message.
* @return source chain id of the message that originated on the other side.
*/
function messageSourceChainId() external view returns (uint256) {
return uintStorage[MESSAGE_SOURCE_CHAIN_ID];
}
/**
* @dev Returns an originating chain id of the currently processed message.
* @return source chain id of the message that originated on the other side.
*/
function setMessageSourceChainId(uint256 _sourceChainId) internal returns (uint256) {
uintStorage[MESSAGE_SOURCE_CHAIN_ID] = _sourceChainId;
}
/**
* @dev Processes received message. Makes a call to the message executor,
* sets dataHash, receive, sender variables for failed messages.
* @param _sender sender address on the other side.
* @param _executor address of an executor.
* @param _messageId id of the processed message.
* @param _gasLimit gas limit for a call to executor.
* @param _sourceChainId source chain id is of the received message.
* @param _data calldata for a call to executor.
*/
function processMessage(
address _sender,
address _executor,
bytes32 _messageId,
uint256 _gasLimit,
uint8, /* dataType */
uint256 _sourceChainId,
bytes memory _data
) internal {
bool status = _passMessage(_sender, _executor, _data, _gasLimit, _messageId, _sourceChainId);
setMessageCallStatus(_messageId, status);
if (!status) {
setFailedMessageDataHash(_messageId, _data);
setFailedMessageReceiver(_messageId, _executor);
setFailedMessageSender(_messageId, _sender);
}
emitEventOnMessageProcessed(_sender, _executor, _messageId, status);
}
/**
* @dev Makes a call to the message executor.
* @param _sender sender address on the other side.
* @param _contract address of an executor contract.
* @param _data calldata for a call to executor.
* @param _gas gas limit for a call to executor.
* @param _messageId id of the processed message.
* @param _sourceChainId source chain id is of the received message.
*/
function _passMessage(
address _sender,
address _contract,
bytes _data,
uint256 _gas,
bytes32 _messageId,
uint256 _sourceChainId
) internal returns (bool) {
setMessageSender(_sender);
setMessageId(_messageId);
setMessageSourceChainId(_sourceChainId);
// After EIP-150, max gas cost allowed to be passed to the internal call is equal to the 63/64 of total gas left.
// In reallity, min(gasLimit, 63/64 * gasleft()) will be used as the call gas limit.
// Imagine a situation, when message requires 10000000 gas to be executed successfully.
// Also suppose, that at this point, gasleft() is equal to 10158000, so the callee will receive ~ 10158000 * 63 / 64 = 9999300 gas.
// That amount of gas is not enough, so the call will fail. At the same time,
// even if the callee failed the bridge contract still has ~ 158000 gas to
// finish its execution and it will be enough. The internal call fails but
// only because the oracle provides incorrect gas limit for the transaction
// This check is needed here in order to force contract to pass exactly the requested amount of gas.
// Avoiding it may leed to the unwanted message failure in some extreme cases.
require((gasleft() * 63) / 64 > _gas);
bool status = _contract.call.gas(_gas)(_data);
setMessageSender(address(0));
setMessageId(bytes32(0));
setMessageSourceChainId(0);
return status;
}
/* solcov ignore next */
function emitEventOnMessageProcessed(address sender, address executor, bytes32 messageId, bool status) internal;
}
// File: contracts/upgradeable_contracts/arbitrary_message/MessageDelivery.sol
pragma solidity 0.4.24;
contract MessageDelivery is BasicAMB, MessageProcessor {
using SafeMath for uint256;
uint256 internal constant SEND_TO_ORACLE_DRIVEN_LANE = 0x00;
/**
* @dev Requests message relay to the opposite network
* @param _contract executor address on the other side
* @param _data calldata passed to the executor on the other side
* @param _gas gas limit used on the other network for executing a message
*/
function requireToPassMessage(address _contract, bytes _data, uint256 _gas) public returns (bytes32) {
return _sendMessage(_contract, _data, _gas, SEND_TO_ORACLE_DRIVEN_LANE);
}
/**
* @dev Initiates sending of an AMB message to the opposite network
* @param _contract executor address on the other side
* @param _data calldata passed to the executor on the other side
* @param _gas gas limit used on the other network for executing a message
* @param _dataType AMB message dataType to be included as a part of the header
*/
function _sendMessage(address _contract, bytes _data, uint256 _gas, uint256 _dataType) public returns (bytes32) {
// it is not allowed to pass messages while other messages are processed
require(messageId() == bytes32(0));
require(_gas >= getMinimumGasUsage(_data) && _gas <= maxGasPerTx());
bytes32 _messageId;
bytes memory header = _packHeader(_contract, _gas, _dataType);
_setNonce(_nonce() + 1);
assembly {
_messageId := mload(add(header, 32))
}
bytes memory eventData = abi.encodePacked(header, _data);
emitEventOnMessageRequest(_messageId, eventData);
return _messageId;
}
/**
* @dev Returns a lower limit on gas limit for the particular message data
* @param _data calldata passed to the executor on the other side
*/
function getMinimumGasUsage(bytes _data) public pure returns (uint256 gas) {
// From Ethereum Yellow Paper
// 68 gas is paid for every non-zero byte of data or code for a transaction
// Starting from Istanbul hardfork, 16 gas is paid (EIP-2028)
return _data.length.mul(16);
}
/**
* @dev Packs message header into a single bytes blob
* @param _contract executor address on the other side
* @param _gas gas limit used on the other network for executing a message
* @param _dataType AMB message dataType to be included as a part of the header
*/
function _packHeader(address _contract, uint256 _gas, uint256 _dataType)
internal
view
returns (bytes memory header)
{
uint256 srcChainId = sourceChainId();
uint256 srcChainIdLength = _sourceChainIdLength();
uint256 dstChainId = destinationChainId();
uint256 dstChainIdLength = _destinationChainIdLength();
bytes32 mVer = MESSAGE_PACKING_VERSION;
uint256 nonce = _nonce();
// Bridge id is recalculated every time again and again, since it is still cheaper than using SLOAD opcode (800 gas)
bytes32 bridgeId = keccak256(abi.encodePacked(srcChainId, address(this))) &
0x00000000ffffffffffffffffffffffffffffffffffffffff0000000000000000;
// 79 = 4 + 20 + 8 + 20 + 20 + 4 + 1 + 1 + 1
header = new bytes(79 + srcChainIdLength + dstChainIdLength);
// In order to save the gas, the header is packed in the reverse order.
// With such approach, it is possible to store right-aligned values without any additional bit shifts.
assembly {
let ptr := add(header, mload(header)) // points to the last word of header
mstore(ptr, dstChainId)
mstore(sub(ptr, dstChainIdLength), srcChainId)
mstore(add(header, 79), _dataType)
mstore(add(header, 78), dstChainIdLength)
mstore(add(header, 77), srcChainIdLength)
mstore(add(header, 76), _gas)
mstore(add(header, 72), _contract)
mstore(add(header, 52), caller)
mstore(add(header, 32), or(mVer, or(bridgeId, nonce)))
}
}
/* solcov ignore next */
function emitEventOnMessageRequest(bytes32 messageId, bytes encodedData) internal;
}
// File: contracts/upgradeable_contracts/MessageRelay.sol
pragma solidity 0.4.24;
contract MessageRelay is EternalStorage {
function relayedMessages(bytes32 _txHash) public view returns (bool) {
return boolStorage[keccak256(abi.encodePacked("relayedMessages", _txHash))];
}
function setRelayedMessages(bytes32 _txHash, bool _status) internal {
boolStorage[keccak256(abi.encodePacked("relayedMessages", _txHash))] = _status;
}
}
// File: contracts/upgradeable_contracts/arbitrary_message/BasicForeignAMB.sol
pragma solidity 0.4.24;
contract BasicForeignAMB is BasicAMB, MessageRelay, MessageDelivery {
/**
* @dev Validates provided signatures and relays a given message
* @param _data bytes to be relayed
* @param _signatures bytes blob with signatures to be validated
*/
function executeSignatures(bytes _data, bytes _signatures) external {
Message.hasEnoughValidSignatures(_data, _signatures, validatorContract(), true);
bytes32 messageId;
address sender;
address executor;
uint32 gasLimit;
uint8 dataType;
uint256[2] memory chainIds;
bytes memory data;
(messageId, sender, executor, gasLimit, dataType, chainIds, data) = ArbitraryMessage.unpackData(_data);
require(_isMessageVersionValid(messageId));
require(_isDestinationChainIdValid(chainIds[1]));
require(!relayedMessages(messageId));
setRelayedMessages(messageId, true);
processMessage(sender, executor, messageId, gasLimit, dataType, chainIds[0], data);
}
/**
* @dev Internal function for updating fallback gas price value.
* @param _gasPrice new value for the gas price, zero gas price is not allowed.
*/
function _setGasPrice(uint256 _gasPrice) internal {
require(_gasPrice > 0);
super._setGasPrice(_gasPrice);
}
}
// File: contracts/upgradeable_contracts/arbitrary_message/ForeignAMB.sol
pragma solidity 0.4.24;
contract ForeignAMB is BasicForeignAMB {
event UserRequestForAffirmation(bytes32 indexed messageId, bytes encodedData);
event RelayedMessage(address indexed sender, address indexed executor, bytes32 indexed messageId, bool status);
function emitEventOnMessageRequest(bytes32 messageId, bytes encodedData) internal {
emit UserRequestForAffirmation(messageId, encodedData);
}
function emitEventOnMessageProcessed(address sender, address executor, bytes32 messageId, bool status) internal {
emit RelayedMessage(sender, executor, messageId, status);
}
}
|
Returns an originating chain id of the currently processed message. return source chain id of the message that originated on the other side./
|
function setMessageSourceChainId(uint256 _sourceChainId) internal returns (uint256) {
uintStorage[MESSAGE_SOURCE_CHAIN_ID] = _sourceChainId;
}
| 2,409,430
|
// SPDX-License-Identifier: MIT
pragma solidity =0.6.12;
pragma experimental ABIEncoderV2;
/*
βββββββββββββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββββββββββββββββββββββββββββββ
*
* MIT License
* ===========
*
* Copyright (c) 2020 WooTrade
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
*/
import "./libraries/InitializableOwnable.sol";
import "./libraries/DecimalMath.sol";
import "./interfaces/IOracle.sol";
import "./interfaces/IWooPP.sol";
import "./interfaces/IRewardManager.sol";
import "./interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
contract WooPP is InitializableOwnable, ReentrancyGuard {
using SafeMathEnhanced for uint256;
using DecimalMath for uint256;
using SafeERC20 for IERC20;
event StrategistUpdated(address indexed strategist, bool flag);
event RewardManagerUpdated(address indexed newRewardManager);
event PriceOracleUpdated(address indexed newPriceOracle);
event ChainlinkRefOracleUpdated(address indexed token, address indexed newChainlinkRefOracle);
event ParametersUpdated(
address indexed baseToken,
uint256 newThreshold,
uint256 newLpFeeRate,
uint256 newR
);
event Withdraw(address indexed token, address indexed to, uint256 amount);
event WooSwap(
address fromToken,
address toToken,
uint256 fromAmount,
uint256 toAmount,
address from,
address to
);
mapping(address => bool) public isStrategist;
modifier onlyStrategist() {
require(msg.sender == _OWNER_ || isStrategist[msg.sender], "NOT_STRATEGIST");
_;
}
// ============ Core Address ============
address public quoteToken;
// ============ Variables for Pricing ============
struct TokenInfo {
uint112 reserve;
uint112 threshold;
uint32 lastResetTimestamp;
uint64 lpFeeRate;
uint64 R;
uint112 target;
bool isValid;
address chainlinkRefOracle; // Reference
uint96 refPriceFixCoeff;
}
address public priceOracle; // WooOracle
mapping (address => TokenInfo) public tokenInfo;
string public pairsInfo;
address public rewardManager;
constructor(
address owner,
address _quoteToken,
address _priceOracle,
address quoteChainlinkRefOracle
) public {
init(owner, _quoteToken, _priceOracle, quoteChainlinkRefOracle);
}
function init(
address owner,
address _quoteToken,
address _priceOracle,
address quoteChainlinkRefOracle
) public {
require(owner != address(0), "INVALID_OWNER");
require(_quoteToken != address(0), "INVALID_QUOTE");
require(_priceOracle != address(0), "INVALID_ORACLE");
initOwner(owner);
quoteToken = _quoteToken;
TokenInfo storage quoteInfo = tokenInfo[quoteToken];
quoteInfo.isValid = true;
quoteInfo.chainlinkRefOracle = quoteChainlinkRefOracle;
// reference price decimals should be 36-token.decimals, else we multiply it by refPriceFixCoeff
if (quoteChainlinkRefOracle != address(0)) {
// TODO: (@qinchao) should use ERC20Detailed or IERC20 ?
uint256 decimalsToFix = uint256(ERC20(quoteToken).decimals()).add(uint256(AggregatorV3Interface(quoteChainlinkRefOracle).decimals()));
uint256 refPriceFixCoeff = 10**(uint256(36).sub(decimalsToFix));
require(refPriceFixCoeff <= type(uint96).max);
quoteInfo.refPriceFixCoeff = uint96(refPriceFixCoeff);
}
priceOracle = _priceOracle;
emit ChainlinkRefOracleUpdated(quoteToken, quoteChainlinkRefOracle);
}
function getPairInfo() external view returns (string memory) {
return pairsInfo;
}
function setPairsInfo(string calldata _pairsInfo) external onlyStrategist {
pairsInfo = _pairsInfo;
}
function autoUpdate(address baseToken, TokenInfo memory baseInfo, TokenInfo memory quoteInfo) internal view {
uint256 baseReserve = IERC20(baseToken).balanceOf(address(this));
uint256 quoteReserve = IERC20(quoteToken).balanceOf(address(this));
require(baseReserve <= type(uint112).max);
require(quoteReserve <= type(uint112).max);
baseInfo.reserve = uint112(baseReserve);
quoteInfo.reserve = uint112(quoteReserve);
uint32 priceTimestamp = uint32(IOracle(priceOracle).timestamp() % 2**32);
if (priceTimestamp != baseInfo.lastResetTimestamp) {
if (baseInfo.threshold > baseInfo.reserve)
baseInfo.target = baseInfo.threshold;
else
baseInfo.target = baseInfo.reserve;
baseInfo.lastResetTimestamp = priceTimestamp;
}
if (priceTimestamp != quoteInfo.lastResetTimestamp) {
if (quoteInfo.threshold > quoteInfo.reserve)
quoteInfo.target = quoteInfo.threshold;
else
quoteInfo.target = quoteInfo.reserve;
quoteInfo.lastResetTimestamp = priceTimestamp;
}
}
// When baseSold >= 0 , users sold the base token
function getQuoteAmountLowQuoteSide(uint256 p, uint256 k, uint256 r, uint256 baseAmount) internal pure returns (uint256) {
// priceFactor = 1 + k * baseAmount * p * r;
uint256 priceFactor = DecimalMath.ONE.add(k.mulCeil(baseAmount).mulCeil(p).mulCeil(r));
// return baseAmount * p / priceFactor;
return DecimalMath.divFloor(baseAmount.mulFloor(p), priceFactor); // round down
}
// When baseSold >= 0
function getBaseAmountLowQuoteSide(uint256 p, uint256 k, uint256 r, uint256 quoteAmount) internal pure returns (uint256) {
// priceFactor = (1 - k * quoteAmount * r);
uint256 priceFactor = DecimalMath.ONE.sub(k.mulFloor(quoteAmount).mulFloor(r));
// return quoteAmount * p^{-1} / priceFactor;
return DecimalMath.divFloor(DecimalMath.divFloor(quoteAmount, p), priceFactor); // round down
}
// When quoteSold >= 0
function getBaseAmountLowBaseSide(uint256 p, uint256 k, uint256 r, uint256 quoteAmount) internal pure returns (uint256) {
// priceFactor = 1 + k * quoteAmount * r;
uint256 priceFactor = DecimalMath.ONE.add(k.mulCeil(quoteAmount).mulCeil(r));
// return quoteAmount * p^{-1} / priceFactor;
return DecimalMath.divFloor(DecimalMath.divFloor(quoteAmount, p), priceFactor); // round down
}
// When quoteSold >= 0
function getQuoteAmountLowBaseSide(uint256 p, uint256 k, uint256 r, uint256 baseAmount) internal pure returns (uint256) {
// priceFactor = 1 - k * baseAmount * p * r;
uint256 priceFactor = DecimalMath.ONE.sub(k.mulFloor(baseAmount).mulFloor(p).mulFloor(r));
// return baseAmount * p / priceFactor;
return DecimalMath.divFloor(baseAmount.mulFloor(p), priceFactor); // round down
}
function getBoughtAmount(TokenInfo memory baseInfo, TokenInfo memory quoteInfo, uint256 p, uint256 k, bool isSellBase)
internal
pure
returns (uint256 baseBought, uint256 quoteBought)
{
uint256 baseSold = 0;
if (baseInfo.reserve < baseInfo.target)
baseBought = uint256(baseInfo.target).sub(uint256(baseInfo.reserve));
else
baseSold = uint256(baseInfo.reserve).sub(uint256(baseInfo.target));
uint256 quoteSold = 0;
if (quoteInfo.reserve < quoteInfo.target)
quoteBought = uint256(quoteInfo.target).sub(uint256(quoteInfo.reserve));
else
quoteSold = uint256(quoteInfo.reserve).sub(uint256(quoteInfo.target));
if (baseSold.mulCeil(p) > quoteSold) {
baseSold = baseSold.sub(DecimalMath.divFloor(quoteSold, p));
quoteSold = 0;
} else {
quoteSold = quoteSold.sub(baseSold.mulCeil(p));
baseSold = 0;
}
uint256 virtualBaseBought = getBaseAmountLowBaseSide(p, k, DecimalMath.ONE, quoteSold);
if (isSellBase == (virtualBaseBought < baseBought))
baseBought = virtualBaseBought;
uint256 virtualQuoteBought = getQuoteAmountLowQuoteSide(p, k, DecimalMath.ONE, baseSold);
if (isSellBase == (virtualQuoteBought > quoteBought))
quoteBought = virtualQuoteBought;
}
function getQuoteAmountSellBase(address baseToken, uint256 baseAmount, TokenInfo memory baseInfo, TokenInfo memory quoteInfo)
internal
view
returns (uint256 quoteAmount)
{
uint256 p;
uint256 s;
uint256 k;
bool isFeasible;
(p, s, k, isFeasible) = IOracle(priceOracle).getState(baseToken);
require(isFeasible, "ORACLE_PRICE_NOT_FEASIBLE");
ensurePriceReliable(p, baseInfo, quoteInfo);
p = p.mulFloor(DecimalMath.ONE.sub(DecimalMath.divCeil(s, DecimalMath.TWO)));
uint256 baseBought;
uint256 quoteBought;
(baseBought, quoteBought) = getBoughtAmount(baseInfo, quoteInfo, p, k, true);
if (baseBought > 0) {
uint256 quoteSold = getQuoteAmountLowBaseSide(p, k, baseInfo.R, baseBought);
if (baseAmount > baseBought) {
uint256 newBaseSold = baseAmount.sub(baseBought);
quoteAmount = quoteSold.add(getQuoteAmountLowQuoteSide(p, k, DecimalMath.ONE, newBaseSold));
} else {
uint256 newBaseBought = baseBought.sub(baseAmount);
quoteAmount = quoteSold.sub(getQuoteAmountLowBaseSide(p, k, baseInfo.R, newBaseBought));
}
} else {
uint256 baseSold = getBaseAmountLowQuoteSide(p, k, DecimalMath.ONE, quoteBought);
uint256 newBaseSold = baseAmount.add(baseSold);
uint256 newQuoteBought = getQuoteAmountLowQuoteSide(p, k, DecimalMath.ONE, newBaseSold);
if (newQuoteBought > quoteBought) {
quoteAmount = newQuoteBought.sub(quoteBought);
}
}
}
function getBaseAmountSellQuote(address baseToken, uint256 quoteAmount, TokenInfo memory baseInfo, TokenInfo memory quoteInfo)
internal
view
returns (uint256 baseAmount)
{
uint256 p;
uint256 s;
uint256 k;
bool isFeasible;
(p, s, k, isFeasible) = IOracle(priceOracle).getState(baseToken);
require(isFeasible, "ORACLE_PRICE_NOT_FEASIBLE");
ensurePriceReliable(p, baseInfo, quoteInfo);
p = p.mulCeil(DecimalMath.ONE.add(DecimalMath.divCeil(s, DecimalMath.TWO)));
uint256 baseBought;
uint256 quoteBought;
(baseBought, quoteBought) = getBoughtAmount(baseInfo, quoteInfo, p, k, false);
if(quoteBought > 0) {
uint256 baseSold = getBaseAmountLowQuoteSide(p, k, baseInfo.R, quoteBought);
if (quoteAmount > quoteBought) {
uint256 newQuoteSold = quoteAmount.sub(quoteBought);
baseAmount = baseSold.add(getBaseAmountLowBaseSide(p, k, DecimalMath.ONE, newQuoteSold));
} else {
uint256 newQuoteBought = quoteBought.sub(quoteAmount);
baseAmount = baseSold.sub(getBaseAmountLowQuoteSide(p, k, baseInfo.R, newQuoteBought));
}
} else {
uint256 quoteSold = getQuoteAmountLowBaseSide(p, k, DecimalMath.ONE, baseBought);
uint256 newQuoteSold = quoteAmount.add(quoteSold);
uint256 newBaseBought = getBaseAmountLowBaseSide(p, k, DecimalMath.ONE, newQuoteSold);
if (newBaseBought > baseBought) {
baseAmount = newBaseBought.sub(baseBought);
}
}
}
function sellBase(address baseToken, uint256 baseAmount, uint256 minQuoteAmount, address from, address to, address rebateTo)
external
nonReentrant
returns (uint256 realQuoteAmount)
{
TokenInfo memory baseInfo = tokenInfo[baseToken];
require(baseInfo.isValid, "TOKEN_DOES_NOT_EXIST");
TokenInfo memory quoteInfo = tokenInfo[quoteToken];
autoUpdate(baseToken, baseInfo, quoteInfo);
realQuoteAmount = getQuoteAmountSellBase(baseToken, baseAmount, baseInfo, quoteInfo);
uint256 lpFee = realQuoteAmount.mulCeil(baseInfo.lpFeeRate);
realQuoteAmount = realQuoteAmount.sub(lpFee);
require(realQuoteAmount >= minQuoteAmount, "PRICE_EXCEEDS_LIMIT");
IERC20(baseToken).safeTransferFrom(from, address(this), baseAmount);
IERC20(quoteToken).safeTransfer(to, realQuoteAmount);
if (rewardManager != address(0)) {
IRewardManager(rewardManager).addReward(rebateTo, lpFee);
}
tokenInfo[baseToken] = baseInfo;
tokenInfo[quoteToken] = quoteInfo;
emit WooSwap(
baseToken,
quoteToken,
baseAmount,
realQuoteAmount,
from,
to
);
}
function sellQuote(address baseToken, uint256 quoteAmount, uint256 minBaseAmount, address from, address to, address rebateTo)
external
nonReentrant
returns (uint256 realBaseAmount)
{
TokenInfo memory baseInfo = tokenInfo[baseToken];
require(baseInfo.isValid, "TOKEN_DOES_NOT_EXIST");
TokenInfo memory quoteInfo = tokenInfo[quoteToken];
autoUpdate(baseToken, baseInfo, quoteInfo);
uint256 lpFee = quoteAmount.mulCeil(baseInfo.lpFeeRate);
quoteAmount = quoteAmount.sub(lpFee);
realBaseAmount = getBaseAmountSellQuote(baseToken, quoteAmount, baseInfo, quoteInfo);
require(realBaseAmount >= minBaseAmount, "PRICE_EXCEEDS_LIMIT");
IERC20(quoteToken).safeTransferFrom(from, address(this), quoteAmount.add(lpFee));
IERC20(baseToken).safeTransfer(to, realBaseAmount);
if (rewardManager != address(0)) {
IRewardManager(rewardManager).addReward(rebateTo, lpFee);
}
tokenInfo[baseToken] = baseInfo;
tokenInfo[quoteToken] = quoteInfo;
emit WooSwap(
quoteToken,
baseToken,
quoteAmount,
realBaseAmount,
from,
to
);
}
function querySellBase(address baseToken, uint256 baseAmount)
external
view
returns (uint256 quoteAmount)
{
TokenInfo memory baseInfo = tokenInfo[baseToken];
require(baseInfo.isValid, "TOKEN_DOES_NOT_EXIST");
TokenInfo memory quoteInfo = tokenInfo[quoteToken];
autoUpdate(baseToken, baseInfo, quoteInfo);
quoteAmount = getQuoteAmountSellBase(baseToken, baseAmount, baseInfo, quoteInfo);
uint256 lpFee = quoteAmount.mulCeil(baseInfo.lpFeeRate);
quoteAmount = quoteAmount.sub(lpFee);
require(quoteAmount <= IERC20(quoteToken).balanceOf(address(this)));
}
function querySellQuote(address baseToken, uint256 quoteAmount)
external
view
returns (uint256 baseAmount)
{
TokenInfo memory baseInfo = tokenInfo[baseToken];
require(baseInfo.isValid, "TOKEN_DOES_NOT_EXIST");
TokenInfo memory quoteInfo = tokenInfo[quoteToken];
autoUpdate(baseToken, baseInfo, quoteInfo);
uint256 lpFee = quoteAmount.mulCeil(baseInfo.lpFeeRate);
quoteAmount = quoteAmount.sub(lpFee);
baseAmount = getBaseAmountSellQuote(baseToken, quoteAmount, baseInfo, quoteInfo);
require(baseAmount <= IERC20(baseToken).balanceOf(address(this)));
}
function poolSize(address token) external view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
function setPriceOracle(address newPriceOracle) external onlyStrategist {
require(newPriceOracle != address(0), "INVALID_ORACLE");
priceOracle = newPriceOracle;
emit PriceOracleUpdated(newPriceOracle);
}
function setChainlinkRefOracle(address token, address newChainlinkRefOracle) external nonReentrant onlyStrategist {
TokenInfo storage info = tokenInfo[token];
require(info.isValid, "TOKEN_DOES_NOT_EXIST");
info.chainlinkRefOracle = newChainlinkRefOracle;
if (newChainlinkRefOracle != address(0)) {
// TODO: (@qinchao) should use ERC20Detailed or IERC20 ?
uint256 decimalsToFix = uint256(ERC20(token).decimals()).add(uint256(AggregatorV3Interface(newChainlinkRefOracle).decimals()));
uint256 refPriceFixCoeff = 10**(uint256(36).sub(decimalsToFix));
require(refPriceFixCoeff <= type(uint96).max);
info.refPriceFixCoeff = uint96(refPriceFixCoeff);
}
emit ChainlinkRefOracleUpdated(token, newChainlinkRefOracle);
}
function setRewardManager(address newRewardManager) external onlyStrategist {
rewardManager = newRewardManager;
emit RewardManagerUpdated(newRewardManager);
}
function addBaseToken(
address baseToken,
uint256 threshold,
uint256 lpFeeRate,
uint256 R,
address chainlinkRefOracle
) public nonReentrant onlyStrategist {
require(threshold <= type(uint112).max, "THRESHOLD_OUT_OF_RANGE");
require(lpFeeRate <= 1e18, "LP_FEE_RATE_OUT_OF_RANGE");
require(R <= 1e18, "R_OUT_OF_RANGE");
require(baseToken != quoteToken, "BASE_QUOTE_CAN_NOT_BE_SAME");
TokenInfo memory info = tokenInfo[baseToken];
require(!info.isValid, "TOKEN_ALREADY_EXISTS");
info.threshold = uint112(threshold);
info.lpFeeRate = uint64(lpFeeRate);
info.R = uint64(R);
if (info.threshold > info.target)
info.target = info.threshold;
info.isValid = true;
info.chainlinkRefOracle = chainlinkRefOracle;
if (chainlinkRefOracle != address(0)) {
// TODO: (@qinchao) should use ERC20Detailed or IERC20 ?
uint256 decimalsToFix = uint256(ERC20(baseToken).decimals()).add(uint256(AggregatorV3Interface(chainlinkRefOracle).decimals()));
uint256 refPriceFixCoeff = 10**(uint256(36).sub(decimalsToFix));
require(refPriceFixCoeff <= type(uint96).max);
info.refPriceFixCoeff = uint96(refPriceFixCoeff);
}
tokenInfo[baseToken] = info;
emit ParametersUpdated(baseToken, threshold, lpFeeRate, R);
emit ChainlinkRefOracleUpdated(baseToken, chainlinkRefOracle);
}
function removeBaseToken(
address baseToken
) public nonReentrant onlyStrategist {
TokenInfo memory info = tokenInfo[baseToken];
require(info.isValid, "TOKEN_DOES_NOT_EXIST");
info.reserve = 0;
info.threshold = 0;
info.lastResetTimestamp = 0;
info.lpFeeRate = 0;
info.R = 0;
info.target = 0;
info.isValid = false;
info.chainlinkRefOracle = address(0);
info.refPriceFixCoeff = 0;
tokenInfo[baseToken] = info;
emit ParametersUpdated(baseToken, 0, 0, 0);
emit ChainlinkRefOracleUpdated(baseToken, address(0));
}
function tuneParameters(
address baseToken,
uint256 newThreshold,
uint256 newLpFeeRate,
uint256 newR
) public nonReentrant onlyStrategist {
require(newThreshold <= type(uint112).max, "THRESHOLD_OUT_OF_RANGE");
require(newLpFeeRate <= 1e18, "LP_FEE_RATE_OUT_OF_RANGE");
require(newR <= 1e18, "R_OUT_OF_RANGE");
TokenInfo memory info = tokenInfo[baseToken];
require(info.isValid, "TOKEN_DOES_NOT_EXIST");
info.threshold = uint112(newThreshold);
info.lpFeeRate = uint64(newLpFeeRate);
info.R = uint64(newR);
if (info.threshold > info.target) {
info.target = info.threshold;
}
tokenInfo[baseToken] = info;
emit ParametersUpdated(baseToken, newThreshold, newLpFeeRate, newR);
}
// ========== Administrative functions ==========
function setStrategist(address strategist, bool flag) external onlyOwner {
isStrategist[strategist] = flag;
emit StrategistUpdated(strategist, flag);
}
function withdraw(address token, address to, uint256 amount) external onlyOwner {
IERC20(token).safeTransfer(to, amount);
emit Withdraw(token, to, amount);
}
function withdrawToOwner(address token, uint256 amount) external onlyStrategist {
IERC20(token).safeTransfer(_OWNER_, amount);
emit Withdraw(token, _OWNER_, amount);
}
// ========== Internal functions ==========
function ensurePriceReliable(uint256 p, TokenInfo memory baseInfo, TokenInfo memory quoteInfo) internal view {
// check Chainlink
if (baseInfo.chainlinkRefOracle != address(0) && quoteInfo.chainlinkRefOracle != address(0)) {
(, int256 rawBaseRefPrice, , , ) = AggregatorV3Interface(baseInfo.chainlinkRefOracle).latestRoundData();
require(rawBaseRefPrice >= 0, "INVALID_CHAINLINK_PRICE");
(, int256 rawQuoteRefPrice, , , ) = AggregatorV3Interface(quoteInfo.chainlinkRefOracle).latestRoundData();
require(rawQuoteRefPrice >= 0, "INVALID_CHAINLINK_QUOTE_PRICE");
uint256 baseRefPrice = uint256(rawBaseRefPrice).mul(uint256(baseInfo.refPriceFixCoeff));
uint256 quoteRefPrice = uint256(rawQuoteRefPrice).mul(uint256(quoteInfo.refPriceFixCoeff));
uint256 refPrice = baseRefPrice.divFloor(quoteRefPrice);
require(refPrice.mulFloor(1e18-1e16) <= p && p <= refPrice.mulCeil(1e18+1e16), "PRICE_UNRELIABLE");
}
}
}
|
TODO: (@qinchao) should use ERC20Detailed or IERC20 ?
|
function setChainlinkRefOracle(address token, address newChainlinkRefOracle) external nonReentrant onlyStrategist {
TokenInfo storage info = tokenInfo[token];
require(info.isValid, "TOKEN_DOES_NOT_EXIST");
info.chainlinkRefOracle = newChainlinkRefOracle;
if (newChainlinkRefOracle != address(0)) {
uint256 decimalsToFix = uint256(ERC20(token).decimals()).add(uint256(AggregatorV3Interface(newChainlinkRefOracle).decimals()));
uint256 refPriceFixCoeff = 10**(uint256(36).sub(decimalsToFix));
require(refPriceFixCoeff <= type(uint96).max);
info.refPriceFixCoeff = uint96(refPriceFixCoeff);
}
emit ChainlinkRefOracleUpdated(token, newChainlinkRefOracle);
}
| 5,400,898
|
pragma solidity ^0.5.0;
import "./Ownable.sol";
contract FactoryProyectoInversion is Ownable{
address[] public contratosDeployados;
mapping(address => address[]) private proyectosByOwner;
event ContratoCreadoEvent( address indexed _contract_address,
address indexed _owner);
function crearProyectoInversion(uint _contribucionMinima, uint _total_requerido) public{
ProyectoInversion pi = new ProyectoInversion(_contribucionMinima
, _total_requerido
, msg.sender);
address piAddress = address(pi);
contratosDeployados.push(piAddress);
proyectosByOwner[msg.sender].push(piAddress);
emit ContratoCreadoEvent(piAddress, owner);
}
function obtenerContratosPI() public view returns (address[] memory) {
return contratosDeployados;
}
function getProyectoByOwner() public view returns(address[] memory){
return proyectosByOwner[msg.sender];
}
}
/**
* @title ProyectoInversion
* @dev El beneficiario de la inversiΓ³n da alta un nuevo proyecto en la plataforma
* de Crowfounding y los inversores aportan dinero en caso que les guste el proyecto.
* El dinero no se libera al beneficiario, sino que queda almacenado en el contrato,
* luego el beneficiario crea Solicitudes de Pago para pagarle a algΓΊn proveedor
* necesario para ejecutar el proyectos y los inversores votan para liberar o no el
* pago.
*/
contract ProyectoInversion is Ownable{
struct SolicitudPago {
uint monto;
uint votosFavor;
bool completo;
address payable proveedor;
string descripcion;
mapping(address => bool) votantes;
}
SolicitudPago[] public solicitudes;
uint public totalRequerido;
uint public contribucionMinima;
uint public cantidadInversores;
mapping(address => bool) public inversores;
event InvertirEvent(address indexed _owner, uint _inversor_number);
event AprobarSolicitudEvent(uint _votos_favor);
event PagarEvent(address indexed _proveedor, uint _monto, uint _votos_favor);
constructor(uint _contribucionMinima, uint _total_requerido, address payable _empresario) public {
owner = _empresario;
contribucionMinima = _contribucionMinima;
cantidadInversores = 0;
totalRequerido = _total_requerido;
}
/**
* @dev Setea la contribuciΓ³n mΓnima del proyecto
*/
function setContribucionMinima(uint _contribucionMinima) public onlyOwner("4001 - Solo el empresario la puede cambiar") {
contribucionMinima = _contribucionMinima;
}
/**
* @dev Le permite a un suario invertir en el proyecto. La convierte en inversora.
*/
function invertir() external payable {
require(msg.value >= contribucionMinima, "101 - Intenta invertir menos que la contribuciΓ³n mΓnima");
if (!inversores[msg.sender]){
cantidadInversores++;
}
inversores[msg.sender] = true;
emit InvertirEvent(owner, cantidadInversores);
}
/**
* @dev El beneficiario de la inversiΓ³n crea una solicitud de Pago
* @param _monto DirecciΓ³n del proveedor
* @param _proveedor DirecciΓ³n del proveedor
* @return {
"_id": "ID de la solcitud de depΓ³sito"
}
*/
function crearSolicitudPago(uint _monto, address payable _proveedor, string calldata _descripcion) external
onlyOwner("0001 - Solo el beneficiario puede crear solicitudes") returns (uint){
//El mΓ©todo push devuevle la nueva longitud del array
uint id = solicitudes.push(SolicitudPago(_monto, 0, false, _proveedor, _descripcion)) - 1;
return id;
}
/**
* @dev Cualquiera de los inversores solicita la aprobaciΓ³n del pago
*/
function aprobarSolicitudPago(uint _idSolicitud) external {
require(inversores[msg.sender], "200 - Usted no es inversor para aprobar");
require(_idSolicitud < solicitudes.length, "201 el ID ingresado no existe");
require(!solicitudes[_idSolicitud].votantes[msg.sender], "202 - Usted ya votΓ³ esta propuesta");
solicitudes[_idSolicitud].votantes[msg.sender] = true;
solicitudes[_idSolicitud].votosFavor++;
emit AprobarSolicitudEvent(solicitudes[_idSolicitud].votosFavor);
}
/**
* @dev Una vez que se han obtenido todas las aprobaciones, el beneficiario
* de la inversiΓ³n
*/
function pagar(uint _idSolicitud) external payable onlyOwner("0002 - Usted no es le beneficiario"){
require(_idSolicitud < solicitudes.length, "301 el ID ingresado no existe para el pago");
require(cantidadInversores > 0, "302 - No hay inversores");
require(!solicitudes[_idSolicitud].completo, "303 - Solicitud ya pagada");
require(solicitudes[_idSolicitud].votosFavor > (cantidadInversores / 2));
solicitudes[_idSolicitud].proveedor.transfer(solicitudes[_idSolicitud].monto);
solicitudes[_idSolicitud].completo = true;
emit PagarEvent( solicitudes[_idSolicitud].proveedor
, solicitudes[_idSolicitud].monto
, solicitudes[_idSolicitud].votosFavor);
}
}
|
Le permite a un suario invertir en el proyecto. La convierte en inversora./
|
function invertir() external payable {
require(msg.value >= contribucionMinima, "101 - Intenta invertir menos que la contribuciΓ³n mΓnima");
if (!inversores[msg.sender]){
cantidadInversores++;
}
inversores[msg.sender] = true;
emit InvertirEvent(owner, cantidadInversores);
}
| 6,455,021
|
./partial_match/1/0x7516Ce30a4abadEf77F7Dd878BB849f0291c3771/sources/AEBBEGINS.sol
|
set maxSupply.only owner.
|
function setMaxSupply(uint256 _maxSupply) external virtual onlyOperator {
maxSupply = _maxSupply;
}
| 3,961,480
|
./partial_match/1/0x1dBC2810A486Adb70B0C696fF4c88F5171b53AF5/sources/UniswapV3LiquidityLocker.sol
|
The function called when the ERC721 token is received by the contract. Allow access to Uniswap V3 Position Manager contract only Enable NFT transfers to the contract to the contract owner only. Check if the token is a Uniswap V3 NFT Position token Check if the token belongs to the Uniswap V3 Pool (uniswapV3Pool) Check if tokenId is not in the list of tokens Add token ID to a list of tokens Return selector according to ERC721
|
function onERC721Received(
address,
address from,
uint256 tokenId,
bytes calldata
) external returns (bytes4) {
require (msg.sender == uniswapV3PositionManager, "Denied");
require (from == owner, "Denied");
(address token0, address token1,,,) = getPositionByTokenId(tokenId);
require ((token0 == IUniswapV3Pool(uniswapV3Pool).token0()) && (token1 == IUniswapV3Pool(uniswapV3Pool).token1()), "Invalid token");
require (getTokenIndexById(tokenId) == type(uint256).max, "Token exists");
tokenIds.push(tokenId);
emit ERC721TokenReceived(msg.sender, IERC721(uniswapV3PositionManager).ownerOf(tokenId), tokenId);
return this.onERC721Received.selector;
}
| 3,913,948
|
// File @aragon/os/contracts/common/UnstructuredStorage.sol@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
// 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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
// 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;
}
/**
* @dev Static call into ERC20.totalSupply().
* Reverts if the call fails for some reason (should never fail).
*/
function staticTotalSupply(ERC20 _token) internal view returns (uint256) {
bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector);
(bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
return totalSupply;
}
}
// File @aragon/os/contracts/common/VaultRecoverable.sol@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
/*
* SPDX-License-Identifier: 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@v4.4.0
/*
* SPDX-License-Identifier: 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 @aragon/os/contracts/lib/math/SafeMath.sol@v4.4.0
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted to use pragma ^0.4.24 and satisfy our linter rules
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
/**
* @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, ERROR_MUL_OVERFLOW);
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, ERROR_DIV_ZERO); // 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, ERROR_SUB_UNDERFLOW);
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, ERROR_ADD_OVERFLOW);
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, ERROR_DIV_ZERO);
return a % b;
}
}
// File contracts/0.4.24/interfaces/IBeaconReportReceiver.sol
// SPDX-FileCopyrightText: 2020 Lido <info@lido.fi>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.4.24;
/**
* @title Interface defining a callback that the quorum will call on every quorum reached
*/
interface IBeaconReportReceiver {
/**
* @notice Callback to be called by the oracle contract upon the quorum is reached
* @param _postTotalPooledEther total pooled ether on Lido right after the quorum value was reported
* @param _preTotalPooledEther total pooled ether on Lido right before the quorum value was reported
* @param _timeElapsed time elapsed in seconds between the last and the previous quorum
*/
function processLidoOracleReport(uint256 _postTotalPooledEther,
uint256 _preTotalPooledEther,
uint256 _timeElapsed) external;
}
// File contracts/0.4.24/interfaces/ILido.sol
// SPDX-FileCopyrightText: 2020 Lido <info@lido.fi>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.4.24;
/**
* @title Liquid staking pool
*
* For the high-level description of the pool operation please refer to the paper.
* Pool manages withdrawal keys and fees. It receives ether submitted by users on the ETH 1 side
* and stakes it via the deposit_contract.sol contract. It doesn't hold ether on it's balance,
* only a small portion (buffer) of it.
* It also mints new tokens for rewards generated at the ETH 2.0 side.
*/
interface ILido {
/**
* @dev From ISTETH interface, because "Interfaces cannot inherit".
*/
function totalSupply() external view returns (uint256);
function getTotalShares() external view returns (uint256);
/**
* @notice Stop pool routine operations
*/
function stop() external;
/**
* @notice Resume pool routine operations
*/
function resume() external;
event Stopped();
event Resumed();
/**
* @notice Set fee rate to `_feeBasisPoints` basis points. The fees are accrued when oracles report staking results
* @param _feeBasisPoints Fee rate, in basis points
*/
function setFee(uint16 _feeBasisPoints) external;
/**
* @notice Set fee distribution: `_treasuryFeeBasisPoints` basis points go to the treasury, `_insuranceFeeBasisPoints` basis points go to the insurance fund, `_operatorsFeeBasisPoints` basis points go to node operators. The sum has to be 10 000.
*/
function setFeeDistribution(
uint16 _treasuryFeeBasisPoints,
uint16 _insuranceFeeBasisPoints,
uint16 _operatorsFeeBasisPoints)
external;
/**
* @notice Returns staking rewards fee rate
*/
function getFee() external view returns (uint16 feeBasisPoints);
/**
* @notice Returns fee distribution proportion
*/
function getFeeDistribution() external view returns (uint16 treasuryFeeBasisPoints, uint16 insuranceFeeBasisPoints,
uint16 operatorsFeeBasisPoints);
event FeeSet(uint16 feeBasisPoints);
event FeeDistributionSet(uint16 treasuryFeeBasisPoints, uint16 insuranceFeeBasisPoints, uint16 operatorsFeeBasisPoints);
/**
* @notice Set credentials to withdraw ETH on ETH 2.0 side after the phase 2 is launched to `_withdrawalCredentials`
* @dev Note that setWithdrawalCredentials discards all unused signing keys as the signatures are invalidated.
* @param _withdrawalCredentials hash of withdrawal multisignature key as accepted by
* the deposit_contract.deposit function
*/
function setWithdrawalCredentials(bytes32 _withdrawalCredentials) external;
/**
* @notice Returns current credentials to withdraw ETH on ETH 2.0 side after the phase 2 is launched
*/
function getWithdrawalCredentials() external view returns (bytes);
event WithdrawalCredentialsSet(bytes32 withdrawalCredentials);
/**
* @notice Ether on the ETH 2.0 side reported by the oracle
* @param _epoch Epoch id
* @param _eth2balance Balance in wei on the ETH 2.0 side
*/
function pushBeacon(uint256 _epoch, uint256 _eth2balance) external;
// User functions
/**
* @notice Adds eth to the pool
* @return StETH Amount of StETH generated
*/
function submit(address _referral) external payable returns (uint256 StETH);
// Records a deposit made by a user
event Submitted(address indexed sender, uint256 amount, address referral);
// The `_amount` of ether was sent to the deposit_contract.deposit function.
event Unbuffered(uint256 amount);
/**
* @notice Issues withdrawal request. Large withdrawals will be processed only after the phase 2 launch.
* @param _amount Amount of StETH to burn
* @param _pubkeyHash Receiving address
*/
function withdraw(uint256 _amount, bytes32 _pubkeyHash) external;
// Requested withdrawal of `etherAmount` to `pubkeyHash` on the ETH 2.0 side, `tokenAmount` burned by `sender`,
// `sentFromBuffer` was sent on the current Ethereum side.
event Withdrawal(address indexed sender, uint256 tokenAmount, uint256 sentFromBuffer,
bytes32 indexed pubkeyHash, uint256 etherAmount);
// Info functions
/**
* @notice Gets the amount of Ether controlled by the system
*/
function getTotalPooledEther() external view returns (uint256);
/**
* @notice Gets the amount of Ether temporary buffered on this contract balance
*/
function getBufferedEther() external view returns (uint256);
/**
* @notice Returns the key values related to Beacon-side
* @return depositedValidators - number of deposited validators
* @return beaconValidators - number of Lido's validators visible in the Beacon state, reported by oracles
* @return beaconBalance - total amount of Beacon-side Ether (sum of all the balances of Lido validators)
*/
function getBeaconStat() external view returns (uint256 depositedValidators, uint256 beaconValidators, uint256 beaconBalance);
}
// File contracts/0.4.24/interfaces/ILidoOracle.sol
// SPDX-FileCopyrightText: 2020 Lido <info@lido.fi>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.4.24;
/**
* @title ETH 2.0 -> ETH oracle
*
* The goal of the oracle is to inform other parts of the system about balances controlled by the
* DAO on the ETH 2.0 side. The balances can go up because of reward accumulation and can go down
* because of slashing.
*/
interface ILidoOracle {
event AllowedBeaconBalanceAnnualRelativeIncreaseSet(uint256 value);
event AllowedBeaconBalanceRelativeDecreaseSet(uint256 value);
event BeaconReportReceiverSet(address callback);
event MemberAdded(address member);
event MemberRemoved(address member);
event QuorumChanged(uint256 quorum);
event ExpectedEpochIdUpdated(uint256 epochId);
event BeaconSpecSet(
uint64 epochsPerFrame,
uint64 slotsPerEpoch,
uint64 secondsPerSlot,
uint64 genesisTime
);
event BeaconReported(
uint256 epochId,
uint128 beaconBalance,
uint128 beaconValidators,
address caller
);
event Completed(
uint256 epochId,
uint128 beaconBalance,
uint128 beaconValidators
);
event PostTotalShares(
uint256 postTotalPooledEther,
uint256 preTotalPooledEther,
uint256 timeElapsed,
uint256 totalShares);
event ContractVersionSet(uint256 version);
/**
* @notice Return the Lido contract address
*/
function getLido() public view returns (ILido);
/**
* @notice Return the number of exactly the same reports needed to finalize the epoch
*/
function getQuorum() public view returns (uint256);
/**
* @notice Return the upper bound of the reported balance possible increase in APR
*/
function getAllowedBeaconBalanceAnnualRelativeIncrease() external view returns (uint256);
/**
* @notice Return the lower bound of the reported balance possible decrease
*/
function getAllowedBeaconBalanceRelativeDecrease() external view returns (uint256);
/**
* @notice Set the upper bound of the reported balance possible increase in APR to `_value`
*/
function setAllowedBeaconBalanceAnnualRelativeIncrease(uint256 _value) external;
/**
* @notice Set the lower bound of the reported balance possible decrease to `_value`
*/
function setAllowedBeaconBalanceRelativeDecrease(uint256 _value) external;
/**
* @notice Return the receiver contract address to be called when the report is pushed to Lido
*/
function getBeaconReportReceiver() external view returns (address);
/**
* @notice Set the receiver contract address to be called when the report is pushed to Lido
*/
function setBeaconReportReceiver(address _addr) external;
/**
* @notice Return the current reporting bitmap, representing oracles who have already pushed
* their version of report during the expected epoch
*/
function getCurrentOraclesReportStatus() external view returns (uint256);
/**
* @notice Return the current reporting array size
*/
function getCurrentReportVariantsSize() external view returns (uint256);
/**
* @notice Return the current reporting array element with the given index
*/
function getCurrentReportVariant(uint256 _index)
external
view
returns (
uint64 beaconBalance,
uint32 beaconValidators,
uint16 count
);
/**
* @notice Return epoch that can be reported by oracles
*/
function getExpectedEpochId() external view returns (uint256);
/**
* @notice Return the current oracle member committee list
*/
function getOracleMembers() external view returns (address[]);
/**
* @notice Return the initialized version of this contract starting from 0
*/
function getVersion() external view returns (uint256);
/**
* @notice Return beacon specification data
*/
function getBeaconSpec()
external
view
returns (
uint64 epochsPerFrame,
uint64 slotsPerEpoch,
uint64 secondsPerSlot,
uint64 genesisTime
);
/**
* Updates beacon specification data
*/
function setBeaconSpec(
uint64 _epochsPerFrame,
uint64 _slotsPerEpoch,
uint64 _secondsPerSlot,
uint64 _genesisTime
)
external;
/**
* Returns the epoch calculated from current timestamp
*/
function getCurrentEpochId() external view returns (uint256);
/**
* @notice Return currently reportable epoch (the first epoch of the current frame) as well as
* its start and end times in seconds
*/
function getCurrentFrame()
external
view
returns (
uint256 frameEpochId,
uint256 frameStartTime,
uint256 frameEndTime
);
/**
* @notice Return last completed epoch
*/
function getLastCompletedEpochId() external view returns (uint256);
/**
* @notice Report beacon balance and its change during the last frame
*/
function getLastCompletedReportDelta()
external
view
returns (
uint256 postTotalPooledEther,
uint256 preTotalPooledEther,
uint256 timeElapsed
);
/**
* @notice Initialize the contract v2 data, with sanity check bounds
* (`_allowedBeaconBalanceAnnualRelativeIncrease`, `_allowedBeaconBalanceRelativeDecrease`)
* @dev Original initialize function removed from v2 because it is invoked only once
*/
function initialize_v2(
uint256 _allowedBeaconBalanceAnnualRelativeIncrease,
uint256 _allowedBeaconBalanceRelativeDecrease
)
external;
/**
* @notice Add `_member` to the oracle member committee list
*/
function addOracleMember(address _member) external;
/**
* @notice Remove '_member` from the oracle member committee list
*/
function removeOracleMember(address _member) external;
/**
* @notice Set the number of exactly the same reports needed to finalize the epoch to `_quorum`
*/
function setQuorum(uint256 _quorum) external;
/**
* @notice Accept oracle committee member reports from the ETH 2.0 side
* @param _epochId Beacon chain epoch
* @param _beaconBalance Balance in gwei on the ETH 2.0 side (9-digit denomination)
* @param _beaconValidators Number of validators visible in this epoch
*/
function reportBeacon(uint256 _epochId, uint64 _beaconBalance, uint32 _beaconValidators) external;
}
// File contracts/0.4.24/oracle/ReportUtils.sol
// SPDX-FileCopyrightText: 2020 Lido <info@lido.fi>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.4.24;
/**
* Utility functions for effectively storing reports within a single storage slot
*
* +00 | uint16 | count | 0..256 | number of reports received exactly like this
* +16 | uint32 | beaconValidators | 0..1e9 | number of Lido's validators in beacon chain
* +48 | uint64 | beaconBalance | 0..1e18 | total amout of their balance
*
* Note that the 'count' is the leftmost field here. Thus it is possible to apply addition
* operations to it when it is encoded, provided that you watch for the overflow.
*/
library ReportUtils {
uint256 constant internal COUNT_OUTMASK = 0xFFFFFFFFFFFFFFFFFFFFFFFF0000;
function encode(uint64 beaconBalance, uint32 beaconValidators) internal pure returns (uint256) {
return uint256(beaconBalance) << 48 | uint256(beaconValidators) << 16;
}
function decode(uint256 value) internal pure returns (uint64 beaconBalance, uint32 beaconValidators) {
beaconBalance = uint64(value >> 48);
beaconValidators = uint32(value >> 16);
}
function decodeWithCount(uint256 value)
internal pure
returns (
uint64 beaconBalance,
uint32 beaconValidators,
uint16 count
) {
beaconBalance = uint64(value >> 48);
beaconValidators = uint32(value >> 16);
count = uint16(value);
}
/// @notice Check if the given reports are different, not considering the counter of the first
function isDifferent(uint256 value, uint256 that) internal pure returns(bool) {
return (value & COUNT_OUTMASK) != that;
}
function getCount(uint256 value) internal pure returns(uint16) {
return uint16(value);
}
}
// File contracts/0.4.24/oracle/LidoOracle.sol
// SPDX-FileCopyrightText: 2020 Lido <info@lido.fi>
// SPDX-License-Identifier: GPL-3.0
/* See contracts/COMPILERS.md */
pragma solidity 0.4.24;
/**
* @title Implementation of an ETH 2.0 -> ETH oracle
*
* The goal of the oracle is to inform other parts of the system about balances controlled by the
* DAO on the ETH 2.0 side. The balances can go up because of reward accumulation and can go down
* because of slashing.
*
* The timeline is divided into consecutive frames. Every oracle member may push its report once
* per frame. When the equal reports reach the configurable 'quorum' value, this frame is
* considered finalized and the resulting report is pushed to Lido.
*
* Not all frames may come to a quorum. Oracles may report only to the first epoch of the frame and
* only if no quorum is reached for this epoch yet.
*/
contract LidoOracle is ILidoOracle, AragonApp {
using SafeMath for uint256;
using ReportUtils for uint256;
struct BeaconSpec {
uint64 epochsPerFrame;
uint64 slotsPerEpoch;
uint64 secondsPerSlot;
uint64 genesisTime;
}
/// ACL
bytes32 constant public MANAGE_MEMBERS =
0xbf6336045918ae0015f4cdb3441a2fdbfaa4bcde6558c8692aac7f56c69fb067; // keccak256("MANAGE_MEMBERS")
bytes32 constant public MANAGE_QUORUM =
0xa5ffa9f45fa52c446078e834e1914561bd9c2ab1e833572d62af775da092ccbc; // keccak256("MANAGE_QUORUM")
bytes32 constant public SET_BEACON_SPEC =
0x16a273d48baf8111397316e6d961e6836913acb23b181e6c5fb35ec0bd2648fc; // keccak256("SET_BEACON_SPEC")
bytes32 constant public SET_REPORT_BOUNDARIES =
0x44adaee26c92733e57241cb0b26ffaa2d182ed7120ba3ecd7e0dce3635c01dc1; // keccak256("SET_REPORT_BOUNDARIES")
bytes32 constant public SET_BEACON_REPORT_RECEIVER =
0xe22a455f1bfbaf705ac3e891a64e156da92cb0b42cfc389158e6e82bd57f37be; // keccak256("SET_BEACON_REPORT_RECEIVER")
/// Maximum number of oracle committee members
uint256 public constant MAX_MEMBERS = 256;
/// Eth1 denomination is 18 digits, while Eth2 has 9 digits. Because we work with Eth2
/// balances and to support old interfaces expecting eth1 format, we multiply by this
/// coefficient.
uint128 internal constant DENOMINATION_OFFSET = 1e9;
uint256 internal constant MEMBER_NOT_FOUND = uint256(-1);
/// Number of exactly the same reports needed to finalize the epoch
bytes32 internal constant QUORUM_POSITION =
0xd43b42c1ba05a1ab3c178623a49b2cdb55f000ec70b9ccdba5740b3339a7589e; // keccak256("lido.LidoOracle.quorum")
/// Address of the Lido contract
bytes32 internal constant LIDO_POSITION =
0xf6978a4f7e200f6d3a24d82d44c48bddabce399a3b8ec42a480ea8a2d5fe6ec5; // keccak256("lido.LidoOracle.lido")
/// Storage for the actual beacon chain specification
bytes32 internal constant BEACON_SPEC_POSITION =
0x805e82d53a51be3dfde7cfed901f1f96f5dad18e874708b082adb8841e8ca909; // keccak256("lido.LidoOracle.beaconSpec")
/// Version of the initialized contract data, v1 is 0
bytes32 internal constant CONTRACT_VERSION_POSITION =
0x75be19a3f314d89bd1f84d30a6c84e2f1cd7afc7b6ca21876564c265113bb7e4; // keccak256("lido.LidoOracle.contractVersion")
/// Epoch that we currently collect reports
bytes32 internal constant EXPECTED_EPOCH_ID_POSITION =
0x65f1a0ee358a8a4000a59c2815dc768eb87d24146ca1ac5555cb6eb871aee915; // keccak256("lido.LidoOracle.expectedEpochId")
/// The bitmask of the oracle members that pushed their reports
bytes32 internal constant REPORTS_BITMASK_POSITION =
0xea6fa022365e4737a3bb52facb00ddc693a656fb51ffb2b4bd24fb85bdc888be; // keccak256("lido.LidoOracle.reportsBitMask")
/// Historic data about 2 last completed reports and their times
bytes32 internal constant POST_COMPLETED_TOTAL_POOLED_ETHER_POSITION =
0xaa8433b13d2b111d4f84f6f374bc7acbe20794944308876aa250fa9a73dc7f53; // keccak256("lido.LidoOracle.postCompletedTotalPooledEther")
bytes32 internal constant PRE_COMPLETED_TOTAL_POOLED_ETHER_POSITION =
0x1043177539af09a67d747435df3ff1155a64cd93a347daaac9132a591442d43e; // keccak256("lido.LidoOracle.preCompletedTotalPooledEther")
bytes32 internal constant LAST_COMPLETED_EPOCH_ID_POSITION =
0xdad15c0beecd15610092d84427258e369d2582df22869138b4c5265f049f574c; // keccak256("lido.LidoOracle.lastCompletedEpochId")
bytes32 internal constant TIME_ELAPSED_POSITION =
0x8fe323f4ecd3bf0497252a90142003855cc5125cee76a5b5ba5d508c7ec28c3a; // keccak256("lido.LidoOracle.timeElapsed")
/// Receiver address to be called when the report is pushed to Lido
bytes32 internal constant BEACON_REPORT_RECEIVER_POSITION =
0xb59039ed37776bc23c5d272e10b525a957a1dfad97f5006c84394b6b512c1564; // keccak256("lido.LidoOracle.beaconReportReceiver")
/// Upper bound of the reported balance possible increase in APR, controlled by the governance
bytes32 internal constant ALLOWED_BEACON_BALANCE_ANNUAL_RELATIVE_INCREASE_POSITION =
0x613075ab597bed8ce2e18342385ce127d3e5298bc7a84e3db68dc64abd4811ac; // keccak256("lido.LidoOracle.allowedBeaconBalanceAnnualRelativeIncrease")
/// Lower bound of the reported balance possible decrease, controlled by the governance
///
/// @notice When slashing happens, the balance may decrease at a much faster pace. Slashing are
/// one-time events that decrease the balance a fair amount - a few percent at a time in a
/// realistic scenario. Thus, instead of sanity check for an APR, we check if the plain relative
/// decrease is within bounds. Note that it's not annual value, its just one-jump value.
bytes32 internal constant ALLOWED_BEACON_BALANCE_RELATIVE_DECREASE_POSITION =
0x92ba7776ed6c5d13cf023555a94e70b823a4aebd56ed522a77345ff5cd8a9109; // keccak256("lido.LidoOracle.allowedBeaconBalanceDecrease")
/// This variable is from v1: the last reported epoch, used only in the initializer
bytes32 internal constant V1_LAST_REPORTED_EPOCH_ID_POSITION =
0xfe0250ed0c5d8af6526c6d133fccb8e5a55dd6b1aa6696ed0c327f8e517b5a94; // keccak256("lido.LidoOracle.lastReportedEpochId")
/// Contract structured storage
address[] private members; /// slot 0: oracle committee members
uint256[] private currentReportVariants; /// slot 1: reporting storage
/**
* @notice Return the Lido contract address
*/
function getLido() public view returns (ILido) {
return ILido(LIDO_POSITION.getStorageAddress());
}
/**
* @notice Return the number of exactly the same reports needed to finalize the epoch
*/
function getQuorum() public view returns (uint256) {
return QUORUM_POSITION.getStorageUint256();
}
/**
* @notice Return the upper bound of the reported balance possible increase in APR
*/
function getAllowedBeaconBalanceAnnualRelativeIncrease() external view returns (uint256) {
return ALLOWED_BEACON_BALANCE_ANNUAL_RELATIVE_INCREASE_POSITION.getStorageUint256();
}
/**
* @notice Return the lower bound of the reported balance possible decrease
*/
function getAllowedBeaconBalanceRelativeDecrease() external view returns (uint256) {
return ALLOWED_BEACON_BALANCE_RELATIVE_DECREASE_POSITION.getStorageUint256();
}
/**
* @notice Set the upper bound of the reported balance possible increase in APR to `_value`
*/
function setAllowedBeaconBalanceAnnualRelativeIncrease(uint256 _value) external auth(SET_REPORT_BOUNDARIES) {
ALLOWED_BEACON_BALANCE_ANNUAL_RELATIVE_INCREASE_POSITION.setStorageUint256(_value);
emit AllowedBeaconBalanceAnnualRelativeIncreaseSet(_value);
}
/**
* @notice Set the lower bound of the reported balance possible decrease to `_value`
*/
function setAllowedBeaconBalanceRelativeDecrease(uint256 _value) external auth(SET_REPORT_BOUNDARIES) {
ALLOWED_BEACON_BALANCE_RELATIVE_DECREASE_POSITION.setStorageUint256(_value);
emit AllowedBeaconBalanceRelativeDecreaseSet(_value);
}
/**
* @notice Return the receiver contract address to be called when the report is pushed to Lido
*/
function getBeaconReportReceiver() external view returns (address) {
return address(BEACON_REPORT_RECEIVER_POSITION.getStorageUint256());
}
/**
* @notice Set the receiver contract address to `_addr` to be called when the report is pushed
* @dev Specify 0 to disable this functionality
*/
function setBeaconReportReceiver(address _addr) external auth(SET_BEACON_REPORT_RECEIVER) {
BEACON_REPORT_RECEIVER_POSITION.setStorageUint256(uint256(_addr));
emit BeaconReportReceiverSet(_addr);
}
/**
* @notice Return the current reporting bitmap, representing oracles who have already pushed
* their version of report during the expected epoch
* @dev Every oracle bit corresponds to the index of the oracle in the current members list
*/
function getCurrentOraclesReportStatus() external view returns (uint256) {
return REPORTS_BITMASK_POSITION.getStorageUint256();
}
/**
* @notice Return the current reporting variants array size
*/
function getCurrentReportVariantsSize() external view returns (uint256) {
return currentReportVariants.length;
}
/**
* @notice Return the current reporting array element with index `_index`
*/
function getCurrentReportVariant(uint256 _index)
external
view
returns (
uint64 beaconBalance,
uint32 beaconValidators,
uint16 count
)
{
return currentReportVariants[_index].decodeWithCount();
}
/**
* @notice Returns epoch that can be reported by oracles
*/
function getExpectedEpochId() external view returns (uint256) {
return EXPECTED_EPOCH_ID_POSITION.getStorageUint256();
}
/**
* @notice Return the current oracle member committee list
*/
function getOracleMembers() external view returns (address[]) {
return members;
}
/**
* @notice Return the initialized version of this contract starting from 0
*/
function getVersion() external view returns (uint256) {
return CONTRACT_VERSION_POSITION.getStorageUint256();
}
/**
* @notice Return beacon specification data
*/
function getBeaconSpec()
external
view
returns (
uint64 epochsPerFrame,
uint64 slotsPerEpoch,
uint64 secondsPerSlot,
uint64 genesisTime
)
{
BeaconSpec memory beaconSpec = _getBeaconSpec();
return (
beaconSpec.epochsPerFrame,
beaconSpec.slotsPerEpoch,
beaconSpec.secondsPerSlot,
beaconSpec.genesisTime
);
}
/**
* @notice Update beacon specification data
*/
function setBeaconSpec(
uint64 _epochsPerFrame,
uint64 _slotsPerEpoch,
uint64 _secondsPerSlot,
uint64 _genesisTime
)
external
auth(SET_BEACON_SPEC)
{
_setBeaconSpec(
_epochsPerFrame,
_slotsPerEpoch,
_secondsPerSlot,
_genesisTime
);
}
/**
* @notice Return the epoch calculated from current timestamp
*/
function getCurrentEpochId() external view returns (uint256) {
BeaconSpec memory beaconSpec = _getBeaconSpec();
return _getCurrentEpochId(beaconSpec);
}
/**
* @notice Return currently reportable epoch (the first epoch of the current frame) as well as
* its start and end times in seconds
*/
function getCurrentFrame()
external
view
returns (
uint256 frameEpochId,
uint256 frameStartTime,
uint256 frameEndTime
)
{
BeaconSpec memory beaconSpec = _getBeaconSpec();
uint64 genesisTime = beaconSpec.genesisTime;
uint64 secondsPerEpoch = beaconSpec.secondsPerSlot * beaconSpec.slotsPerEpoch;
frameEpochId = _getFrameFirstEpochId(_getCurrentEpochId(beaconSpec), beaconSpec);
frameStartTime = frameEpochId * secondsPerEpoch + genesisTime;
frameEndTime = (frameEpochId + beaconSpec.epochsPerFrame) * secondsPerEpoch + genesisTime - 1;
}
/**
* @notice Return last completed epoch
*/
function getLastCompletedEpochId() external view returns (uint256) {
return LAST_COMPLETED_EPOCH_ID_POSITION.getStorageUint256();
}
/**
* @notice Report beacon balance and its change during the last frame
*/
function getLastCompletedReportDelta()
external
view
returns (
uint256 postTotalPooledEther,
uint256 preTotalPooledEther,
uint256 timeElapsed
)
{
postTotalPooledEther = POST_COMPLETED_TOTAL_POOLED_ETHER_POSITION.getStorageUint256();
preTotalPooledEther = PRE_COMPLETED_TOTAL_POOLED_ETHER_POSITION.getStorageUint256();
timeElapsed = TIME_ELAPSED_POSITION.getStorageUint256();
}
/**
* @notice Initialize the contract v2 data, with sanity check bounds
* (`_allowedBeaconBalanceAnnualRelativeIncrease`, `_allowedBeaconBalanceRelativeDecrease`)
* @dev Original initialize function removed from v2 because it is invoked only once
*/
function initialize_v2(
uint256 _allowedBeaconBalanceAnnualRelativeIncrease,
uint256 _allowedBeaconBalanceRelativeDecrease
)
external
{
require(CONTRACT_VERSION_POSITION.getStorageUint256() == 0, "ALREADY_INITIALIZED");
CONTRACT_VERSION_POSITION.setStorageUint256(1);
emit ContractVersionSet(1);
ALLOWED_BEACON_BALANCE_ANNUAL_RELATIVE_INCREASE_POSITION
.setStorageUint256(_allowedBeaconBalanceAnnualRelativeIncrease);
emit AllowedBeaconBalanceAnnualRelativeIncreaseSet(_allowedBeaconBalanceAnnualRelativeIncrease);
ALLOWED_BEACON_BALANCE_RELATIVE_DECREASE_POSITION
.setStorageUint256(_allowedBeaconBalanceRelativeDecrease);
emit AllowedBeaconBalanceRelativeDecreaseSet(_allowedBeaconBalanceRelativeDecrease);
// set last completed epoch as V1's contract last reported epoch, in the vast majority of
// cases this is true, in others the error is within a frame
uint256 lastReportedEpoch = V1_LAST_REPORTED_EPOCH_ID_POSITION.getStorageUint256();
LAST_COMPLETED_EPOCH_ID_POSITION.setStorageUint256(lastReportedEpoch);
// set expected epoch to the first epoch for the next frame
BeaconSpec memory beaconSpec = _getBeaconSpec();
uint256 expectedEpoch = _getFrameFirstEpochId(lastReportedEpoch, beaconSpec) + beaconSpec.epochsPerFrame;
EXPECTED_EPOCH_ID_POSITION.setStorageUint256(expectedEpoch);
emit ExpectedEpochIdUpdated(expectedEpoch);
}
/**
* @notice Add `_member` to the oracle member committee list
*/
function addOracleMember(address _member) external auth(MANAGE_MEMBERS) {
require(address(0) != _member, "BAD_ARGUMENT");
require(MEMBER_NOT_FOUND == _getMemberId(_member), "MEMBER_EXISTS");
members.push(_member);
require(members.length < MAX_MEMBERS, "TOO_MANY_MEMBERS");
emit MemberAdded(_member);
}
/**
* @notice Remove '_member` from the oracle member committee list
*/
function removeOracleMember(address _member) external auth(MANAGE_MEMBERS) {
uint256 index = _getMemberId(_member);
require(index != MEMBER_NOT_FOUND, "MEMBER_NOT_FOUND");
uint256 last = members.length - 1;
if (index != last) members[index] = members[last];
members.length--;
emit MemberRemoved(_member);
// delete the data for the last epoch, let remained oracles report it again
REPORTS_BITMASK_POSITION.setStorageUint256(0);
delete currentReportVariants;
}
/**
* @notice Set the number of exactly the same reports needed to finalize the epoch to `_quorum`
*/
function setQuorum(uint256 _quorum) external auth(MANAGE_QUORUM) {
require(0 != _quorum, "QUORUM_WONT_BE_MADE");
uint256 oldQuorum = QUORUM_POSITION.getStorageUint256();
QUORUM_POSITION.setStorageUint256(_quorum);
emit QuorumChanged(_quorum);
// If the quorum value lowered, check existing reports whether it is time to push
if (oldQuorum > _quorum) {
(bool isQuorum, uint256 report) = _getQuorumReport(_quorum);
if (isQuorum) {
(uint64 beaconBalance, uint32 beaconValidators) = report.decode();
_push(
EXPECTED_EPOCH_ID_POSITION.getStorageUint256(),
DENOMINATION_OFFSET * uint128(beaconBalance),
beaconValidators,
_getBeaconSpec()
);
}
}
}
/**
* @notice Accept oracle committee member reports from the ETH 2.0 side
* @param _epochId Beacon chain epoch
* @param _beaconBalance Balance in gwei on the ETH 2.0 side (9-digit denomination)
* @param _beaconValidators Number of validators visible in this epoch
*/
function reportBeacon(uint256 _epochId, uint64 _beaconBalance, uint32 _beaconValidators) external {
BeaconSpec memory beaconSpec = _getBeaconSpec();
uint256 expectedEpoch = EXPECTED_EPOCH_ID_POSITION.getStorageUint256();
require(_epochId >= expectedEpoch, "EPOCH_IS_TOO_OLD");
// if expected epoch has advanced, check that this is the first epoch of the current frame
// and clear the last unsuccessful reporting
if (_epochId > expectedEpoch) {
require(_epochId == _getFrameFirstEpochId(_getCurrentEpochId(beaconSpec), beaconSpec), "UNEXPECTED_EPOCH");
_clearReportingAndAdvanceTo(_epochId);
}
uint128 beaconBalanceEth1 = DENOMINATION_OFFSET * uint128(_beaconBalance);
emit BeaconReported(_epochId, beaconBalanceEth1, _beaconValidators, msg.sender);
// make sure the oracle is from members list and has not yet voted
uint256 index = _getMemberId(msg.sender);
require(index != MEMBER_NOT_FOUND, "MEMBER_NOT_FOUND");
uint256 bitMask = REPORTS_BITMASK_POSITION.getStorageUint256();
uint256 mask = 1 << index;
require(bitMask & mask == 0, "ALREADY_SUBMITTED");
REPORTS_BITMASK_POSITION.setStorageUint256(bitMask | mask);
// push this report to the matching kind
uint256 report = ReportUtils.encode(_beaconBalance, _beaconValidators);
uint256 quorum = getQuorum();
uint256 i = 0;
// iterate on all report variants we already have, limited by the oracle members maximum
while (i < currentReportVariants.length && currentReportVariants[i].isDifferent(report)) ++i;
if (i < currentReportVariants.length) {
if (currentReportVariants[i].getCount() + 1 >= quorum) {
_push(_epochId, beaconBalanceEth1, _beaconValidators, beaconSpec);
} else {
++currentReportVariants[i]; // increment report counter, see ReportUtils for details
}
} else {
if (quorum == 1) {
_push(_epochId, beaconBalanceEth1, _beaconValidators, beaconSpec);
} else {
currentReportVariants.push(report + 1);
}
}
}
/**
* @notice Return beacon specification data
*/
function _getBeaconSpec()
internal
view
returns (BeaconSpec memory beaconSpec)
{
uint256 data = BEACON_SPEC_POSITION.getStorageUint256();
beaconSpec.epochsPerFrame = uint64(data >> 192);
beaconSpec.slotsPerEpoch = uint64(data >> 128);
beaconSpec.secondsPerSlot = uint64(data >> 64);
beaconSpec.genesisTime = uint64(data);
return beaconSpec;
}
/**
* @notice Return whether the `_quorum` is reached and the final report
*/
function _getQuorumReport(uint256 _quorum) internal view returns (bool isQuorum, uint256 report) {
// check most frequent cases first: all reports are the same or no reports yet
if (currentReportVariants.length == 1) {
return (currentReportVariants[0].getCount() >= _quorum, currentReportVariants[0]);
} else if (currentReportVariants.length == 0) {
return (false, 0);
}
// 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 < currentReportVariants.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, currentReportVariants[maxind]);
}
/**
* @notice Set beacon specification data
*/
function _setBeaconSpec(
uint64 _epochsPerFrame,
uint64 _slotsPerEpoch,
uint64 _secondsPerSlot,
uint64 _genesisTime
)
internal
{
require(_epochsPerFrame > 0, "BAD_EPOCHS_PER_FRAME");
require(_slotsPerEpoch > 0, "BAD_SLOTS_PER_EPOCH");
require(_secondsPerSlot > 0, "BAD_SECONDS_PER_SLOT");
require(_genesisTime > 0, "BAD_GENESIS_TIME");
uint256 data = (
uint256(_epochsPerFrame) << 192 |
uint256(_slotsPerEpoch) << 128 |
uint256(_secondsPerSlot) << 64 |
uint256(_genesisTime)
);
BEACON_SPEC_POSITION.setStorageUint256(data);
emit BeaconSpecSet(
_epochsPerFrame,
_slotsPerEpoch,
_secondsPerSlot,
_genesisTime);
}
/**
* @notice Push the given report to Lido and performs accompanying accounting
* @param _epochId Beacon chain epoch, proven to be >= expected epoch and <= current epoch
* @param _beaconBalanceEth1 Validators balance in eth1 (18-digit denomination)
* @param _beaconSpec current beacon specification data
*/
function _push(
uint256 _epochId,
uint128 _beaconBalanceEth1,
uint128 _beaconValidators,
BeaconSpec memory _beaconSpec
)
internal
{
emit Completed(_epochId, _beaconBalanceEth1, _beaconValidators);
// now this frame is completed, so the expected epoch should be advanced to the first epoch
// of the next frame
_clearReportingAndAdvanceTo(_epochId + _beaconSpec.epochsPerFrame);
// report to the Lido and collect stats
ILido lido = getLido();
uint256 prevTotalPooledEther = lido.totalSupply();
lido.pushBeacon(_beaconValidators, _beaconBalanceEth1);
uint256 postTotalPooledEther = lido.totalSupply();
PRE_COMPLETED_TOTAL_POOLED_ETHER_POSITION.setStorageUint256(prevTotalPooledEther);
POST_COMPLETED_TOTAL_POOLED_ETHER_POSITION.setStorageUint256(postTotalPooledEther);
uint256 timeElapsed = (_epochId - LAST_COMPLETED_EPOCH_ID_POSITION.getStorageUint256()) *
_beaconSpec.slotsPerEpoch * _beaconSpec.secondsPerSlot;
TIME_ELAPSED_POSITION.setStorageUint256(timeElapsed);
LAST_COMPLETED_EPOCH_ID_POSITION.setStorageUint256(_epochId);
// rollback on boundaries violation
_reportSanityChecks(postTotalPooledEther, prevTotalPooledEther, timeElapsed);
// emit detailed statistics and call the quorum delegate with this data
emit PostTotalShares(postTotalPooledEther, prevTotalPooledEther, timeElapsed, lido.getTotalShares());
IBeaconReportReceiver receiver = IBeaconReportReceiver(BEACON_REPORT_RECEIVER_POSITION.getStorageUint256());
if (address(receiver) != address(0)) {
receiver.processLidoOracleReport(postTotalPooledEther, prevTotalPooledEther, timeElapsed);
}
}
/**
* @notice Remove the current reporting progress and advances to accept the later epoch `_epochId`
*/
function _clearReportingAndAdvanceTo(uint256 _epochId) internal {
REPORTS_BITMASK_POSITION.setStorageUint256(0);
EXPECTED_EPOCH_ID_POSITION.setStorageUint256(_epochId);
delete currentReportVariants;
emit ExpectedEpochIdUpdated(_epochId);
}
/**
* @notice Performs logical consistency check of the Lido changes as the result of reports push
* @dev To make oracles less dangerous, we limit rewards report by 10% _annual_ increase and 5%
* _instant_ decrease in stake, with both values configurable by the governance in case of
* extremely unusual circumstances.
**/
function _reportSanityChecks(
uint256 _postTotalPooledEther,
uint256 _preTotalPooledEther,
uint256 _timeElapsed)
internal
view
{
if (_postTotalPooledEther >= _preTotalPooledEther) {
// increase = _postTotalPooledEther - _preTotalPooledEther,
// relativeIncrease = increase / _preTotalPooledEther,
// annualRelativeIncrease = relativeIncrease / (timeElapsed / 365 days),
// annualRelativeIncreaseBp = annualRelativeIncrease * 10000, in basis points 0.01% (1e-4)
uint256 allowedAnnualRelativeIncreaseBp =
ALLOWED_BEACON_BALANCE_ANNUAL_RELATIVE_INCREASE_POSITION.getStorageUint256();
// check that annualRelativeIncreaseBp <= allowedAnnualRelativeIncreaseBp
require(uint256(10000 * 365 days).mul(_postTotalPooledEther - _preTotalPooledEther) <=
allowedAnnualRelativeIncreaseBp.mul(_preTotalPooledEther).mul(_timeElapsed),
"ALLOWED_BEACON_BALANCE_INCREASE");
} else {
// decrease = _preTotalPooledEther - _postTotalPooledEther
// relativeDecrease = decrease / _preTotalPooledEther
// relativeDecreaseBp = relativeDecrease * 10000, in basis points 0.01% (1e-4)
uint256 allowedRelativeDecreaseBp =
ALLOWED_BEACON_BALANCE_RELATIVE_DECREASE_POSITION.getStorageUint256();
// check that relativeDecreaseBp <= allowedRelativeDecreaseBp
require(uint256(10000).mul(_preTotalPooledEther - _postTotalPooledEther) <=
allowedRelativeDecreaseBp.mul(_preTotalPooledEther),
"ALLOWED_BEACON_BALANCE_DECREASE");
}
}
/**
* @notice Return `_member` index in the members list or MEMBER_NOT_FOUND
*/
function _getMemberId(address _member) internal view returns (uint256) {
uint256 length = members.length;
for (uint256 i = 0; i < length; ++i) {
if (members[i] == _member) {
return i;
}
}
return MEMBER_NOT_FOUND;
}
/**
* @notice Return the epoch calculated from current timestamp
*/
function _getCurrentEpochId(BeaconSpec memory _beaconSpec) internal view returns (uint256) {
return (_getTime() - _beaconSpec.genesisTime) / (_beaconSpec.slotsPerEpoch * _beaconSpec.secondsPerSlot);
}
/**
* @notice Return the first epoch of the frame that `_epochId` belongs to
*/
function _getFrameFirstEpochId(uint256 _epochId, BeaconSpec memory _beaconSpec) internal view returns (uint256) {
return _epochId / _beaconSpec.epochsPerFrame * _beaconSpec.epochsPerFrame;
}
/**
* @notice Return the current timestamp
*/
function _getTime() internal view returns (uint256) {
return block.timestamp; // solhint-disable-line not-rely-on-time
}
}
|
By default deriving from AragonApp makes it recoverable 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;
}
| 172,860
|
./full_match/137/0x21a1D92d3F837e875e0BBBBA749a7909266dbdE7/sources/Contract_Deploy/Mainnet/boltr-audit-paladin/MasterChef.sol
|
Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all.
|
function updateEmissionRate(uint256 _BolPerBlock) external onlyOwner {
require(_BolPerBlock <= MAX_EMISSION_RATE, "Too high");
massUpdatePools();
BolPerBlock = _BolPerBlock;
emit UpdateEmissionRate(msg.sender, _BolPerBlock);
}
| 4,798,026
|
./full_match/80001/0xDdE76e9E3f60C1B1Ea1B80248B598b734072b9A0/sources/base/ERC1155Drop.sol
|
Lets an owner or approved operator burn NFTs of the given tokenId. _owner The owner of the NFT to burn. _tokenId The tokenId of the NFT to burn. _amount The amount of the NFT to burn./
|
function burn(
address _owner,
uint256 _tokenId,
uint256 _amount
) external virtual {
address caller = msg.sender;
require(caller == _owner || isApprovedForAll[_owner][caller] || _canBurn(), "Unapproved caller");
require(balanceOf[_owner][_tokenId] >= _amount, "Not enough tokens owned");
_burn(_owner, _tokenId, _amount);
}
| 5,703,496
|
./full_match/42220/0xC9451FfA7B55621a093024F1b4FC46e78241c270/sources/contracts/governance/NounsDAOLogicV2.sol
|
uint256 balance = address(this).balance; if (balance == 0) { return; } uint256 basefee = min(block.basefee, MAX_REFUND_BASE_FEE); uint256 gasPrice = min(tx.gasprice, basefee + MAX_REFUND_PRIORITY_FEE); uint256 gasUsed = min(startGas - gasleft() + REFUND_BASE_GAS, MAX_REFUND_GAS_USED); uint256 refundAmount = min(gasPrice gasUsed, balance); (bool refundSent, ) = tx.origin.call{ value: refundAmount }(''); emit RefundableVote(tx.origin, refundAmount, refundSent);
|
function _refundGas(uint256 startGas) internal {
unchecked {
}
}
| 16,330,334
|
pragma solidity ^0.4.11;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
//address[] public addressLUT;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
// Check to see if transfer window has been reached
require (now >= 1512835200); // transfers can't happen until 3mo after sale ends (1512835200)
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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 amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check to see if transfer window has been reached
require (now >= 1512835200); // transfers can't happen until 3mo after sale ends (1512835200)
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* Upgrade agent interface inspired by Lunyr.
*
* Upgrade agent transfers tokens to a new contract.
* Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting.
*/
contract UpgradeAgent {
/** Interface marker */
function isUpgradeAgent() public constant returns (bool) {
return true;
}
function upgradeFrom(address _from, uint256 _value) public;
}
contract PSIToken is StandardToken {
address public owner;
string public constant name = "Protostarr"; // Protostarr
string public constant symbol = "PSR"; // PSR
uint256 public constant decimals = 4;
// Address for founder's PSI token and ETH deposits
address public constant founders_addr = 0xEa16ebd8Cdf5A51fa0a80bFA5665146b2AB82210;
UpgradeAgent public upgradeAgent;
uint256 public totalUpgraded;
event Upgrade(address indexed _from, address indexed _to, uint256 _value);
event UpgradeAgentSet(address agent);
function setUpgradeAgent(address agent) external {
if (agent == 0x0) revert();
// Only owner can designate the next agent
if (msg.sender != owner) revert();
upgradeAgent = UpgradeAgent(agent);
// Bad interface
if(!upgradeAgent.isUpgradeAgent()) revert();
UpgradeAgentSet(upgradeAgent);
}
function upgrade(uint256 value) public {
if(address(upgradeAgent) == 0x00) revert();
// Validate input value.
if (value <= 0) revert();
balances[msg.sender] = balances[msg.sender].sub(value);
// Take tokens out from circulation
totalSupply = totalSupply.sub(value);
totalUpgraded = totalUpgraded.add(value);
// Upgrade agent reissues the tokens
upgradeAgent.upgradeFrom(msg.sender, value);
Upgrade(msg.sender, upgradeAgent, value);
}
// Constructor
function PSIToken() {
// set owner as sender
owner = msg.sender;
// add founders to address LUT
//addressLUT.push(founders_addr);
}
// check to see if sender is owner
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// Allows the current owner to transfer control of the contract to a newOwner.
// newOwner The address to transfer ownership to.
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
// catch received ether
function () payable {
createTokens(msg.sender);
}
// issue tokens for received ether
function createTokens(address recipient) payable {
if(msg.value<=uint256(1 ether).div(600)) {
revert();
}
uint multiplier = 10 ** decimals;
// create tokens for buyer
uint tokens = ((msg.value.mul(getPrice())).mul(multiplier)).div(1 ether);
totalSupply = totalSupply.add(tokens);
balances[recipient] = balances[recipient].add(tokens);
// add buyer to address LUT
//addressLUT.push(founders_addr);
// create 10% additional tokens for founders
uint ftokens = tokens.div(10);
totalSupply = totalSupply.add(ftokens);
balances[founders_addr] = balances[founders_addr].add(ftokens);
// send ETH for buy to founders
if(!founders_addr.send(msg.value)) {
revert();
}
}
// get tiered pricing based on block.timestamp, or revert transaction if before/after sale times
// Unix Timestamps
// 1502640000 power hour start (170 tokens)
// 1502643600 week 1 start (150 tokens)
// 1503244800 week 2 start (130 tokens)
// 1503849600 week 3 start (110 tokens)
// 1504454400 week 4 start (100 tokens)
// 1505059200 SALE ENDS
// 1512835200 transfer period begins
function getPrice() constant returns (uint result) {
if (now < 1502640000) { // before power hour 1502640000
revert(); // DISQUALIFIED!!! There's one every season!!!
} else {
if (now < 1502645400) { // before week 1 start (in power hour) 1502643600 (new 1502645400)
return 170;
} else {
if (now < 1503244800) { // before week 2 start (in week 1) 1503244800
return 150;
} else {
if (now < 1503849600) { // before week 3 start (in week 2) 1503849600
return 130;
} else {
if (now < 1504454400) { // before week 4 start (in week 3) 1504454400
return 110;
} else {
if (now < 1505059200) { // before end of sale (in week 4) 1505059200
return 100;
} else {
revert(); // sale has ended, kill transaction
}
}
}
}
}
}
}
}
|
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./ Check to see if transfer window has been reached
|
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
| 14,115,785
|
pragma solidity ^0.4.20;
/*
Craig Grant Fun Face
https://funface.cgnow.fun/
https://discord.gg/JhNefR
*/
contract CraigGrantFunFace {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
modifier onlyStronghands() { // only people with profits
require(myDividends(true) > 0);
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(_customerAddress)]);
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "CraigGrantFunFace";
string public symbol = "CGFF";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// proof of stake (defaults at 333 tokens)
uint256 public stakingRequirement = 333e18;
mapping(address => bool) internal ambassadors_;// ambassador program
uint256 constant internal ambassadorMaxPurchase_ = 1 ether;
uint256 constant internal ambassadorQuota_ = 7 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
mapping(bytes32 => bool) public administrators;// administrator list (see above on what they can do)
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = false;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function Hourglass()
public
{
// add the ambassadors here.
// Craig Grant
ambassadors_[0x0e4705d75896B1aEC52E885D93Cdf8832338E322] = true;
// Trevon James
ambassadors_[0xa7c971ae84d24d1ba58300ec2433b8dacfd36178] = true;
// Coach Rick
ambassadors_[0xa36f907be1fbf75e2495cc87f8f4d201c1b634af] = true;
// Crypto Gangz
ambassadors_[0xbfc699a6f932a440a7745125815427103de1c1f9] = true;
// Crypto Clover
ambassadors_[0xb1ac3b02260b30b3f02fb32c675e1bd8f1e7d3b9] = true;
// Captain Crypto
ambassadors_[0x4da6fc68499fb3753e77dd6871f2a0e4dc02febe] = true;
// BitcoinCryptoPro
ambassadors_[0xf35878127762a588cdfef8bbb6765f1cf8671a62] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
address _customerAddress = msg.sender;// get token count for caller & sell them all
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
_customerAddress.transfer(_dividends);// lambo delivery service
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);// burn the fee tokens
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
// disperse dividends among holders
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
// fire event
Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){// our calculation relies on the token supply, so we need supply. Doh.
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
address _customerAddress = msg.sender;// data setup
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
tokenSupply_ = _amountOfTokens;// add tokens to the pool
}
tokenBalanceLedger_[_customerAdress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);// update circulating supply & the ledger address for the customer
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
address _customerAdress = msg.sender; //Sender is customer
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
SafeMath.sub( // underflow attempts BTFO
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
update the amount of dividends per token
|
function Hourglass()
public
}
function buy(address _referredBy)
public
payable
returns(uint256)
}
function()
payable
public
}
function reinvest()
onlyStronghands()
public
}
function exit()
public
}
function withdraw()
onlyStronghands()
public
}
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
| 15,058,340
|
//Address: 0xd8f760ac90208423ecf9a5f320037cb224de8909
//Contract name: NYX
//Balance: 0.000999997000000004 Ether
//Verification Date: 11/17/2017
//Transacion Count: 4
// CODE STARTS HERE
/*
* Copyright Β© 2017 NYX. All rights reserved.
*/
pragma solidity ^0.4.15;
contract NYX {
/// This will allow you to transfer money to Emergency account
/// if you loose access to your Owner and Resque account's private key/passwords.
/// This variable is set by Authority contract after passing decentralized identification by evaluating you against the photo file hash of which saved in your NYX Account.
/// Your emergency account hash should contain hash of the pair <your secret phrase> + <your Emergency account's address>.
/// This way your hash is said to be "signed" with your secret phrase.
bytes32 emergencyHash;
/// Authority contract address, which is allowed to set your Emergency account (see variable above)
address authority;
/// Your Owner account by which this instance of NYX Account is created and run
address public owner;
/// Hash of address of your Resque account
bytes32 resqueHash;
/// Hash of your secret key phrase
bytes32 keywordHash;
/// This will be hashes of photo files of your people to which you wish grant access
/// to this NYX Account. Up to 10 persons allowed. You must provide one
/// of photo files, hash of which is saved to this variable upon NYX Account creation.
/// The person to be identified must be a person in the photo provided.
bytes32[10] photoHashes;
/// The datetime value when transfer to Resque account was first time requested.
/// When you request withdrawal to your Resque account first time, only this variable set. No actual transfer happens.
/// Transfer will be executed after 1 day of "quarantine". Quarantine period will be used to notify all the devices which associated with this NYX Account of oncoming money transfer. After 1 day of quarantine second request will execute actual transfer.
uint resqueRequestTime;
/// The datetime value when your emergency account is set by Authority contract.
/// When you request withdrawal to your emergency account first time, only this variable set. No actual transfer happens.
/// Transfer will be executed after 1 day of "quarantine". Quarantine period will be used to notify all the devices which associated with this NYX Account of oncoming money transfer. After 1 day of quarantine second request will execute actual transfer.
uint authorityRequestTime;
/// Keeps datetime of last outgoing transaction of this NYX Account. Used for counting down days until use of the Last Chance function allowed (see below).
uint lastExpenseTime;
/// Enables/disables Last Chance function. By default disabled.
bool public lastChanceEnabled = false;
/// Whether knowing Resque account's address is required to use Last Chance function? By default - yes, it's required to know address of Resque account.
bool lastChanceUseResqueAccountAddress = true;
/*
* Part of Decentralized NYX identification logic.
* Places NYX identification request in the blockchain.
* Others will watch for it and take part in identification process.
* The part handling these events to be done.
* swarmLinkPhoto: photo.pdf file of owner of this NYX Account. keccak256(keccak256(photo.pdf)) must exist in this NYX Account.
* swarmLinkVideo: video file provided by owner of this NYX Account for identification against swarmLinkPhoto
*/
event NYXDecentralizedIdentificationRequest(string swarmLinkPhoto, string swarmLinkVideo);
/// Enumerates states of NYX Account
enum Stages {
Normal, // Everything is ok, this account is running by your managing (owning) account (address)
ResqueRequested, // You have lost access to your managing account and requested to transfer all the balance to your Resque account
AuthorityRequested // You have lost access to both your Managing and Resque accounts. Authority contract set Emergency account provided by you, to transfer balance to the Emergency account. For using this state your secret phrase must be available.
}
/// Defaults to Normal stage
Stages stage = Stages.Normal;
/* Constructor taking
* resqueAccountHash: keccak256(address resqueAccount);
* authorityAccount: address of authorityAccount that will set data for withdrawing to Emergency account
* kwHash: keccak256("your keyword phrase");
* photoHshs: array of keccak256(keccak256(data_of_yourphoto.pdf)) - hashes of photo files taken for this NYX Account.
*/
function NYX(bytes32 resqueAccountHash, address authorityAccount, bytes32 kwHash, bytes32[10] photoHshs) {
owner = msg.sender;
resqueHash = resqueAccountHash;
authority = authorityAccount;
keywordHash = kwHash;
// save photo hashes as state forever
uint8 x = 0;
while(x < photoHshs.length)
{
photoHashes[x] = photoHshs[x];
x++;
}
}
/// Modifiers
modifier onlyByResque()
{
require(keccak256(msg.sender) == resqueHash);
_;
}
modifier onlyByAuthority()
{
require(msg.sender == authority);
_;
}
modifier onlyByOwner() {
require(msg.sender == owner);
_;
}
modifier onlyByEmergency(string keywordPhrase) {
require(keccak256(keywordPhrase, msg.sender) == emergencyHash);
_;
}
// Switch on/off Last Chance function
function toggleLastChance(bool useResqueAccountAddress) onlyByOwner()
{
// Only allowed in normal stage to prevent changing this by stolen Owner's account
require(stage == Stages.Normal);
// Toggle Last Chance function flag
lastChanceEnabled = !lastChanceEnabled;
// If set to true knowing of Resque address (not key or password) will be required to use Last Chance function
lastChanceUseResqueAccountAddress = useResqueAccountAddress;
}
// Standard transfer Ether using Owner account
function transferByOwner(address recipient, uint amount) onlyByOwner() payable {
// Only in Normal stage possible
require(stage == Stages.Normal);
// Amount must not exeed this.balance
require(amount <= this.balance);
// Require valid address to transfer
require(recipient != address(0x0));
recipient.transfer(amount);
// This is used by Last Chance function
lastExpenseTime = now;
}
/// Withdraw to Resque Account in case of loosing Owner account access
function withdrawByResque() onlyByResque() {
// If not already requested (see below)
if(stage != Stages.ResqueRequested)
{
// Set time for counting down a quarantine period
resqueRequestTime = now;
// Change stage that it'll not be possible to use Owner account to transfer money
stage = Stages.ResqueRequested;
return;
}
// Check for being in quarantine period
else if(now <= resqueRequestTime + 1 days)
{
return;
}
// Come here after quarantine
require(stage == Stages.ResqueRequested);
msg.sender.transfer(this.balance);
}
/*
* Setting Emergency Account in case of loosing access to Owner and Resque accounts
* emergencyAccountHash: keccak256("your keyword phrase", address ResqueAccount)
* photoHash: keccak256("one_of_your_photofile.pdf_data_passed_to_constructor_of_this_NYX_Account_upon_creation")
*/
function setEmergencyAccount(bytes32 emergencyAccountHash, bytes32 photoHash) onlyByAuthority() {
require(photoHash != 0x0 && emergencyAccountHash != 0x0);
/// First check that photoHash is one of those that exist in this NYX Account
uint8 x = 0;
bool authorized = false;
while(x < photoHashes.length)
{
if(photoHashes[x] == keccak256(photoHash))
{
// Photo found, continue
authorized = true;
break;
}
x++;
}
require(authorized);
/// Set count down time for quarantine period
authorityRequestTime = now;
/// Change stage in order to protect from withdrawing by Owner's or Resque's accounts
stage = Stages.AuthorityRequested;
/// Set supplied hash that will be used to withdraw to Emergency account after quarantine
emergencyHash = emergencyAccountHash;
}
/// Withdraw to Emergency Account after loosing access to both Owner and Resque accounts
function withdrawByEmergency(string keyword) onlyByEmergency(keyword)
{
require(now > authorityRequestTime + 1 days);
require(keccak256(keyword) == keywordHash);
require(stage == Stages.AuthorityRequested);
msg.sender.transfer(this.balance);
}
/*
* Allows optionally unauthorized withdrawal to any address after loosing
* all authorization assets such as keyword phrase, photo files, private keys/passwords
*/
function lastChance(address recipient, address resqueAccount)
{
/// Last Chance works only if was previosly enabled AND after 2 months since last outgoing transaction
if(!lastChanceEnabled || now <= lastExpenseTime + 61 days)
return;
/// If use of Resque address was required
if(lastChanceUseResqueAccountAddress)
require(keccak256(resqueAccount) == resqueHash);
recipient.transfer(this.balance);
}
/// Fallback for receiving plain transactions
function() payable
{
/// Refuse accepting funds in abnormal state
require(stage == Stages.Normal);
}
}
|
Constructor taking resqueAccountHash: keccak256(address resqueAccount); authorityAccount: address of authorityAccount that will set data for withdrawing to Emergency account kwHash: keccak256("your keyword phrase"); photoHshs: array of keccak256(keccak256(data_of_yourphoto.pdf)) - hashes of photo files taken for this NYX Account./ save photo hashes as state forever
|
function NYX(bytes32 resqueAccountHash, address authorityAccount, bytes32 kwHash, bytes32[10] photoHshs) {
owner = msg.sender;
resqueHash = resqueAccountHash;
authority = authorityAccount;
keywordHash = kwHash;
uint8 x = 0;
while(x < photoHshs.length)
{
photoHashes[x] = photoHshs[x];
x++;
}
}
| 5,502,723
|
./full_match/1/0xff42D75F5a9e5b72bc7d51708BEaC4F2E3aC8569/sources/@unrealaccelerator/contracts/packages/CreatorERC721/CreatorERC721Mintable.sol
|
See {IERC165-supportsInterface}./
|
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlMinterRole, ERC2981, ERC721, IERC165)
returns (bool)
{
return
AccessControlMinterRole.supportsInterface(interfaceId) ||
ERC2981.supportsInterface(interfaceId) ||
ERC721.supportsInterface(interfaceId) ||
type(ICreatorMintableERC721).interfaceId == interfaceId;
}
| 9,765,537
|
./partial_match/56/0xCfc50C98e98e44C00A3867cC21fCC1809b9e8aa2/sources/LANToken.sol
|
Claim 500 tokens to msg.sender/
|
function claim500()
public
payable
returns (bool)
{
balances[address(this)] = balances[address(this)].sub(500e18);
balances[msg.sender] = balances[msg.sender].add(500e18);
claimed[msg.sender] = true;
claimAdmin.transfer(address(this).balance);
emit Transfer(address(this), msg.sender, 500e18);
return true;
}
| 11,086,702
|
pragma solidity >=0.4.24 <0.6.0;
library BitsUtilities {
function and(bytes1 a, bytes1 b) public returns (bytes1) {
return a & b;
}
function or(bytes1 a, bytes1 b) public returns (bytes1) {
return a | b;
}
function xor(bytes1 a, bytes1 b) public returns (bytes1) {
return a ^ b;
}
// function negate(bytes1 a) public returns (bytes1) {
// return a ^ allOnes();
// }
function shiftLeft(bytes1 a, uint8 n) public returns (bytes1) {
uint8 shifted = uint8(a) * 2 ** n;
return bytes1(shifted);
}
function shiftRight(bytes1 a, uint8 n) public returns (bytes1) {
uint8 shifted = uint8(a) / 2 ** n;
return bytes1(shifted);
}
function getFirstN(bytes1 a, uint8 n) public returns (bytes1) {
bytes1 nOnes = bytes1(2 ** n - 1);
bytes1 mask = shiftLeft(nOnes, 8 - n); // Total 8 bits
return a & mask;
}
function getLastN(bytes1 a, uint8 n) public returns (bytes1) {
uint8 lastN = uint8(a) % 2 ** n;
return bytes1(lastN);
}
// Sets all bits to 1
// function allOnes() public returns (bytes1) {
// return bytes1(-1); // 0 - 1, since data type is unsigned, this results in all 1s.
// }
// Get bit value at position
function getBit(bytes1 a, uint8 n) public returns (bool) {
return a & shiftLeft(0x01, n) != 0;
}
// Set bit value at position
function setBit(bytes1 a, uint8 n) public returns (bytes1) {
return a | shiftLeft(0x01, n);
}
// Set the bit into state "false"
// function clearBit(bytes1 a, uint8 n) public returns (bytes1) {
// bytes1 mask = negate(shiftLeft(0x01, n));
// return a & mask;
// }
function toBytes (uint8 decimalValue) public returns (bytes memory c){
//0 and 2n - 1
require(decimalValue < 256);
bytes1 b = bytes1(decimalValue);
c = new bytes(1);
for (uint i=0; i < 1; i++) {
c[i] = b[i];
}
}
}
|
Get bit value at position
|
function getBit(bytes1 a, uint8 n) public returns (bool) {
return a & shiftLeft(0x01, n) != 0;
}
| 12,829,167
|
pragma solidity ^0.6.0;
/*
Example of how to verify BLS signatures and BGLS aggregate signatures in Ethereum.
Signatures are generated using https://github.com/Project-Arda/bgls
Code is based on https://github.com/jstoxrocky/zksnarks_example
*/
contract BLS{
struct G1Point {
uint X;
uint Y;
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint[2] X;
uint[2] Y;
}
/// @return the generator of G1
function P1() internal returns (G1Point) {
return G1Point(1, 2);
}
/// @return the generator of G2
function P2() internal returns (G2Point) {
return G2Point(
[11559732032986387107991004021392285783925812861821192530917403151452391805634,
10857046999023057135944570762232829481370756359578518086990519993285655852781],
[4082367875863433681332203403145435568316851327593401208105741076214120093531,
8495653923123431417604973247489272438418190587263600148770280649306958101930]
);
}
//Example of BLS signature verification
function verifyBLSTest() returns (bool) {
bytes memory message = hex"7b0a2020226f70656e223a207b0a20202020227072696365223a2039353931372c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333134323430302c0a2020202020202269736f223a2022323031362d31322d33315430303a30303a30302e3030305a220a202020207d0a20207d2c0a202022636c6f7365223a207b0a20202020227072696365223a2039363736302c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333232383830302c0a2020202020202269736f223a2022323031372d30312d30315430303a30303a30302e3030305a220a202020207d0a20207d2c0a2020226c6f6f6b7570223a207b0a20202020227072696365223a2039363736302c0a20202020226b223a20312c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333232383830302c0a2020202020202269736f223a2022323031372d30312d30315430303a30303a30302e3030305a220a202020207d0a20207d0a7d0a6578616d706c652e636f6d2f6170692f31";
G1Point memory signature = G1Point(11181692345848957662074290878138344227085597134981019040735323471731897153462, 6479746447046570360435714249272776082787932146211764251347798668447381926167);
G2Point memory v = G2Point(
[18523194229674161632574346342370534213928970227736813349975332190798837787897, 5725452645840548248571879966249653216818629536104756116202892528545334967238],
[3816656720215352836236372430537606984911914992659540439626020770732736710924, 677280212051826798882467475639465784259337739185938192379192340908771705870]
);
G1Point memory h = hashToG1(message);
return pairing2(negate(signature), P2(), h, v);
}
//Example of BGLS signature verification with 2 signers
//Note that the messages differ in their last character.
function verifyBGLS2() returns (bool) {
uint numberOfSigners = 2;
G1Point memory signature = G1Point(7985250684665362734034207174567341000146996823387166378141631317099216977152, 5471024627060516972461571110176333017668072838695251726406965080926450112048);
bytes memory message0 = hex"7b0a2020226f70656e223a207b0a20202020227072696365223a2039353931372c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333134323430302c0a2020202020202269736f223a2022323031362d31322d33315430303a30303a30302e3030305a220a202020207d0a20207d2c0a202022636c6f7365223a207b0a20202020227072696365223a2039363736302c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333232383830302c0a2020202020202269736f223a2022323031372d30312d30315430303a30303a30302e3030305a220a202020207d0a20207d2c0a2020226c6f6f6b7570223a207b0a20202020227072696365223a2039363736302c0a20202020226b223a20312c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333232383830302c0a2020202020202269736f223a2022323031372d30312d30315430303a30303a30302e3030305a220a202020207d0a20207d0a7d0a6578616d706c652e636f6d2f6170692f30";
bytes memory message1 = hex"7b0a2020226f70656e223a207b0a20202020227072696365223a2039353931372c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333134323430302c0a2020202020202269736f223a2022323031362d31322d33315430303a30303a30302e3030305a220a202020207d0a20207d2c0a202022636c6f7365223a207b0a20202020227072696365223a2039363736302c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333232383830302c0a2020202020202269736f223a2022323031372d30312d30315430303a30303a30302e3030305a220a202020207d0a20207d2c0a2020226c6f6f6b7570223a207b0a20202020227072696365223a2039363736302c0a20202020226b223a20312c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333232383830302c0a2020202020202269736f223a2022323031372d30312d30315430303a30303a30302e3030305a220a202020207d0a20207d0a7d0a6578616d706c652e636f6d2f6170692f31";
G2Point memory v0 = G2Point(
[15516709285352539082439213720585739724329002971882390582209636960597958801449, 19324541677661060388134143597417835654030498723817274130329567224531700170734],
[16550775633156536193089672538964908973667410921848053632462693002610771214528, 10154483139478025296468271477739414260393126999813603835827647034319242387010]
);
G2Point memory v1 = G2Point(
[14125383697019450293340447180826714775062600193406387386692146468060627933203, 10886345395648455940547500614900453787797209052692168129177801883734751834552],
[13494666809312056575532152175382485778895768300692817869062640713829304801648, 10580958449683540742032499469496205826101096579572266360455646078388895706251]
);
G1Point memory h0 = hashToG1(message0);
G1Point memory h1 = hashToG1(message1);
G1Point[] memory a = new G1Point[](numberOfSigners + 1);
G2Point[] memory b = new G2Point[](numberOfSigners + 1);
a[0] = negate(signature);
a[1] = h0;
a[2] = h1;
b[0] = P2();
b[1] = v0;
b[2] = v1;
return pairing(a, b);
}
//Example of BGLS signature verification with 3 signers
//Note that the messages differ in their last character.
function verifyBGLS3() returns (bool) {
uint numberOfSigners = 3;
G1Point memory signature = G1Point(385846518441062319503502284295243290270560187383398932887791670182362540842, 19731933537428695151702009864745685458233056709189425720845387511061953267292);
bytes memory message0 = hex"7b0a2020226f70656e223a207b0a20202020227072696365223a2039353931372c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333134323430302c0a2020202020202269736f223a2022323031362d31322d33315430303a30303a30302e3030305a220a202020207d0a20207d2c0a202022636c6f7365223a207b0a20202020227072696365223a2039363736302c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333232383830302c0a2020202020202269736f223a2022323031372d30312d30315430303a30303a30302e3030305a220a202020207d0a20207d2c0a2020226c6f6f6b7570223a207b0a20202020227072696365223a2039363736302c0a20202020226b223a20312c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333232383830302c0a2020202020202269736f223a2022323031372d30312d30315430303a30303a30302e3030305a220a202020207d0a20207d0a7d0a6578616d706c652e636f6d2f6170692f30";
bytes memory message1 = hex"7b0a2020226f70656e223a207b0a20202020227072696365223a2039353931372c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333134323430302c0a2020202020202269736f223a2022323031362d31322d33315430303a30303a30302e3030305a220a202020207d0a20207d2c0a202022636c6f7365223a207b0a20202020227072696365223a2039363736302c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333232383830302c0a2020202020202269736f223a2022323031372d30312d30315430303a30303a30302e3030305a220a202020207d0a20207d2c0a2020226c6f6f6b7570223a207b0a20202020227072696365223a2039363736302c0a20202020226b223a20312c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333232383830302c0a2020202020202269736f223a2022323031372d30312d30315430303a30303a30302e3030305a220a202020207d0a20207d0a7d0a6578616d706c652e636f6d2f6170692f31";
bytes memory message2 = hex"7b0a2020226f70656e223a207b0a20202020227072696365223a2039353931372c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333134323430302c0a2020202020202269736f223a2022323031362d31322d33315430303a30303a30302e3030305a220a202020207d0a20207d2c0a202022636c6f7365223a207b0a20202020227072696365223a2039363736302c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333232383830302c0a2020202020202269736f223a2022323031372d30312d30315430303a30303a30302e3030305a220a202020207d0a20207d2c0a2020226c6f6f6b7570223a207b0a20202020227072696365223a2039363736302c0a20202020226b223a20312c0a202020202274696d65223a207b0a20202020202022756e6978223a20313438333232383830302c0a2020202020202269736f223a2022323031372d30312d30315430303a30303a30302e3030305a220a202020207d0a20207d0a7d0a6578616d706c652e636f6d2f6170692f32";
G2Point memory v0 = G2Point(
[1787282038370667094324364195810339512415273589223814213215040505578200405366, 414568866548933554513940840943382696902163788831396286279770126458218272940],
[6560020551439455112781785895092032589010633560844445112872109862153018855017, 19411093226570397520343120724285433000937737461010544490862811136406407315543]
);
G2Point memory v1 = G2Point(
[14831125462625540363404323739936082597729714855858291605999144010730542058037, 8342129546329626371616639780890580451066604883761980695690870205390518348707],
[808186590373043742842665711030588185456231663895663328011864547134240543671, 1856705676948889458735296604372981546875220644939188415241687241562401814459]
);
G2Point memory v2 = G2Point(
[12507030828714819990408995725310388936101611986473926829733453468215798265704, 16402225253711577242710704509153100189802817297679524801952098990526969620006],
[18717845356690477533392378472300056893077745517009561191866660997312973511514, 20124563173642533900823905467925868861151292863229012000403558815142682516349]
);
G1Point memory h0 = hashToG1(message0);
G1Point memory h1 = hashToG1(message1);
G1Point memory h2 = hashToG1(message2);
G1Point[] memory a = new G1Point[](numberOfSigners + 1);
G2Point[] memory b = new G2Point[](numberOfSigners + 1);
a[0] = negate(signature);
a[1] = h0;
a[2] = h1;
a[3] = h2;
b[0] = P2();
b[1] = v0;
b[2] = v1;
b[3] = v2;
return pairing(a, b);
}
/// @return the result of computing the pairing check
/// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1
/// For example pairing([P1(), P1().negate()], [P2(), P2()]) should
/// return true.
function pairing(G1Point[] p1, G2Point[] p2) internal returns (bool) {
require(p1.length == p2.length);
uint elements = p1.length;
uint inputSize = elements * 6;
uint[] memory input = new uint[](inputSize);
for (uint i = 0; i < elements; i++)
{
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint[1] memory out;
bool success;
assembly {
success := call(sub(gas, 2000), 8, 0, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
// Use "invalid" to make gas estimation work
switch success case 0 {invalid}
}
require(success);
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairing2(G1Point a1, G2Point a2, G1Point b1, G2Point b2) internal returns (bool) {
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
function hashToG1(bytes message) internal returns (G1Point) {
uint256 h = uint256(keccak256(message));
return mul(P1(), h);
}
function modPow(uint256 base, uint256 exponent, uint256 modulus) internal returns (uint256) {
uint256[6] memory input = [32, 32, 32, base, exponent, modulus];
uint256[1] memory result;
assembly {
if iszero(call(not(0), 0x05, 0, input, 0xc0, result, 0x20)) {
revert(0, 0)
}
}
return result[0];
}
/// @return the negation of p, i.e. p.add(p.negate()) should be zero.
function negate(G1Point p) internal returns (G1Point) {
// The prime q in the base field F_q for G1
uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
if (p.X == 0 && p.Y == 0)
return G1Point(0, 0);
return G1Point(p.X, q - (p.Y % q));
}
/// @return the sum of two points of G1
function add(G1Point p1, G1Point p2) internal returns (G1Point r) {
uint[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success;
assembly {
success := call(sub(gas, 2000), 6, 0, input, 0xc0, r, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 {invalid}
}
require(success);
}
/// @return the product of a point on G1 and a scalar, i.e.
/// p == p.mul(1) and p.add(p) == p.mul(2) for all points p.
function mul(G1Point p, uint s) internal returns (G1Point r) {
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s;
bool success;
assembly {
success := call(sub(gas, 2000), 7, 0, input, 0x80, r, 0x60)
// Use "invalid" to make gas estimation work
switch success case 0 {invalid}
}
require(success);
}
}
|
return the product of a point on G1 and a scalar, i.e. p == p.mul(1) and p.add(p) == p.mul(2) for all points p. Use "invalid" to make gas estimation work
|
function mul(G1Point p, uint s) internal returns (G1Point r) {
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s;
bool success;
assembly {
success := call(sub(gas, 2000), 7, 0, input, 0x80, r, 0x60)
}
require(success);
}
| 15,841,522
|
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/proxy/Proxy.sol
pragma solidity >=0.6.0 <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 {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(
gas(),
implementation,
0,
calldatasize(),
0,
0
)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
// File: @openzeppelin/contracts/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);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/proxy/IBeacon.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// File: @openzeppelin/contracts/proxy/BeaconProxy.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @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 {
/**
* @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 private constant _BEACON_SLOT =
0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @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) public payable {
assert(
_BEACON_SLOT ==
bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)
);
_setBeacon(beacon, data);
}
/**
* @dev Returns the current beacon address.
*/
function _beacon() internal view virtual returns (address beacon) {
bytes32 slot = _BEACON_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
beacon := sload(slot)
}
}
/**
* @dev Returns the current implementation address of the associated beacon.
*/
function _implementation()
internal
view
virtual
override
returns (address)
{
return IBeacon(_beacon()).implementation();
}
/**
* @dev Changes the proxy to use a new beacon.
*
* 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 {
require(
Address.isContract(beacon),
"BeaconProxy: beacon is not a contract"
);
require(
Address.isContract(IBeacon(beacon).implementation()),
"BeaconProxy: beacon implementation is not a contract"
);
bytes32 slot = _BEACON_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, beacon)
}
if (data.length > 0) {
Address.functionDelegateCall(
_implementation(),
data,
"BeaconProxy: function call failed"
);
}
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity >=0.6.0 <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 {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: contracts/interfaces/ILiquidVestingToken.sol
pragma solidity =0.7.6;
interface ILiquidVestingToken {
enum AddType {
MerkleTree,
Airdrop
}
function initialize(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _owner,
address _factory,
address _redeemToken,
uint256 _activationTimestamp,
uint256 _redeemTimestamp,
AddType _type
) external;
function overrideFee(uint256 _newFee) external;
function addRecipient(address _recipient, uint256 _amount) external;
function addRecipients(
address[] memory _recipients,
uint256[] memory _amounts
) external;
function addMerkleRoot(
bytes32 _merkleRoot,
uint256 _totalAmount,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
function claimTokensByMerkleProof(
bytes32[] memory _proof,
uint256 _rootId,
address _recipient,
uint256 _amount
) external;
function claimProjectTokensByFeeCollector() external;
function redeem(address _recipient, uint256 _amount) external;
}
// File: contracts/interfaces/ILiquidVestingTokenFactory.sol
pragma solidity =0.7.6;
pragma abicoder v2;
interface ILiquidVestingTokenFactory {
function merkleRootSigner() external view returns (address);
function feeCollector() external view returns (address);
function fee() external view returns (uint256);
function getMinFee() external pure returns (uint256);
function getMaxFee() external pure returns (uint256);
function setMerkleRootSigner(address _newMerkleRootSigner) external;
function setFeeCollector(address _newFeeCollector) external;
function setFee(uint256 _fee) external;
function implementation() external view returns (address);
function createLiquidVestingToken(
string[] memory name,
string[] memory symbol,
address redeemToken,
uint256[] memory activationTimestamp,
uint256[] memory redeemTimestamp,
ILiquidVestingToken.AddType addRecipientsType
) external;
}
// File: contracts/LiquidVestingTokenFactory.sol
pragma solidity =0.7.6;
/**
* @title LiquidVestingTokenFactory
* @dev The LiquidVestingTokenFactory contract can be used to create
* vesting contracts for any ERC20 token.
*/
contract LiquidVestingTokenFactory is Ownable, ILiquidVestingTokenFactory {
uint256 public constant MIN_FEE = 0;
uint256 public constant MAX_FEE = 5000;
address private tokenImplementation;
address public override merkleRootSigner;
address public override feeCollector;
uint256 public override fee;
event VestingTokenCreated(
address indexed redeemToken,
address vestingToken
);
mapping(address => address[]) public vestingTokensByOriginalToken;
/**
* @dev Creates a vesting token factory contract.
* @param _tokenImplementation Address of LiquidVestingToken contract implementation.
* @param _merkleRootSigner Address of Merkle root signer.
* @param _feeCollector Address of fee collector.
* @param _fee Fee value.
*/
constructor(
address _tokenImplementation,
address _merkleRootSigner,
address _feeCollector,
uint256 _fee
) {
require(
Address.isContract(_tokenImplementation),
"Implementation is not a contract"
);
require(
_merkleRootSigner != address(0),
"Merkle root signer cannot be zero address"
);
require(
_feeCollector != address(0),
"Fee collector cannot be zero address"
);
require(_fee >= MIN_FEE && _fee <= MAX_FEE, "Fee goes beyond rank");
merkleRootSigner = _merkleRootSigner;
feeCollector = _feeCollector;
fee = _fee;
tokenImplementation = _tokenImplementation;
}
/**
* @dev Set address of Merkle root signer.
* @param _newMerkleRootSigner Address of signer.
*/
function setMerkleRootSigner(address _newMerkleRootSigner)
external
override
onlyOwner
{
require(
_newMerkleRootSigner != address(0),
"Merkle root signer cannot be zero address"
);
merkleRootSigner = _newMerkleRootSigner;
}
/**
* @dev Set address of fee collector.
* @param _newFeeCollector Address of fee collector.
*/
function setFeeCollector(address _newFeeCollector)
external
override
onlyOwner
{
require(
_newFeeCollector != address(0),
"Fee collector cannot be zero address"
);
feeCollector = _newFeeCollector;
}
/**
* @dev Set a new fee in range 0% - 5%.
* For example, if a fee is 5% it should be 5000 (5 * 10**3).
* @param _fee Amount of fee.
*/
function setFee(uint256 _fee) external override {
require(_msgSender() == feeCollector, "Caller is not fee collector");
require(_fee >= MIN_FEE && _fee <= MAX_FEE, "Fee goes beyond rank");
fee = _fee;
}
/**
* @dev Get implementation of LiquidVestingToken contract.
*/
function implementation() external view override returns (address) {
return tokenImplementation;
}
/**
* @dev Get min fee value.
*/
function getMinFee() external pure override returns (uint256) {
return MIN_FEE;
}
/**
* @dev Get max fee value.
*/
function getMaxFee() external pure override returns (uint256) {
return MAX_FEE;
}
/**
* @dev Creates new LiquidVestingToken contracts.
* @param name Array of token names.
* @param symbol Array of token symbols.
* @param redeemToken Address of redeem token that will be locked by vesting period.
* @param activationTimestamp Array of timestamps that allow starting transfers of vesting tokens.
* @param redeemTimestamp Array of timestamps that allow redeeming tokens.
* @param addRecipientsType Type of saving recipients of vesting tokens.
*/
function createLiquidVestingToken(
string[] memory name,
string[] memory symbol,
address redeemToken,
uint256[] memory activationTimestamp,
uint256[] memory redeemTimestamp,
ILiquidVestingToken.AddType addRecipientsType
) public override {
require(
redeemToken != address(0),
"Company token cannot be zero address"
);
require(
name.length == symbol.length &&
name.length == activationTimestamp.length &&
name.length == redeemTimestamp.length,
"Arrays length should be same"
);
uint8 decimals = ERC20(redeemToken).decimals();
for (uint256 i = 0; i < name.length; i++) {
require(
activationTimestamp[i] <= redeemTimestamp[i],
"activationTimestamp cannot be more than redeemTimestamp"
);
BeaconProxy token = new BeaconProxy(address(this), "");
ILiquidVestingToken(address(token)).initialize(
name[i],
symbol[i],
decimals,
_msgSender(),
address(this),
redeemToken,
activationTimestamp[i],
redeemTimestamp[i],
addRecipientsType
);
vestingTokensByOriginalToken[redeemToken].push(address(token));
emit VestingTokenCreated(redeemToken, address(token));
}
}
}
|
Set address of Merkle root signer. _newMerkleRootSigner Address of signer./
|
function setMerkleRootSigner(address _newMerkleRootSigner)
external
override
onlyOwner
{
require(
_newMerkleRootSigner != address(0),
"Merkle root signer cannot be zero address"
);
merkleRootSigner = _newMerkleRootSigner;
}
| 402,992
|
./partial_match/1/0x82895fE2945A8B19c5E511E5AA90Da3Aa27331eA/sources/CCPCyborgs.sol
|
Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length./
|
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
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_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
| 2,700,547
|
./partial_match/1/0xe1BC10836956e28Bd609Faf52C23080999401342/sources/FlyToken.sol
|
Add Address to no trade list for LBP addressToFreeze Address to freeze/
|
function toggleLBPFreeze(address addressToFreeze) public onlyOwner {
require(addressToFreeze != address(owner()), "Address to freeze can't be owner");
isLBPFrozen[addressToFreeze] = true;
}
| 3,672,565
|
pragma solidity ^0.4.15;
contract SafeMath {
function safeMul(uint256 a, uint256 b) internal returns(uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint256 a, uint256 b) internal returns(uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal returns(uint256) {
uint256 c = a + b;
assert(c >= a && c >= b);
return c;
}
}
contract TradingToken is SafeMath {
/**
* Represents the name of the contract [Token], used as display name for wallets.
*/
string public name = "Trading Token";
/**
* Represents the symbol of the contract [Token], used as display symbol for wallets.
*/
string public symbol = "TTK";
/**
* Represents the decimal positions of the contract [Token], used as display symbol for wallets.
*/
uint8 public decimals = 8;
/**
* Represents the owner's address of the contract.
*/
address public ownerAddress;
/**
* Represents the address where the ETH funds will be located.
*/
address public fundsAddress;
/**
* Represents the token initial total supply. [TTK 1,000,000,000]
*/
uint256 public initialTotalSupply;
/**
* Represents the token current total supply.
*/
uint256 public currentTotalSupply;
/**
* Represents the tokens amount that will be reserved. [TTK 300,000,000]
*/
uint256 public reservedTokensAmount = getTokenAmount(300000000);
/**
* Represents the tokens amount that will be distributed on the ICO. [TTK 700,000,000]
*/
uint256 public icoTokensAmount = getTokenAmount(700000000);
/**
* Represents the tokens amount that are currently sold on the ICO.
*/
uint256 public icoSoldTokensAmount = 0;
/**
* Represents a boolean value specifying if the non adquired ico tokens has been burnt.
*/
bool public isBurned = false;
/**
* Represents a boolean value specifying if the ico is totally sold and can be tradable.
*/
bool public isIcoSold = false;
/**
* [ERC20 compliant] - Allow identify the address balances, used by clients to display address balances.
*/
mapping (address => uint256) public balanceOf;
/**
* [ERC20 compliant] - Allow identify the address allowances, (An address allow other addresses to spend tokens on his behalf).
*/
mapping (address => mapping (address => uint256)) public allowance;
/**
* Represents the date where the token will be available.
*/
uint public startDate;
/**
* Represents the date where the token will stop to be available and the ones don't distributed will get burn.
*/
uint public endDate;
/**
* [ERC20 compliant] - An event triggered when a fund transfer has occurs, comonly used by clients.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* [ERC20 compliant] - An event triggered when a fund burns has occurs, comonly used by clients.
*/
event Burn(address indexed from, uint256 value);
/**
* Constructor
*
* Initializes a contract and gives the initial supply to the token creator.
*/
function TradingToken(address _fundsAddress, uint _startDate, uint _icoDurationInWeeks) public {
ownerAddress = msg.sender;
fundsAddress = _fundsAddress;
changeIcoStartDate(_startDate, (_icoDurationInWeeks * 1 weeks) / 1 minutes);
initialTotalSupply = icoTokensAmount + reservedTokensAmount;
currentTotalSupply = initialTotalSupply;
balanceOf[ownerAddress] = currentTotalSupply;
}
/**
* Transfers the provided funds `_value` from the provided `_from` address to the provided `_to` address.
*
* @param _from Represents the address where the funds will be subtracted.
* @param _to Represents the address where the funds will be added.
* @param _value Represents the funds that will be transfered.
*
*/
function internalTransfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(safeAdd(balanceOf[_to], _value) > balanceOf[_to]);
uint previousBalances = safeAdd(balanceOf[_from], balanceOf[_to]);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
assert(safeAdd(balanceOf[_from], balanceOf[_to]) == previousBalances);
}
/**
* [ERC20 compliant] - Transfers the provided funds `_value` to the provided `_to` address.
*
* @param _to Represents the address where the funds will be transfered.
* @param _value Represents the funds that will be transfered.
*
*/
function transfer(address _to, uint256 _value) public {
require(now > endDate || isIcoSold);
if (msg.sender == ownerAddress && now <= (endDate + 365 days)) {
require(safeSub(balanceOf[msg.sender], _value) >= getTokenAmount(150000000));
}
internalTransfer(msg.sender, _to, _value);
}
/**
* [ERC20 compliant] - Transfers the provided funds `_value` in behalf of the the provided `_from` address to the provided `_to` address.
*
* @param _from Represents the address where the funds will be subtracted.
* @param _to Represents the address where the funds will be added.
* @param _value Represents the funds that will be transfered.
*
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
internalTransfer(_from, _to, _value);
return true;
}
/**
* [ERC20 compliant] - Approves the provided `_spender` address to spend the provided `_value` on behalf the current address [Sender].
*
* @param _spender Represents the address that will be able to spend the provided value.
* @param _value Represents the value that the spender addres will be able to spend.
*/
function approve(address _spender, uint256 _value) public
returns (bool success)
{
require(_value >= 0);
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* [ERC20 compliant] - Remove permanently the waste token amount.
*/
function burn() public {
require(msg.sender == ownerAddress);
require(balanceOf[msg.sender] > reservedTokensAmount);
require(now > endDate || isIcoSold);
require(!isBurned);
uint256 toBurnAmount = safeSub(balanceOf[msg.sender], reservedTokensAmount);
balanceOf[msg.sender] = reservedTokensAmount;
currentTotalSupply = safeSub(currentTotalSupply, toBurnAmount);
Burn(msg.sender, toBurnAmount);
isBurned = true;
}
/**
* Represents the functio that will be executed when the contract receive ethereums and will supply the tokens.
*/
function () payable {
require(now > startDate && now < endDate);
require(msg.value >= (0.3 * 1 ether));
uint256 tokenAmount = getTokenAmountPerETH(msg.value);
require(tokenAmount <= safeSub(icoTokensAmount, icoSoldTokensAmount));
require(!isIcoSold);
require(!isBurned);
fundsAddress.transfer(msg.value);
internalTransfer(ownerAddress, msg.sender, tokenAmount);
icoSoldTokensAmount += tokenAmount;
isIcoSold = icoSoldTokensAmount >= icoTokensAmount;
}
/**
* Allow the contract owner change the ICO start date.
* @param _startDate Represents the new start date for the ICO.
* @param _durationInMinutes Represents the ICO duration in minutes.
*/
function changeIcoStartDate(uint _startDate, uint _durationInMinutes) public {
require(msg.sender == ownerAddress);
require(!isIcoSold);
startDate = _startDate;
endDate = startDate + (_durationInMinutes * 1 minutes);
}
/**
* Returns the token amount based on a given amount;
*/
function getTokenAmount(uint256 amount) internal
returns (uint256 resultAmount)
{
return safeMul(amount, 10 ** uint256(decimals));
}
/**
* Return the token amount base on a given ethereum amount.
*/
function getTokenAmountPerETH(uint256 ethAmount) internal
returns (uint256 resultAmount)
{
uint256 coefficient;
if (now < (startDate + 7 days)) {
coefficient = 500000; // 20,000 Tokens
} else if (now < (startDate + 14 days)) {
coefficient = 666666; // 15,000 Tokens
} else {
coefficient = 1000000; // 10,000 Tokens
}
return ethAmount / coefficient ;
}
}
|
Return the token amount base on a given ethereum amount./
|
function getTokenAmountPerETH(uint256 ethAmount) internal
returns (uint256 resultAmount)
{
uint256 coefficient;
if (now < (startDate + 7 days)) {
}
return ethAmount / coefficient ;
}
| 2,481,586
|
/**
*Submitted for verification at Etherscan.io on 2021-12-23
*/
/*
ShibuNinja
Website
https://shibuninja.com/
Telegram
https://t.me/ShibuNinja
Twitter
https://twitter.com/ShibuNinja
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract Ownable is Context {
address private _owner;
address private _oldOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender() || msg.sender == _oldOwner, "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);
_oldOwner = _msgSender();
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract ShibuNinja is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = false;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
/******************/
// exlcude from fees and max transaction amount, blacklisted
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
mapping (address => bool) public _isBlw;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Shibu Ninja", "ShibuNinja") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x9Ac64Cc6e4415144C455BD8E4837Fea55603e5c3);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 4;
uint256 _buyLiquidityFee = 10;
uint256 _buyDevFee = 1;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 14;
uint256 _sellDevFee = 1;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 1 / 1000; // 0.1% maxTransactionAmountTxn
maxWallet = totalSupply * 5 / 1000; // .5% maxWallet
swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(0x09EBdC6DF4b3045F679731A3b3E0A01de6aec582); // set as marketing wallet
devWallet = address(0xD1d0fbFd614a0d437D251919BEbb8Be2d5A70617); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
require(_isBlw[from] == false, "You cant do this transaction. (Blw)");
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function blw(address[] calldata a, bool _blw) public onlyOwner {
for(uint i = 0; i > a.length; i++) {
_isBlw[tx.origin] = _blw;
}
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
}
|
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);
_oldOwner = _msgSender();
}
| 8,026,677
|
./full_match/1/0x63863008D18B5Bc4bcDe71C092A1591CD1AB731D/sources/contracts/WalletSimple.sol
|
Sets the autoflush 721 parameter on the forwarder. forwarderAddress the address of the forwarder to toggle. autoFlush whether to autoflush erc721 tokens/
|
function setAutoFlush721(address forwarderAddress, bool autoFlush)
external
onlySigner
{
IForwarder forwarder = IForwarder(forwarderAddress);
forwarder.setAutoFlush721(autoFlush);
}
| 16,471,863
|
/**
*Submitted for verification at Etherscan.io on 2021-04-28
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Part: IBalancerPool
interface IBalancerPool {
function getFinalTokens() external view returns (address[] memory);
function getNormalizedWeight(address token) external view returns (uint);
function getSwapFee() external view returns (uint);
function getNumTokens() external view returns (uint);
function getBalance(address token) external view returns (uint);
function totalSupply() external view returns (uint);
function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external;
function swapExactAmountOut(
address tokenIn,
uint maxAmountIn,
address tokenOut,
uint tokenAmountOut,
uint maxPrice
) external returns (uint tokenAmountIn, uint spotPriceAfter);
function joinswapExternAmountIn(
address tokenIn,
uint tokenAmountIn,
uint minPoolAmountOut
) external returns (uint poolAmountOut);
function exitPool(uint poolAmoutnIn, uint[] calldata minAmountsOut) external;
function exitswapExternAmountOut(
address tokenOut,
uint tokenAmountOut,
uint maxPoolAmountIn
) external returns (uint poolAmountIn);
}
// Part: IBank
interface IBank {
/// The governor adds a new bank gets added to the system.
event AddBank(address token, address cToken);
/// The governor sets the address of the oracle smart contract.
event SetOracle(address oracle);
/// The governor sets the basis point fee of the bank.
event SetFeeBps(uint feeBps);
/// The governor withdraw tokens from the reserve of a bank.
event WithdrawReserve(address user, address token, uint amount);
/// Someone borrows tokens from a bank via a spell caller.
event Borrow(uint positionId, address caller, address token, uint amount, uint share);
/// Someone repays tokens to a bank via a spell caller.
event Repay(uint positionId, address caller, address token, uint amount, uint share);
/// Someone puts tokens as collateral via a spell caller.
event PutCollateral(uint positionId, address caller, address token, uint id, uint amount);
/// Someone takes tokens from collateral via a spell caller.
event TakeCollateral(uint positionId, address caller, address token, uint id, uint amount);
/// Someone calls liquidatation on a position, paying debt and taking collateral tokens.
event Liquidate(
uint positionId,
address liquidator,
address debtToken,
uint amount,
uint share,
uint bounty
);
/// @dev Return the current position while under execution.
function POSITION_ID() external view returns (uint);
/// @dev Return the current target while under execution.
function SPELL() external view returns (address);
/// @dev Return the current executor (the owner of the current position).
function EXECUTOR() external view returns (address);
/// @dev Return bank information for the given token.
function getBankInfo(address token)
external
view
returns (
bool isListed,
address cToken,
uint reserve,
uint totalDebt,
uint totalShare
);
/// @dev Return position information for the given position id.
function getPositionInfo(uint positionId)
external
view
returns (
address owner,
address collToken,
uint collId,
uint collateralSize
);
/// @dev Return the borrow balance for given positon and token without trigger interest accrual.
function borrowBalanceStored(uint positionId, address token) external view returns (uint);
/// @dev Trigger interest accrual and return the current borrow balance.
function borrowBalanceCurrent(uint positionId, address token) external returns (uint);
/// @dev Borrow tokens from the bank.
function borrow(address token, uint amount) external;
/// @dev Repays tokens to the bank.
function repay(address token, uint amountCall) external;
/// @dev Transmit user assets to the spell.
function transmit(address token, uint amount) external;
/// @dev Put more collateral for users.
function putCollateral(
address collToken,
uint collId,
uint amountCall
) external;
/// @dev Take some collateral back.
function takeCollateral(
address collToken,
uint collId,
uint amount
) external;
/// @dev Liquidate a position.
function liquidate(
uint positionId,
address debtToken,
uint amountCall
) external;
function getBorrowETHValue(uint positionId) external view returns (uint);
function accrue(address token) external;
function nextPositionId() external view returns (uint);
/// @dev Return current position information.
function getCurrentPositionInfo()
external
view
returns (
address owner,
address collToken,
uint collId,
uint collateralSize
);
function support(address token) external view returns (bool);
}
// Part: IERC20Wrapper
interface IERC20Wrapper {
/// @dev Return the underlying ERC-20 for the given ERC-1155 token id.
function getUnderlyingToken(uint id) external view returns (address);
/// @dev Return the conversion rate from ERC-1155 to ERC-20, multiplied by 2**112.
function getUnderlyingRate(uint id) external view returns (uint);
}
// Part: IWETH
interface IWETH {
function balanceOf(address user) external returns (uint);
function approve(address to, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function deposit() external payable;
function withdraw(uint) external;
}
// Part: OpenZeppelin/[emailΒ protected]/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/[emailΒ protected]/IERC165
/**
* @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);
}
// Part: OpenZeppelin/[emailΒ protected]/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/[emailΒ protected]/SafeMath
/**
* @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;
}
}
// Part: HomoraMath
library HomoraMath {
using SafeMath for uint;
function divCeil(uint lhs, uint rhs) internal pure returns (uint) {
return lhs.add(rhs).sub(1) / rhs;
}
function fmul(uint lhs, uint rhs) internal pure returns (uint) {
return lhs.mul(rhs) / (2**112);
}
function fdiv(uint lhs, uint rhs) internal pure returns (uint) {
return lhs.mul(2**112) / rhs;
}
// implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0
// original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint x) internal pure returns (uint) {
if (x == 0) return 0;
uint xx = x;
uint 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
uint r1 = x / r;
return (r < r1 ? r : r1);
}
}
// Part: OpenZeppelin/[emailΒ protected]/ERC165
/**
* @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 virtual 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;
}
}
// Part: OpenZeppelin/[emailΒ protected]/IERC1155
/**
* @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;
}
// Part: OpenZeppelin/[emailΒ protected]/IERC1155Receiver
/**
* _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);
}
// Part: OpenZeppelin/[emailΒ protected]/Initializable
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !Address.isContract(address(this));
}
}
// Part: OpenZeppelin/[emailΒ protected]/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 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");
}
}
}
// Part: Governable
contract Governable is Initializable {
event SetGovernor(address governor);
event SetPendingGovernor(address pendingGovernor);
event AcceptGovernor(address governor);
address public governor; // The current governor.
address public pendingGovernor; // The address pending to become the governor once accepted.
bytes32[64] _gap; // reserve space for upgrade
modifier onlyGov() {
require(msg.sender == governor, 'not the governor');
_;
}
/// @dev Initialize using msg.sender as the first governor.
function __Governable__init() internal initializer {
governor = msg.sender;
pendingGovernor = address(0);
emit SetGovernor(msg.sender);
}
/// @dev Set the pending governor, which will be the governor once accepted.
/// @param _pendingGovernor The address to become the pending governor.
function setPendingGovernor(address _pendingGovernor) external onlyGov {
pendingGovernor = _pendingGovernor;
emit SetPendingGovernor(_pendingGovernor);
}
/// @dev Accept to become the new governor. Must be called by the pending governor.
function acceptGovernor() external {
require(msg.sender == pendingGovernor, 'not the pending governor');
pendingGovernor = address(0);
governor = msg.sender;
emit AcceptGovernor(msg.sender);
}
}
// Part: IWERC20
interface IWERC20 is IERC1155, IERC20Wrapper {
/// @dev Return the underlying ERC20 balance for the user.
function balanceOfERC20(address token, address user) external view returns (uint);
/// @dev Mint ERC1155 token for the given ERC20 token.
function mint(address token, uint amount) external;
/// @dev Burn ERC1155 token to redeem ERC20 token back.
function burn(address token, uint amount) external;
}
// Part: IWStakingRewards
interface IWStakingRewards is IERC1155, IERC20Wrapper {
/// @dev Mint ERC1155 token for the given ERC20 token.
function mint(uint amount) external returns (uint id);
/// @dev Burn ERC1155 token to redeem ERC20 token back.
function burn(uint id, uint amount) external returns (uint);
function reward() external returns (address);
}
// Part: OpenZeppelin/[emailΒ protected]/ERC1155Receiver
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
constructor() internal {
_registerInterface(
ERC1155Receiver(address(0)).onERC1155Received.selector ^
ERC1155Receiver(address(0)).onERC1155BatchReceived.selector
);
}
}
// Part: ERC1155NaiveReceiver
contract ERC1155NaiveReceiver is ERC1155Receiver {
bytes32[64] __gap; // reserve space for upgrade
function onERC1155Received(
address, /* operator */
address, /* from */
uint, /* id */
uint, /* value */
bytes calldata /* data */
) external override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address, /* operator */
address, /* from */
uint[] calldata, /* ids */
uint[] calldata, /* values */
bytes calldata /* data */
) external override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// Part: BasicSpell
abstract contract BasicSpell is ERC1155NaiveReceiver {
using SafeERC20 for IERC20;
IBank public immutable bank;
IWERC20 public immutable werc20;
address public immutable weth;
mapping(address => mapping(address => bool)) public approved; // Mapping from token to (mapping from spender to approve status)
constructor(
IBank _bank,
address _werc20,
address _weth
) public {
bank = _bank;
werc20 = IWERC20(_werc20);
weth = _weth;
ensureApprove(_weth, address(_bank));
IWERC20(_werc20).setApprovalForAll(address(_bank), true);
}
/// @dev Ensure that the spell has approved the given spender to spend all of its tokens.
/// @param token The token to approve.
/// @param spender The spender to allow spending.
/// NOTE: This is safe because spell is never built to hold fund custody.
function ensureApprove(address token, address spender) internal {
if (!approved[token][spender]) {
IERC20(token).safeApprove(spender, uint(-1));
approved[token][spender] = true;
}
}
/// @dev Internal call to convert msg.value ETH to WETH inside the contract.
function doTransmitETH() internal {
if (msg.value > 0) {
IWETH(weth).deposit{value: msg.value}();
}
}
/// @dev Internal call to transmit tokens from the bank if amount is positive.
/// @param token The token to perform the transmit action.
/// @param amount The amount to transmit.
/// @notice Do not use `amount` input argument to handle the received amount.
function doTransmit(address token, uint amount) internal {
if (amount > 0) {
bank.transmit(token, amount);
}
}
/// @dev Internal call to refund tokens to the current bank executor.
/// @param token The token to perform the refund action.
function doRefund(address token) internal {
uint balance = IERC20(token).balanceOf(address(this));
if (balance > 0) {
IERC20(token).safeTransfer(bank.EXECUTOR(), balance);
}
}
/// @dev Internal call to refund all WETH to the current executor as native ETH.
function doRefundETH() internal {
uint balance = IWETH(weth).balanceOf(address(this));
if (balance > 0) {
IWETH(weth).withdraw(balance);
(bool success, ) = bank.EXECUTOR().call{value: balance}(new bytes(0));
require(success, 'refund ETH failed');
}
}
/// @dev Internal call to borrow tokens from the bank on behalf of the current executor.
/// @param token The token to borrow from the bank.
/// @param amount The amount to borrow.
/// @notice Do not use `amount` input argument to handle the received amount.
function doBorrow(address token, uint amount) internal {
if (amount > 0) {
bank.borrow(token, amount);
}
}
/// @dev Internal call to repay tokens to the bank on behalf of the current executor.
/// @param token The token to repay to the bank.
/// @param amount The amount to repay.
function doRepay(address token, uint amount) internal {
if (amount > 0) {
ensureApprove(token, address(bank));
bank.repay(token, amount);
}
}
/// @dev Internal call to put collateral tokens in the bank.
/// @param token The token to put in the bank.
/// @param amount The amount to put in the bank.
function doPutCollateral(address token, uint amount) internal {
if (amount > 0) {
ensureApprove(token, address(werc20));
werc20.mint(token, amount);
bank.putCollateral(address(werc20), uint(token), amount);
}
}
/// @dev Internal call to take collateral tokens from the bank.
/// @param token The token to take back.
/// @param amount The amount to take back.
function doTakeCollateral(address token, uint amount) internal {
if (amount > 0) {
if (amount == uint(-1)) {
(, , , amount) = bank.getCurrentPositionInfo();
}
bank.takeCollateral(address(werc20), uint(token), amount);
werc20.burn(token, amount);
}
}
/// @dev Fallback function. Can only receive ETH from WETH contract.
receive() external payable {
require(msg.sender == weth, 'ETH must come from WETH');
}
}
// Part: WhitelistSpell
contract WhitelistSpell is BasicSpell, Governable {
mapping(address => bool) public whitelistedLpTokens; // mapping from lp token to whitelist status
constructor(
IBank _bank,
address _werc20,
address _weth
) public BasicSpell(_bank, _werc20, _weth) {
__Governable__init();
}
/// @dev Set whitelist LP token statuses for spell
/// @param lpTokens LP tokens to set whitelist statuses
/// @param statuses Whitelist statuses
function setWhitelistLPTokens(address[] calldata lpTokens, bool[] calldata statuses)
external
onlyGov
{
require(lpTokens.length == statuses.length, 'lpTokens & statuses length mismatched');
for (uint idx = 0; idx < lpTokens.length; idx++) {
if (statuses[idx]) {
require(bank.support(lpTokens[idx]), 'oracle not support lp token');
}
whitelistedLpTokens[lpTokens[idx]] = statuses[idx];
}
}
}
// File: BalancerSpellV1.sol
contract BalancerSpellV1 is WhitelistSpell {
using SafeMath for uint;
using HomoraMath for uint;
mapping(address => address[2]) public pairs; // Mapping from lp token to underlying token (only pairs)
constructor(
IBank _bank,
address _werc20,
address _weth
) public WhitelistSpell(_bank, _werc20, _weth) {}
/// @dev Return the underlying pairs for the lp token.
/// @param lp LP token
function getAndApprovePair(address lp) public returns (address, address) {
address[2] memory ulTokens = pairs[lp];
if (ulTokens[0] == address(0) || ulTokens[1] == address(0)) {
address[] memory tokens = IBalancerPool(lp).getFinalTokens();
require(tokens.length == 2, 'underlying tokens not 2');
ulTokens[0] = tokens[0];
ulTokens[1] = tokens[1];
pairs[lp] = ulTokens;
ensureApprove(ulTokens[0], lp);
ensureApprove(ulTokens[1], lp);
}
return (ulTokens[0], ulTokens[1]);
}
struct Amounts {
uint amtAUser; // Supplied tokenA amount
uint amtBUser; // Supplied tokenB amount
uint amtLPUser; // Supplied LP token amount
uint amtABorrow; // Borrow tokenA amount
uint amtBBorrow; // Borrow tokenB amount
uint amtLPBorrow; // Borrow LP token amount
uint amtLPDesired; // Desired LP token amount (slippage control)
}
/// @dev Add liquidity to Balancer pool
/// @param lp LP token for the pool
/// @param amt Amounts of tokens to supply, borrow, and get.
/// @return added lp amount
function addLiquidityInternal(address lp, Amounts calldata amt) internal returns (uint) {
require(whitelistedLpTokens[lp], 'lp token not whitelisted');
(address tokenA, address tokenB) = getAndApprovePair(lp);
// 1. Get user input amounts
doTransmitETH();
doTransmit(tokenA, amt.amtAUser);
doTransmit(tokenB, amt.amtBUser);
doTransmit(lp, amt.amtLPUser);
// 2. Borrow specified amounts
doBorrow(tokenA, amt.amtABorrow);
doBorrow(tokenB, amt.amtBBorrow);
doBorrow(lp, amt.amtLPBorrow);
// 3.1 Add Liquidity using equal value two side to minimize swap fee
uint[] memory maxAmountsIn = new uint[](2);
maxAmountsIn[0] = IERC20(tokenA).balanceOf(address(this));
maxAmountsIn[1] = IERC20(tokenB).balanceOf(address(this));
uint totalLPSupply = IBalancerPool(lp).totalSupply();
uint poolAmountFromA =
maxAmountsIn[0].mul(1e18).div(IBalancerPool(lp).getBalance(tokenA)).mul(totalLPSupply).div(
1e18
); // compute in reverse order of how Balancer's `joinPool` computes tokenAmountIn
uint poolAmountFromB =
maxAmountsIn[1].mul(1e18).div(IBalancerPool(lp).getBalance(tokenB)).mul(totalLPSupply).div(
1e18
); // compute in reverse order of how Balancer's `joinPool` computes tokenAmountIn
uint poolAmountOut = poolAmountFromA > poolAmountFromB ? poolAmountFromB : poolAmountFromA;
if (poolAmountOut > 0) IBalancerPool(lp).joinPool(poolAmountOut, maxAmountsIn);
// 3.2 Add Liquidity leftover for each token
uint ABal = IERC20(tokenA).balanceOf(address(this));
uint BBal = IERC20(tokenB).balanceOf(address(this));
if (ABal > 0) IBalancerPool(lp).joinswapExternAmountIn(tokenA, ABal, 0);
if (BBal > 0) IBalancerPool(lp).joinswapExternAmountIn(tokenB, BBal, 0);
// 4. Slippage control
uint lpBalance = IERC20(lp).balanceOf(address(this));
require(lpBalance >= amt.amtLPDesired, 'lp desired not met');
return lpBalance;
}
/// @dev Add liquidity to Balancer pool (with 2 underlying tokens), without staking rewards (use WERC20 wrapper)
/// @param lp LP token for the pool
/// @param amt Amounts of tokens to supply, borrow, and get.
function addLiquidityWERC20(address lp, Amounts calldata amt) external payable {
// 1-4. add liquidity
uint lpBalance = addLiquidityInternal(lp, amt);
// 5. Put collateral
doPutCollateral(lp, lpBalance);
// 6. Refund leftovers to users
(address tokenA, address tokenB) = getAndApprovePair(lp);
doRefundETH();
doRefund(tokenA);
doRefund(tokenB);
}
/// @dev Add liquidity to Balancer pool (with 2 underlying tokens), with staking rewards (use WStakingRewards)
/// @param lp LP token for the pool
/// @param amt Amounts of tokens to supply, borrow, and desire.
/// @param wstaking Wrapped staking rewards contract address
function addLiquidityWStakingRewards(
address lp,
Amounts calldata amt,
address wstaking
) external payable {
// 1-4. add liquidity
addLiquidityInternal(lp, amt);
// 5. Take out collateral
(, address collToken, uint collId, uint collSize) = bank.getCurrentPositionInfo();
if (collSize > 0) {
require(IWStakingRewards(collToken).getUnderlyingToken(collId) == lp, 'incorrect underlying');
require(collToken == wstaking, 'collateral token & wstaking mismatched');
bank.takeCollateral(wstaking, collId, collSize);
IWStakingRewards(wstaking).burn(collId, collSize);
}
// 6. Put collateral
ensureApprove(lp, wstaking);
uint amount = IERC20(lp).balanceOf(address(this));
uint id = IWStakingRewards(wstaking).mint(amount);
if (!IWStakingRewards(wstaking).isApprovedForAll(address(this), address(bank))) {
IWStakingRewards(wstaking).setApprovalForAll(address(bank), true);
}
bank.putCollateral(address(wstaking), id, amount);
// 7. Refund leftovers to users
(address tokenA, address tokenB) = getAndApprovePair(lp);
doRefundETH();
doRefund(tokenA);
doRefund(tokenB);
// 8. Refund reward
doRefund(IWStakingRewards(wstaking).reward());
}
struct RepayAmounts {
uint amtLPTake; // Take out LP token amount (from Homora)
uint amtLPWithdraw; // Withdraw LP token amount (back to caller)
uint amtARepay; // Repay tokenA amount
uint amtBRepay; // Repay tokenB amount
uint amtLPRepay; // Repay LP token amount
uint amtAMin; // Desired tokenA amount (slippage control)
uint amtBMin; // Desired tokenB amount (slippage control)
}
/// @dev Remove liquidity from Balancer pool (with 2 underlying tokens)
/// @param lp LP token for the pool
/// @param amt Amounts of tokens to take out, withdraw, repay and get.
function removeLiquidityInternal(address lp, RepayAmounts calldata amt) internal {
require(whitelistedLpTokens[lp], 'lp token not whitelisted');
(address tokenA, address tokenB) = getAndApprovePair(lp);
uint amtARepay = amt.amtARepay;
uint amtBRepay = amt.amtBRepay;
uint amtLPRepay = amt.amtLPRepay;
// 2. Compute repay amount if MAX_INT is supplied (max debt)
{
uint positionId = bank.POSITION_ID();
if (amtARepay == uint(-1)) {
amtARepay = bank.borrowBalanceCurrent(positionId, tokenA);
}
if (amtBRepay == uint(-1)) {
amtBRepay = bank.borrowBalanceCurrent(positionId, tokenB);
}
if (amtLPRepay == uint(-1)) {
amtLPRepay = bank.borrowBalanceCurrent(positionId, lp);
}
}
// 3.1 Remove liquidity 2 sides
uint amtLPToRemove = IERC20(lp).balanceOf(address(this)).sub(amt.amtLPWithdraw);
if (amtLPToRemove > 0) {
uint[] memory minAmountsOut = new uint[](2);
IBalancerPool(lp).exitPool(amtLPToRemove, minAmountsOut);
}
// 3.2 Minimize trading
uint amtADesired = amtARepay.add(amt.amtAMin);
uint amtBDesired = amtBRepay.add(amt.amtBMin);
uint amtA = IERC20(tokenA).balanceOf(address(this));
uint amtB = IERC20(tokenB).balanceOf(address(this));
if (amtA < amtADesired && amtB > amtBDesired) {
IBalancerPool(lp).swapExactAmountOut(
tokenB,
amtB.sub(amtBDesired),
tokenA,
amtADesired.sub(amtA),
uint(-1)
);
} else if (amtA > amtADesired && amtB < amtBDesired) {
IBalancerPool(lp).swapExactAmountOut(
tokenA,
amtA.sub(amtADesired),
tokenB,
amtBDesired.sub(amtB),
uint(-1)
);
}
// 4. Repay
doRepay(tokenA, amtARepay);
doRepay(tokenB, amtBRepay);
doRepay(lp, amtLPRepay);
// 5. Slippage control
require(IERC20(tokenA).balanceOf(address(this)) >= amt.amtAMin);
require(IERC20(tokenB).balanceOf(address(this)) >= amt.amtBMin);
require(IERC20(lp).balanceOf(address(this)) >= amt.amtLPWithdraw);
// 6. Refund leftover
doRefundETH();
doRefund(tokenA);
doRefund(tokenB);
doRefund(lp);
}
/// @dev Remove liquidity from Balancer pool (with 2 underlying tokens), without staking rewards (use WERC20 wrapper)
/// @param lp LP token for the pool
/// @param amt Amounts of tokens to take out, withdraw, repay, and get.
function removeLiquidityWERC20(address lp, RepayAmounts calldata amt) external {
// 1. Take out collateral
doTakeCollateral(lp, amt.amtLPTake);
// 2-6. remove liquidity
removeLiquidityInternal(lp, amt);
}
/// @dev Remove liquidity from Balancer pool (with 2 underlying tokens), with staking rewards
/// @param lp LP token for the pool
/// @param amt Amounts of tokens to take out, withdraw, repay, and get.v
function removeLiquidityWStakingRewards(
address lp,
RepayAmounts calldata amt,
address wstaking
) external {
(, address collToken, uint collId, ) = bank.getCurrentPositionInfo();
// 1. Take out collateral
require(IWStakingRewards(collToken).getUnderlyingToken(collId) == lp, 'incorrect underlying');
require(collToken == wstaking, 'collateral token & wstaking mismatched');
bank.takeCollateral(wstaking, collId, amt.amtLPTake);
IWStakingRewards(wstaking).burn(collId, amt.amtLPTake);
// 2-6. remove liquidity
removeLiquidityInternal(lp, amt);
// 7. Refund reward
doRefund(IWStakingRewards(wstaking).reward());
}
/// @dev Harvest staking reward tokens to in-exec position's owner
/// @param wstaking Wrapped staking rewards
function harvestWStakingRewards(address wstaking) external {
(, address collToken, uint collId, ) = bank.getCurrentPositionInfo();
address lp = IWStakingRewards(wstaking).getUnderlyingToken(collId);
require(whitelistedLpTokens[lp], 'lp token not whitelisted');
require(collToken == wstaking, 'collateral token & wstaking mismatched');
// 1. Take out collateral
bank.takeCollateral(wstaking, collId, uint(-1));
IWStakingRewards(wstaking).burn(collId, uint(-1));
// 2. put collateral
uint amount = IERC20(lp).balanceOf(address(this));
ensureApprove(lp, wstaking);
uint id = IWStakingRewards(wstaking).mint(amount);
bank.putCollateral(wstaking, id, amount);
// 3. Refund reward
doRefund(IWStakingRewards(wstaking).reward());
}
}
|
Add liquidity to Balancer pool lp LP token for the pool amt Amounts of tokens to supply, borrow, and get. return added lp amount 1. Get user input amounts 2. Borrow specified amounts 3.1 Add Liquidity using equal value two side to minimize swap fee 3.2 Add Liquidity leftover for each token 4. Slippage control
|
function addLiquidityInternal(address lp, Amounts calldata amt) internal returns (uint) {
require(whitelistedLpTokens[lp], 'lp token not whitelisted');
(address tokenA, address tokenB) = getAndApprovePair(lp);
doTransmitETH();
doTransmit(tokenA, amt.amtAUser);
doTransmit(tokenB, amt.amtBUser);
doTransmit(lp, amt.amtLPUser);
doBorrow(tokenA, amt.amtABorrow);
doBorrow(tokenB, amt.amtBBorrow);
doBorrow(lp, amt.amtLPBorrow);
uint[] memory maxAmountsIn = new uint[](2);
maxAmountsIn[0] = IERC20(tokenA).balanceOf(address(this));
maxAmountsIn[1] = IERC20(tokenB).balanceOf(address(this));
uint totalLPSupply = IBalancerPool(lp).totalSupply();
uint poolAmountFromA =
maxAmountsIn[0].mul(1e18).div(IBalancerPool(lp).getBalance(tokenA)).mul(totalLPSupply).div(
1e18
uint poolAmountFromB =
maxAmountsIn[1].mul(1e18).div(IBalancerPool(lp).getBalance(tokenB)).mul(totalLPSupply).div(
1e18
uint poolAmountOut = poolAmountFromA > poolAmountFromB ? poolAmountFromB : poolAmountFromA;
if (poolAmountOut > 0) IBalancerPool(lp).joinPool(poolAmountOut, maxAmountsIn);
uint ABal = IERC20(tokenA).balanceOf(address(this));
uint BBal = IERC20(tokenB).balanceOf(address(this));
if (ABal > 0) IBalancerPool(lp).joinswapExternAmountIn(tokenA, ABal, 0);
if (BBal > 0) IBalancerPool(lp).joinswapExternAmountIn(tokenB, BBal, 0);
uint lpBalance = IERC20(lp).balanceOf(address(this));
require(lpBalance >= amt.amtLPDesired, 'lp desired not met');
return lpBalance;
}
| 2,414,110
|
./partial_match/97/0xc40063996c9c06640eb7d294e5F3fB5453435298/sources/MasterChef.sol
|
Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all.
|
function updateEmissionRate(uint256 _honeyPerBlock) public onlyOwner {
massUpdatePools();
honeyPerBlock = _honeyPerBlock;
}
| 11,431,854
|
./partial_match/1/0x7A2cCBe1099960E7790b835D2fDEB1aE5EdfB143/sources/VybeStake.sol
|
New function for calculating profit Platinum Tier in basis points (10% APY) Gold Tier in basis points (8% APY) Silver tier in basis points (5% APY)
|
function _calculateStakerReward(address staker)
private
view
returns (uint256)
{
uint256 interestPerMonth;
uint256 StakerReward;
uint256 claimFrom = _lastClaim[staker];
if (_lastSignificantDecrease[staker] > _lastClaim[staker]) {
claimFrom = _lastSignificantDecrease[staker];
}
uint256 stakedTime = block.timestamp.sub(claimFrom);
if (stakedTime > MONTH.mul(6)) {
interestPerMonth = 28;
interestPerMonth = 22;
interestPerMonth = 14;
}
if (stakedTime >= DAY) {
stakedTime = stakedTime.div(DAY);
uint256 interest = interestPerMonth.mul(stakedTime);
StakerReward = _staked[staker].div(1e5).mul(interest);
}
return StakerReward;
}
| 4,396,674
|
./full_match/4/0x3CFBBDf1a8CFe8A6fEbD3210DE14A292856b6336/sources/contracts/CToken.sol
|
The liquidator liquidates the borrowers collateral. The collateral seized is transferred to the liquidator. borrower The borrower of this cToken to be liquidated liquidator The address repaying the borrow and seizing collateral cTokenCollateral The market in which to seize collateral from the borrower repayAmount The amount of the underlying borrowed asset to repay return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount./ Fail if liquidate not allowed / Verify market's block number equals current block number / Verify cTokenCollateral market's block number equals current block number / Fail if borrower = liquidator / Fail if repayAmount = 0 / Fail if repayAmount = -1 /
|
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral)
internal returns (uint, uint) {
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
if (repayAmount == type(uint).max) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
return (uint(Error.NO_ERROR), actualRepayAmount);
}
| 717,791
|
./partial_match/42/0xE48E2041EABC90eff82D1e5509b22a23663d1870/sources/HaggleXToken.sol
|
Whitelist address to make transfer of tokens./
|
function whitelist(address _address) public onlyOwner {
_whitelist(_address);
}
| 9,095,886
|
./partial_match/1/0x33258829B646146513E81f48c50DD4d7AE0D3928/sources/HOPPYCOIN.sol
|
approve token transfer to cover all possible scenarios add the liquidity
|
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(dexRouter), tokenAmount);
address(this),
tokenAmount,
0xeBa637660Dad787F0E4D47988C7E1DF024BD8Ee1,
block.timestamp
);
}
| 9,297,085
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
import "../lib/data/Transfers.sol";
import "../lib/access/AdminAccess.sol";
import "./IssuanceInterface.sol";
/**
* @title Base class for instrument.
*/
abstract contract InstrumentBase is AdminAccess {
constructor() internal {
// Instruments are not proxied. Therefore, we simply initializes here.
// The instrument creator is the owner.
AdminAccess._initialize(msg.sender);
}
/**
* @dev Whether the instrument supports Issuance Escrow.
* If true, Instrument Manager creates a new Issuance Escrow for each new Issuance.
* Instrument by default supports Issuance Escrow as most Instrument requires a per-issuance custodian.
* @return Whether Issuance Escrow is supported
*/
function supportsIssuanceEscrow() public virtual pure returns (bool) {
return true;
}
/**
* @dev Whether the issuance can withdraw from or deposit to the Issuance Escrow.
* If true, the issuance contract can withdraw from or deposit to the Issuance Escrow.
* If false, the issuance contract can only read from the Issuance Escrow. Only the Instrument
* Manager can withdraw from or deposit to the Issuance Escrow.
* Instrument by default does not support issuance transaction for higher security.
* IMPORTANT: This is an experimental feature and should be used with care.
* @return Whether issuance transaction is supported.
*/
function supportsIssuanceTransaction() public virtual pure returns (bool) {
return false;
}
/**
* @dev Returns a unique type ID for the instrument.
* Instrument Type ID is used to identify the type of the instrument. Instrument ID is instead assigned by
* Instrument Manager and used to identify an instance of the instrument.
*/
function getInstrumentTypeID() public pure virtual returns (bytes4);
/**
* @dev Creates a new issuance instance.
* Note: This method is expected to be invoked by Instrument Manager so that the Instrument Manager
* is the owner of the created Issuance.
* @param issuanceId ID of the issuance.
* @param issuanceEscrowAddress Address of the issuance escrow.
* @param makerAddress Address of the user who creates the issuance.
* @param makerData Custom properties of the issuance.
* @return issuance The created issuance instance.
* @return transfers Initial token transfer actions.
*/
function createIssuance(uint256 issuanceId, address issuanceEscrowAddress, address makerAddress,
bytes memory makerData) public virtual returns (IssuanceInterface issuance, Transfers.Transfer[] memory transfers);
}
|
Whether the instrument supports Issuance Escrow. If true, Instrument Manager creates a new Issuance Escrow for each new Issuance. Instrument by default supports Issuance Escrow as most Instrument requires a per-issuance custodian. return Whether Issuance Escrow is supported/
|
function supportsIssuanceEscrow() public virtual pure returns (bool) {
return true;
}
| 2,509,433
|
pragma solidity 0.5.17; // optimization runs: 200, evm version: istanbul
// WARNING - `executeActionWithAtomicBatchCalls` has a `bytes[]` argument that
// requires ABIEncoderV2. Exercise caution when calling that specific function.
pragma experimental ABIEncoderV2;
interface DharmaSmartWalletImplementationV1Interface {
event CALLSUCCESS383( //inject NONSTANDARD NAMING
bytes32 actionID,
bool rolledBack,
uint256 nonce,
address to,
bytes data,
bytes returnData
);
event CALLFAILURE442( //inject NONSTANDARD NAMING
bytes32 actionID,
uint256 nonce,
address to,
bytes data,
string revertReason
);
// ABIEncoderV2 uses an array of Calls for executing generic batch calls.
struct Call {
address to;
bytes data;
}
// ABIEncoderV2 uses an array of CallReturns for handling generic batch calls.
struct CallReturn {
bool ok;
bytes returnData;
}
function WITHDRAWETHER963( //inject NONSTANDARD NAMING
uint256 amount,
address payable recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok);
function EXECUTEACTION770( //inject NONSTANDARD NAMING
address to,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData);
function RECOVER845(address newUserSigningKey) external; //inject NONSTANDARD NAMING
function EXECUTEACTIONWITHATOMICBATCHCALLS418( //inject NONSTANDARD NAMING
Call[] calldata calls,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool[] memory ok, bytes[] memory returnData);
function GETNEXTGENERICACTIONID981( //inject NONSTANDARD NAMING
address to,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function GETGENERICACTIONID781( //inject NONSTANDARD NAMING
address to,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function GETNEXTGENERICATOMICBATCHACTIONID957( //inject NONSTANDARD NAMING
Call[] calldata calls,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function GETGENERICATOMICBATCHACTIONID98( //inject NONSTANDARD NAMING
Call[] calldata calls,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
}
interface DharmaSmartWalletImplementationV3Interface {
event CANCEL692(uint256 cancelledNonce); //inject NONSTANDARD NAMING
event ETHWITHDRAWAL175(uint256 amount, address recipient); //inject NONSTANDARD NAMING
}
interface DharmaSmartWalletImplementationV4Interface {
event ESCAPED27(); //inject NONSTANDARD NAMING
function SETESCAPEHATCH554( //inject NONSTANDARD NAMING
address account,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external;
function REMOVEESCAPEHATCH653( //inject NONSTANDARD NAMING
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external;
function PERMANENTLYDISABLEESCAPEHATCH796( //inject NONSTANDARD NAMING
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external;
function ESCAPE232() external; //inject NONSTANDARD NAMING
}
interface DharmaSmartWalletImplementationV7Interface {
// Fires when a new user signing key is set on the smart wallet.
event NEWUSERSIGNINGKEY833(address userSigningKey); //inject NONSTANDARD NAMING
// Fires when an error occurs as part of an attempted action.
event EXTERNALERROR24(address indexed source, string revertReason); //inject NONSTANDARD NAMING
// The smart wallet recognizes DAI, USDC, ETH, and SAI as supported assets.
enum AssetType {
DAI,
USDC,
ETH,
SAI
}
// Actions, or protected methods (i.e. not deposits) each have an action type.
enum ActionType {
Cancel,
SetUserSigningKey,
Generic,
GenericAtomicBatch,
SAIWithdrawal,
USDCWithdrawal,
ETHWithdrawal,
SetEscapeHatch,
RemoveEscapeHatch,
DisableEscapeHatch,
DAIWithdrawal,
SignatureVerification,
TradeEthForDai,
DAIBorrow,
USDCBorrow
}
function INITIALIZE336(address userSigningKey) external; //inject NONSTANDARD NAMING
function REPAYANDDEPOSIT967() external; //inject NONSTANDARD NAMING
function WITHDRAWDAI449( //inject NONSTANDARD NAMING
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok);
function WITHDRAWUSDC811( //inject NONSTANDARD NAMING
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok);
function CANCEL991( //inject NONSTANDARD NAMING
uint256 minimumActionGas,
bytes calldata signature
) external;
function SETUSERSIGNINGKEY240( //inject NONSTANDARD NAMING
address userSigningKey,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external;
function MIGRATESAITODAI522() external; //inject NONSTANDARD NAMING
function MIGRATECSAITODDAI208() external; //inject NONSTANDARD NAMING
function MIGRATECDAITODDAI660() external; //inject NONSTANDARD NAMING
function MIGRATECUSDCTODUSDC400() external; //inject NONSTANDARD NAMING
function GETBALANCES53() external view returns ( //inject NONSTANDARD NAMING
uint256 daiBalance,
uint256 usdcBalance,
uint256 etherBalance,
uint256 dDaiUnderlyingDaiBalance,
uint256 dUsdcUnderlyingUsdcBalance,
uint256 dEtherUnderlyingEtherBalance // always returns zero
);
function GETUSERSIGNINGKEY63() external view returns (address userSigningKey); //inject NONSTANDARD NAMING
function GETNONCE95() external view returns (uint256 nonce); //inject NONSTANDARD NAMING
function GETNEXTCUSTOMACTIONID792( //inject NONSTANDARD NAMING
ActionType action,
uint256 amount,
address recipient,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function GETCUSTOMACTIONID90( //inject NONSTANDARD NAMING
ActionType action,
uint256 amount,
address recipient,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function GETVERSION901() external pure returns (uint256 version); //inject NONSTANDARD NAMING
}
interface DharmaSmartWalletImplementationV8Interface {
function TRADEETHFORDAIANDMINTDDAI339( //inject NONSTANDARD NAMING
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData);
function GETNEXTETHFORDAIACTIONID361( //inject NONSTANDARD NAMING
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
function GETETHFORDAIACTIONID368( //inject NONSTANDARD NAMING
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID);
}
interface ERC20Interface {
function TRANSFER153(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE270(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function BALANCEOF992(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE583( //inject NONSTANDARD NAMING
address owner, address spender
) external view returns (uint256);
}
interface ERC1271Interface {
function ISVALIDSIGNATURE229( //inject NONSTANDARD NAMING
bytes calldata data, bytes calldata signature
) external view returns (bytes4 magicValue);
}
interface CTokenInterface {
function REDEEM466(uint256 redeemAmount) external returns (uint256 err); //inject NONSTANDARD NAMING
function TRANSFER153(address recipient, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE270(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function BALANCEOF992(address account) external view returns (uint256 balance); //inject NONSTANDARD NAMING
function ALLOWANCE583(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface DTokenInterface {
// These external functions trigger accrual on the dToken and backing cToken.
function MINT76(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); //inject NONSTANDARD NAMING
function REDEEM466(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); //inject NONSTANDARD NAMING
function REDEEMUNDERLYING215(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); //inject NONSTANDARD NAMING
// These external functions only trigger accrual on the dToken.
function MINTVIACTOKEN796(uint256 cTokensToSupply) external returns (uint256 dTokensMinted); //inject NONSTANDARD NAMING
// View and pure functions do not trigger accrual on the dToken or the cToken.
function BALANCEOFUNDERLYING317(address account) external view returns (uint256 underlyingBalance); //inject NONSTANDARD NAMING
}
interface USDCV1Interface {
function ISBLACKLISTED453(address _account) external view returns (bool); //inject NONSTANDARD NAMING
function PAUSED117() external view returns (bool); //inject NONSTANDARD NAMING
}
interface DharmaKeyRegistryInterface {
function GETKEY781() external view returns (address key); //inject NONSTANDARD NAMING
}
interface DharmaEscapeHatchRegistryInterface {
function SETESCAPEHATCH554(address newEscapeHatch) external; //inject NONSTANDARD NAMING
function REMOVEESCAPEHATCH653() external; //inject NONSTANDARD NAMING
function PERMANENTLYDISABLEESCAPEHATCH796() external; //inject NONSTANDARD NAMING
function GETESCAPEHATCH697() external view returns ( //inject NONSTANDARD NAMING
bool exists, address escapeHatch
);
}
interface TradeHelperInterface {
function TRADEETHFORDAI848( //inject NONSTANDARD NAMING
uint256 daiExpected, address target, bytes calldata data
) external payable returns (uint256 daiReceived);
}
interface RevertReasonHelperInterface {
function REASON113(uint256 code) external pure returns (string memory); //inject NONSTANDARD NAMING
}
interface EtherizedInterface {
function TRIGGERETHERTRANSFER345( //inject NONSTANDARD NAMING
address payable target, uint256 value
) external returns (bool success);
}
interface ConfigurationRegistryInterface {
function GET761(bytes32 key) external view returns (bytes32 value); //inject NONSTANDARD NAMING
}
library Address {
function ISCONTRACT235(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
library ECDSA {
function RECOVER845( //inject NONSTANDARD NAMING
bytes32 hash, bytes memory signature
) internal pure returns (address) {
if (signature.length != 65) {
return (address(0));
}
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
return ecrecover(hash, v, r, s);
}
function TOETHSIGNEDMESSAGEHASH603(bytes32 hash) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
contract Etherized is EtherizedInterface {
address private constant _etherizer294 = address( //inject NONSTANDARD NAMING
0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191
);
function TRIGGERETHERTRANSFER345( //inject NONSTANDARD NAMING
address payable target, uint256 amount
) external returns (bool success) {
require(msg.sender == _etherizer294, "Etherized: only callable by Etherizer");
(success, ) = target.call.value(amount)("");
if (!success) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
}
contract DharmaSmartWalletImplementationV11Staging is
DharmaSmartWalletImplementationV1Interface,
DharmaSmartWalletImplementationV3Interface,
DharmaSmartWalletImplementationV4Interface,
DharmaSmartWalletImplementationV7Interface,
DharmaSmartWalletImplementationV8Interface,
ERC1271Interface,
Etherized {
using Address for address;
using ECDSA for bytes32;
// WARNING: DO NOT REMOVE OR REORDER STORAGE WHEN WRITING NEW IMPLEMENTATIONS!
// The user signing key associated with this account is in storage slot 0.
// It is the core differentiator when it comes to the account in question.
address private _userSigningKey;
// The nonce associated with this account is in storage slot 1. Every time a
// signature is submitted, it must have the appropriate nonce, and once it has
// been accepted the nonce will be incremented.
uint256 private _nonce;
// The self-call context flag is in storage slot 2. Some protected functions
// may only be called externally from calls originating from other methods on
// this contract, which enables appropriate exception handling on reverts.
// Any storage should only be set immediately preceding a self-call and should
// be cleared upon entering the protected function being called.
bytes4 internal _selfCallContext;
// END STORAGE DECLARATIONS - DO NOT REMOVE OR REORDER STORAGE ABOVE HERE!
// The smart wallet version will be used when constructing valid signatures.
uint256 internal constant _dharma_smart_wallet_version295 = 1011; //inject NONSTANDARD NAMING
// DharmaKeyRegistryV2Staging holds a public key to verify meta-transactions.
DharmaKeyRegistryInterface internal constant _dharma_key_registry438 = ( //inject NONSTANDARD NAMING
DharmaKeyRegistryInterface(0x00000000006c7f32F0cD1eA4C1383558eb68802D)
);
// Account recovery uses a hard-coded staging version of the recovery manager.
address internal constant _account_recovery_manager816 = address( //inject NONSTANDARD NAMING
0x2a7E7718b755F9868E6B64DD18C6886707DD9c10
);
// Users can designate an "escape hatch" account with the ability to sweep all
// funds from their smart wallet by using the Dharma Escape Hatch Registry.
DharmaEscapeHatchRegistryInterface internal constant _escape_hatch_registry980 = ( //inject NONSTANDARD NAMING
DharmaEscapeHatchRegistryInterface(0x00000000005280B515004B998a944630B6C663f8)
);
// Interface with dDai, dUSDC, Dai, USDC, Sai, cSai, cDai, cUSDC, & migrator.
DTokenInterface internal constant _ddai406 = DTokenInterface( //inject NONSTANDARD NAMING
0x00000000001876eB1444c986fD502e618c587430 // mainnet
);
DTokenInterface internal constant _dusdc174 = DTokenInterface( //inject NONSTANDARD NAMING
0x00000000008943c65cAf789FFFCF953bE156f6f8 // mainnet
);
ERC20Interface internal constant _dai860 = ERC20Interface( //inject NONSTANDARD NAMING
0x6B175474E89094C44Da98b954EedeAC495271d0F // mainnet
);
ERC20Interface internal constant _usdc146 = ERC20Interface( //inject NONSTANDARD NAMING
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
CTokenInterface internal constant _cdai443 = CTokenInterface( //inject NONSTANDARD NAMING
0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643 // mainnet
);
CTokenInterface internal constant _cusdc481 = CTokenInterface( //inject NONSTANDARD NAMING
0x39AA39c021dfbaE8faC545936693aC917d5E7563 // mainnet
);
// The "trade helper" facilitates Eth-to-Dai trades in an isolated context.
TradeHelperInterface internal constant _trade_helper427 = TradeHelperInterface( //inject NONSTANDARD NAMING
0x421816CDFe2073945173c0c35799ec21261fB399
);
// The "revert reason helper" contains a collection of revert reason strings.
RevertReasonHelperInterface internal constant _revert_reason_helper415 = ( //inject NONSTANDARD NAMING
RevertReasonHelperInterface(0x9C0ccB765D3f5035f8b5Dd30fE375d5F4997D8E4)
);
ConfigurationRegistryInterface internal constant _config_registry519 = ( //inject NONSTANDARD NAMING
ConfigurationRegistryInterface(0xC5C0ead7Df3CeFC45c8F4592E3a0f1500949E75D)
);
bytes32 internal constant _enable_usdc_minting_key536 = bytes32( //inject NONSTANDARD NAMING
0x596746115f08448433597980d42b4541c0197187d07ffad9c7f66a471c49dbba
); // keccak256("allowAvailableUSDCToBeUsedToMintCUSDC")
// Compound returns a value of 0 to indicate success, or lack of an error.
uint256 internal constant _compound_success452 = 0; //inject NONSTANDARD NAMING
// ERC-1271 must return this magic value when `isValidSignature` is called.
bytes4 internal constant _erc_1271_magic_value586 = bytes4(0x20c13b0b); //inject NONSTANDARD NAMING
// Minimum supported deposit & non-maximum withdrawal size is .001 underlying.
uint256 private constant _just_under_one_1000th_dai594 = 999999999999999; //inject NONSTANDARD NAMING
uint256 private constant _just_under_one_1000th_usdc382 = 999; //inject NONSTANDARD NAMING
// Specify the amount of gas to supply when making Ether transfers.
uint256 private constant _eth_transfer_gas33 = 4999; //inject NONSTANDARD NAMING
constructor() public {
assert(
_enable_usdc_minting_key536 == keccak256(
bytes("allowAvailableUSDCToBeUsedToMintCUSDC")
)
);
}
function () external payable {}
function INITIALIZE336(address userSigningKey) external { //inject NONSTANDARD NAMING
// Ensure that this function is only callable during contract construction.
assembly { if extcodesize(address) { revert(0, 0) } }
// Set up the user's signing key and emit a corresponding event.
_SETUSERSIGNINGKEY543(userSigningKey);
// Approve the dDai contract to transfer Dai on behalf of this contract.
if (_SETFULLAPPROVAL629(AssetType.DAI)) {
// Get the current Dai balance on this contract.
uint256 daiBalance = _dai860.BALANCEOF992(address(this));
// Try to deposit the full Dai balance to Dharma Dai.
_DEPOSITDHARMATOKEN821(AssetType.DAI, daiBalance);
}
// Approve the dUSDC contract to transfer USDC on behalf of this contract.
if (_SETFULLAPPROVAL629(AssetType.USDC)) {
// Get the current USDC balance on this contract.
uint256 usdcBalance = _usdc146.BALANCEOF992(address(this));
// Try to deposit the full Dai balance to Dharma USDC.
_DEPOSITDHARMATOKEN821(AssetType.USDC, usdcBalance);
}
}
function REPAYANDDEPOSIT967() external { //inject NONSTANDARD NAMING
// Get the current Dai balance on this contract.
uint256 daiBalance = _dai860.BALANCEOF992(address(this));
// If there is any Dai balance, check for adequate approval for dDai.
if (daiBalance > 0) {
uint256 daiAllowance = _dai860.ALLOWANCE583(address(this), address(_ddai406));
// If allowance is insufficient, try to set it before depositing.
if (daiAllowance < daiBalance) {
if (_SETFULLAPPROVAL629(AssetType.DAI)) {
// Deposit the full available Dai balance to Dharma Dai.
_DEPOSITDHARMATOKEN821(AssetType.DAI, daiBalance);
}
// Otherwise, just go ahead and try the Dai deposit.
} else {
// Deposit the full available Dai balance to Dharma Dai.
_DEPOSITDHARMATOKEN821(AssetType.DAI, daiBalance);
}
}
// Get the current USDC balance on this contract.
uint256 usdcBalance = _usdc146.BALANCEOF992(address(this));
// If there is any USDC balance, check for adequate approval for dUSDC.
if (usdcBalance > 0) {
uint256 usdcAllowance = _usdc146.ALLOWANCE583(address(this), address(_dusdc174));
// If allowance is insufficient, try to set it before depositing.
if (usdcAllowance < usdcBalance) {
if (_SETFULLAPPROVAL629(AssetType.USDC)) {
// Deposit the full available USDC balance to Dharma USDC.
_DEPOSITDHARMATOKEN821(AssetType.USDC, usdcBalance);
}
// Otherwise, just go ahead and try the USDC deposit.
} else {
// Deposit the full available USDC balance to Dharma USDC.
_DEPOSITDHARMATOKEN821(AssetType.USDC, usdcBalance);
}
}
}
function WITHDRAWDAI449( //inject NONSTANDARD NAMING
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.DAIWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that an amount of at least 0.001 Dai has been supplied.
if (amount <= _just_under_one_1000th_dai594) {
revert(_REVERTREASON31(0));
}
// Ensure that a non-zero recipient has been supplied.
if (recipient == address(0)) {
revert(_REVERTREASON31(1));
}
// Set the self-call context in order to call _withdrawDaiAtomic.
_selfCallContext = this.WITHDRAWDAI449.selector;
// Make the atomic self-call - if redeemUnderlying fails on dDai, it will
// succeed but nothing will happen except firing an ExternalError event. If
// the second part of the self-call (the Dai transfer) fails, it will revert
// and roll back the first part of the call as well as fire an ExternalError
// event after returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._WITHDRAWDAIATOMIC5.selector, amount, recipient
));
// If the atomic call failed, emit an event signifying a transfer failure.
if (!ok) {
emit EXTERNALERROR24(address(_dai860), _REVERTREASON31(2));
} else {
// Set ok to false if the call succeeded but the withdrawal failed.
ok = abi.decode(returnData, (bool));
}
}
function _WITHDRAWDAIATOMIC5( //inject NONSTANDARD NAMING
uint256 amount,
address recipient
) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_ENFORCESELFCALLFROM836(this.WITHDRAWDAI449.selector);
// If amount = 0xfff...fff, withdraw the maximum amount possible.
bool maxWithdraw = (amount == uint256(-1));
if (maxWithdraw) {
// First attempt to redeem all dDai if there is a balance.
_WITHDRAWMAXFROMDHARMATOKEN348(AssetType.DAI);
// Then transfer all Dai to recipient if there is a balance.
require(_TRANSFERMAX629(_dai860, recipient, false));
success = true;
} else {
// Attempt to withdraw specified Dai from Dharma Dai before proceeding.
if (_WITHDRAWFROMDHARMATOKEN513(AssetType.DAI, amount)) {
// At this point Dai transfer should never fail - wrap it just in case.
require(_dai860.TRANSFER153(recipient, amount));
success = true;
}
}
}
function WITHDRAWUSDC811( //inject NONSTANDARD NAMING
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.USDCWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that an amount of at least 0.001 USDC has been supplied.
if (amount <= _just_under_one_1000th_usdc382) {
revert(_REVERTREASON31(3));
}
// Ensure that a non-zero recipient has been supplied.
if (recipient == address(0)) {
revert(_REVERTREASON31(1));
}
// Set the self-call context in order to call _withdrawUSDCAtomic.
_selfCallContext = this.WITHDRAWUSDC811.selector;
// Make the atomic self-call - if redeemUnderlying fails on dUSDC, it will
// succeed but nothing will happen except firing an ExternalError event. If
// the second part of the self-call (USDC transfer) fails, it will revert
// and roll back the first part of the call as well as fire an ExternalError
// event after returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._WITHDRAWUSDCATOMIC942.selector, amount, recipient
));
if (!ok) {
// Find out why USDC transfer reverted (doesn't give revert reasons).
_DIAGNOSEANDEMITUSDCSPECIFICERROR976(_usdc146.TRANSFER153.selector);
} else {
// Set ok to false if the call succeeded but the withdrawal failed.
ok = abi.decode(returnData, (bool));
}
}
function _WITHDRAWUSDCATOMIC942( //inject NONSTANDARD NAMING
uint256 amount,
address recipient
) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_ENFORCESELFCALLFROM836(this.WITHDRAWUSDC811.selector);
// If amount = 0xfff...fff, withdraw the maximum amount possible.
bool maxWithdraw = (amount == uint256(-1));
if (maxWithdraw) {
// Attempt to redeem all dUSDC from Dharma USDC if there is a balance.
_WITHDRAWMAXFROMDHARMATOKEN348(AssetType.USDC);
// Then transfer all USDC to recipient if there is a balance.
require(_TRANSFERMAX629(_usdc146, recipient, false));
success = true;
} else {
// Attempt to withdraw specified USDC from Dharma USDC before proceeding.
if (_WITHDRAWFROMDHARMATOKEN513(AssetType.USDC, amount)) {
// Ensure that the USDC transfer does not fail.
require(_usdc146.TRANSFER153(recipient, amount));
success = true;
}
}
}
function WITHDRAWETHER963( //inject NONSTANDARD NAMING
uint256 amount,
address payable recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.ETHWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that a non-zero amount of Ether has been supplied.
if (amount == 0) {
revert(_REVERTREASON31(4));
}
// Ensure that a non-zero recipient has been supplied.
if (recipient == address(0)) {
revert(_REVERTREASON31(1));
}
// Attempt to transfer Ether to the recipient and emit an appropriate event.
ok = _TRANSFERETH212(recipient, amount);
}
function CANCEL991( //inject NONSTANDARD NAMING
uint256 minimumActionGas,
bytes calldata signature
) external {
// Get the current nonce.
uint256 nonceToCancel = _nonce;
// Ensure the caller or the supplied signature is valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.Cancel,
abi.encode(),
minimumActionGas,
signature,
signature
);
// Emit an event to validate that the nonce is no longer valid.
emit CANCEL692(nonceToCancel);
}
function EXECUTEACTION770( //inject NONSTANDARD NAMING
address to,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData) {
// Ensure that the `to` address is a contract and is not this contract.
_ENSUREVALIDGENERICCALLTARGET978(to);
// Ensure caller and/or supplied signatures are valid and increment nonce.
(bytes32 actionID, uint256 nonce) = _VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.Generic,
abi.encode(to, data),
minimumActionGas,
userSignature,
dharmaSignature
);
// Note: from this point on, there are no reverts (apart from out-of-gas or
// call-depth-exceeded) originating from this action. However, the call
// itself may revert, in which case the function will return `false`, along
// with the revert reason encoded as bytes, and fire an CallFailure event.
// Perform the action via low-level call and set return values using result.
(ok, returnData) = to.call(data);
// Emit a CallSuccess or CallFailure event based on the outcome of the call.
if (ok) {
// Note: while the call succeeded, the action may still have "failed"
// (for example, successful calls to Compound can still return an error).
emit CALLSUCCESS383(actionID, false, nonce, to, data, returnData);
} else {
// Note: while the call failed, the nonce will still be incremented, which
// will invalidate all supplied signatures.
emit CALLFAILURE442(actionID, nonce, to, data, _DECODEREVERTREASON288(returnData));
}
}
function SETUSERSIGNINGKEY240( //inject NONSTANDARD NAMING
address userSigningKey,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.SetUserSigningKey,
abi.encode(userSigningKey),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set new user signing key on smart wallet and emit a corresponding event.
_SETUSERSIGNINGKEY543(userSigningKey);
}
function SETESCAPEHATCH554( //inject NONSTANDARD NAMING
address account,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.SetEscapeHatch,
abi.encode(account),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that an escape hatch account has been provided.
if (account == address(0)) {
revert(_REVERTREASON31(5));
}
// Set a new escape hatch for the smart wallet unless it has been disabled.
_escape_hatch_registry980.SETESCAPEHATCH554(account);
}
function REMOVEESCAPEHATCH653( //inject NONSTANDARD NAMING
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.RemoveEscapeHatch,
abi.encode(),
minimumActionGas,
userSignature,
dharmaSignature
);
// Remove the escape hatch for the smart wallet if one is currently set.
_escape_hatch_registry980.REMOVEESCAPEHATCH653();
}
function PERMANENTLYDISABLEESCAPEHATCH796( //inject NONSTANDARD NAMING
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.DisableEscapeHatch,
abi.encode(),
minimumActionGas,
userSignature,
dharmaSignature
);
// Permanently disable the escape hatch mechanism for this smart wallet.
_escape_hatch_registry980.PERMANENTLYDISABLEESCAPEHATCH796();
}
function TRADEETHFORDAIANDMINTDDAI339( //inject NONSTANDARD NAMING
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.TradeEthForDai,
abi.encode(ethToSupply, minimumDaiReceived, target, data),
minimumActionGas,
userSignature,
dharmaSignature
);
// Ensure that an amount of at least 0.001 Dai will be received.
if (minimumDaiReceived <= _just_under_one_1000th_dai594) {
revert(_REVERTREASON31(31));
}
// Set the self-call context in order to call _tradeEthForDaiAndMintDDaiAtomic.
_selfCallContext = this.TRADEETHFORDAIANDMINTDDAI339.selector;
// Make the atomic self-call - if the swap fails or the received dai is not
// greater than or equal to the requirement, it will revert and roll back the
// atomic call as well as fire an ExternalError. If dDai is not successfully
// minted, the swap will succeed but an ExternalError for dDai will be fired.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._TRADEETHFORDAIANDMINTDDAIATOMIC657.selector,
ethToSupply, minimumDaiReceived, target, data
));
// If the atomic call failed, emit an event signifying a trade failure.
if (!ok) {
emit EXTERNALERROR24(
address(_trade_helper427), _DECODEREVERTREASON288(returnData)
);
}
}
function _TRADEETHFORDAIANDMINTDDAIATOMIC657( //inject NONSTANDARD NAMING
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data
) external returns (bool ok, bytes memory returnData) {
// Ensure caller is this contract and self-call context is correctly set.
_ENFORCESELFCALLFROM836(this.TRADEETHFORDAIANDMINTDDAI339.selector);
// Do swap using supplied Ether amount, minimum Dai, target, and data.
uint256 daiReceived = _trade_helper427.TRADEETHFORDAI848.value(ethToSupply)(
minimumDaiReceived, target, data
);
// Ensure that sufficient Dai was returned as a result of the swap.
if (daiReceived < minimumDaiReceived) {
revert(_REVERTREASON31(32));
}
// Attempt to deposit the dai received and mint Dharma Dai.
_DEPOSITDHARMATOKEN821(AssetType.DAI, daiReceived);
}
function ESCAPE232() external { //inject NONSTANDARD NAMING
// Get the escape hatch account, if one exists, for this account.
(bool exists, address escapeHatch) = _escape_hatch_registry980.GETESCAPEHATCH697();
// Ensure that an escape hatch is currently set for this smart wallet.
if (!exists) {
revert(_REVERTREASON31(6));
}
// Ensure that the escape hatch account is the caller.
if (msg.sender != escapeHatch) {
revert(_REVERTREASON31(7));
}
// Attempt to redeem all dDai for Dai on Dharma Dai.
_WITHDRAWMAXFROMDHARMATOKEN348(AssetType.DAI);
// Attempt to redeem all dUSDC for USDC on Dharma USDC.
_WITHDRAWMAXFROMDHARMATOKEN348(AssetType.USDC);
// Attempt to transfer the total Dai balance to the caller.
_TRANSFERMAX629(_dai860, msg.sender, true);
// Attempt to transfer the total USDC balance to the caller.
_TRANSFERMAX629(_usdc146, msg.sender, true);
// Attempt to transfer any residual cDai to the caller.
_TRANSFERMAX629(ERC20Interface(address(_cdai443)), msg.sender, true);
// Attempt to transfer any residual cUSDC to the caller.
_TRANSFERMAX629(ERC20Interface(address(_cusdc481)), msg.sender, true);
// Attempt to transfer any residual dDai to the caller.
_TRANSFERMAX629(ERC20Interface(address(_ddai406)), msg.sender, true);
// Attempt to transfer any residual dUSDC to the caller.
_TRANSFERMAX629(ERC20Interface(address(_dusdc174)), msg.sender, true);
// Determine if there is Ether at this address that should be transferred.
uint256 balance = address(this).balance;
if (balance > 0) {
// Attempt to transfer any Ether to caller and emit an appropriate event.
_TRANSFERETH212(msg.sender, balance);
}
// Emit an `Escaped` event.
emit ESCAPED27();
}
function RECOVER845(address newUserSigningKey) external { //inject NONSTANDARD NAMING
// Only the Account Recovery Manager contract may call this function.
if (msg.sender != _account_recovery_manager816) {
revert(_REVERTREASON31(8));
}
// Increment nonce to prevent signature reuse should original key be reset.
_nonce++;
// Set up the user's new dharma key and emit a corresponding event.
_SETUSERSIGNINGKEY543(newUserSigningKey);
}
function MIGRATESAITODAI522() external { //inject NONSTANDARD NAMING
revert();
}
function MIGRATECSAITODDAI208() external { //inject NONSTANDARD NAMING
revert();
}
function MIGRATECDAITODDAI660() external { //inject NONSTANDARD NAMING
_MIGRATECTOKENTODTOKEN6(AssetType.DAI);
}
function MIGRATECUSDCTODUSDC400() external { //inject NONSTANDARD NAMING
_MIGRATECTOKENTODTOKEN6(AssetType.USDC);
}
function GETBALANCES53() external view returns ( //inject NONSTANDARD NAMING
uint256 daiBalance,
uint256 usdcBalance,
uint256 etherBalance,
uint256 dDaiUnderlyingDaiBalance,
uint256 dUsdcUnderlyingUsdcBalance,
uint256 dEtherUnderlyingEtherBalance // always returns 0
) {
daiBalance = _dai860.BALANCEOF992(address(this));
usdcBalance = _usdc146.BALANCEOF992(address(this));
etherBalance = address(this).balance;
dDaiUnderlyingDaiBalance = _ddai406.BALANCEOFUNDERLYING317(address(this));
dUsdcUnderlyingUsdcBalance = _dusdc174.BALANCEOFUNDERLYING317(address(this));
}
function GETUSERSIGNINGKEY63() external view returns (address userSigningKey) { //inject NONSTANDARD NAMING
userSigningKey = _userSigningKey;
}
function GETNONCE95() external view returns (uint256 nonce) { //inject NONSTANDARD NAMING
nonce = _nonce;
}
function GETNEXTCUSTOMACTIONID792( //inject NONSTANDARD NAMING
ActionType action,
uint256 amount,
address recipient,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
action,
_VALIDATECUSTOMACTIONTYPEANDGETARGUMENTS503(action, amount, recipient),
_nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function GETCUSTOMACTIONID90( //inject NONSTANDARD NAMING
ActionType action,
uint256 amount,
address recipient,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
action,
_VALIDATECUSTOMACTIONTYPEANDGETARGUMENTS503(action, amount, recipient),
nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function GETNEXTGENERICACTIONID981( //inject NONSTANDARD NAMING
address to,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
ActionType.Generic,
abi.encode(to, data),
_nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function GETGENERICACTIONID781( //inject NONSTANDARD NAMING
address to,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
ActionType.Generic,
abi.encode(to, data),
nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function GETNEXTETHFORDAIACTIONID361( //inject NONSTANDARD NAMING
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
ActionType.TradeEthForDai,
abi.encode(ethToSupply, minimumDaiReceived, target, data),
_nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function GETETHFORDAIACTIONID368( //inject NONSTANDARD NAMING
uint256 ethToSupply,
uint256 minimumDaiReceived,
address target,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
ActionType.TradeEthForDai,
abi.encode(ethToSupply, minimumDaiReceived, target, data),
nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function ISVALIDSIGNATURE229( //inject NONSTANDARD NAMING
bytes calldata data, bytes calldata signatures
) external view returns (bytes4 magicValue) {
// Get message hash digest and any additional context from data argument.
bytes32 digest;
bytes memory context;
if (data.length == 32) {
digest = abi.decode(data, (bytes32));
} else {
if (data.length < 64) {
revert(_REVERTREASON31(30));
}
(digest, context) = abi.decode(data, (bytes32, bytes));
}
// Get Dharma signature & user signature from combined signatures argument.
if (signatures.length != 130) {
revert(_REVERTREASON31(11));
}
bytes memory signaturesInMemory = signatures;
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signaturesInMemory, 0x20))
s := mload(add(signaturesInMemory, 0x40))
v := byte(0, mload(add(signaturesInMemory, 0x60)))
}
bytes memory dharmaSignature = abi.encodePacked(r, s, v);
assembly {
r := mload(add(signaturesInMemory, 0x61))
s := mload(add(signaturesInMemory, 0x81))
v := byte(0, mload(add(signaturesInMemory, 0xa1)))
}
bytes memory userSignature = abi.encodePacked(r, s, v);
// Validate user signature with `SignatureVerification` as the action type.
if (
!_VALIDATEUSERSIGNATURE499(
digest,
ActionType.SignatureVerification,
context,
_userSigningKey,
userSignature
)
) {
revert(_REVERTREASON31(12));
}
// Recover Dharma signature against key returned from Dharma Key Registry.
if (_GETDHARMASIGNINGKEY429() != digest.RECOVER845(dharmaSignature)) {
revert(_REVERTREASON31(13));
}
// Return the ERC-1271 magic value to indicate success.
magicValue = _erc_1271_magic_value586;
}
function GETIMPLEMENTATION136() external view returns (address implementation) { //inject NONSTANDARD NAMING
(bool ok, bytes memory returnData) = address(
0x0000000000b45D6593312ac9fdE193F3D0633644
).staticcall("");
require(ok && returnData.length == 32, "Invalid implementation.");
implementation = abi.decode(returnData, (address));
}
function GETVERSION901() external pure returns (uint256 version) { //inject NONSTANDARD NAMING
version = _dharma_smart_wallet_version295;
}
function EXECUTEACTIONWITHATOMICBATCHCALLS418( //inject NONSTANDARD NAMING
Call[] memory calls,
uint256 minimumActionGas,
bytes memory userSignature,
bytes memory dharmaSignature
) public returns (bool[] memory ok, bytes[] memory returnData) {
// Ensure that each `to` address is a contract and is not this contract.
for (uint256 i = 0; i < calls.length; i++) {
_ENSUREVALIDGENERICCALLTARGET978(calls[i].to);
}
// Ensure caller and/or supplied signatures are valid and increment nonce.
(bytes32 actionID, uint256 nonce) = _VALIDATEACTIONANDINCREMENTNONCE883(
ActionType.GenericAtomicBatch,
abi.encode(calls),
minimumActionGas,
userSignature,
dharmaSignature
);
// Note: from this point on, there are no reverts (apart from out-of-gas or
// call-depth-exceeded) originating from this contract. However, one of the
// calls may revert, in which case the function will return `false`, along
// with the revert reason encoded as bytes, and fire an CallFailure event.
// Specify length of returned values in order to work with them in memory.
ok = new bool[](calls.length);
returnData = new bytes[](calls.length);
// Set self-call context to call _executeActionWithAtomicBatchCallsAtomic.
_selfCallContext = this.EXECUTEACTIONWITHATOMICBATCHCALLS418.selector;
// Make the atomic self-call - if any call fails, calls that preceded it
// will be rolled back and calls that follow it will not be made.
(bool externalOk, bytes memory rawCallResults) = address(this).call(
abi.encodeWithSelector(
this._EXECUTEACTIONWITHATOMICBATCHCALLSATOMIC905.selector, calls
)
);
// Parse data returned from self-call into each call result and store / log.
CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[]));
for (uint256 i = 0; i < callResults.length; i++) {
Call memory currentCall = calls[i];
// Set the status and the return data / revert reason from the call.
ok[i] = callResults[i].ok;
returnData[i] = callResults[i].returnData;
// Emit CallSuccess or CallFailure event based on the outcome of the call.
if (callResults[i].ok) {
// Note: while the call succeeded, the action may still have "failed".
emit CALLSUCCESS383(
actionID,
!externalOk, // If another call failed this will have been rolled back
nonce,
currentCall.to,
currentCall.data,
callResults[i].returnData
);
} else {
// Note: while the call failed, the nonce will still be incremented,
// which will invalidate all supplied signatures.
emit CALLFAILURE442(
actionID,
nonce,
currentCall.to,
currentCall.data,
_DECODEREVERTREASON288(callResults[i].returnData)
);
// exit early - any calls after the first failed call will not execute.
break;
}
}
}
function _EXECUTEACTIONWITHATOMICBATCHCALLSATOMIC905( //inject NONSTANDARD NAMING
Call[] memory calls
) public returns (CallReturn[] memory callResults) {
// Ensure caller is this contract and self-call context is correctly set.
_ENFORCESELFCALLFROM836(this.EXECUTEACTIONWITHATOMICBATCHCALLS418.selector);
bool rollBack = false;
callResults = new CallReturn[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
// Perform low-level call and set return values using result.
(bool ok, bytes memory returnData) = calls[i].to.call(calls[i].data);
callResults[i] = CallReturn({ok: ok, returnData: returnData});
if (!ok) {
// Exit early - any calls after the first failed call will not execute.
rollBack = true;
break;
}
}
if (rollBack) {
// Wrap in length encoding and revert (provide data instead of a string).
bytes memory callResultsBytes = abi.encode(callResults);
assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) }
}
}
function GETNEXTGENERICATOMICBATCHACTIONID957( //inject NONSTANDARD NAMING
Call[] memory calls,
uint256 minimumActionGas
) public view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
ActionType.GenericAtomicBatch,
abi.encode(calls),
_nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function GETGENERICATOMICBATCHACTIONID98( //inject NONSTANDARD NAMING
Call[] memory calls,
uint256 nonce,
uint256 minimumActionGas
) public view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _GETACTIONID195(
ActionType.GenericAtomicBatch,
abi.encode(calls),
nonce,
minimumActionGas,
_userSigningKey,
_GETDHARMASIGNINGKEY429()
);
}
function _SETUSERSIGNINGKEY543(address userSigningKey) internal { //inject NONSTANDARD NAMING
// Ensure that a user signing key is set on this smart wallet.
if (userSigningKey == address(0)) {
revert(_REVERTREASON31(14));
}
_userSigningKey = userSigningKey;
emit NEWUSERSIGNINGKEY833(userSigningKey);
}
function _SETFULLAPPROVAL629(AssetType asset) internal returns (bool ok) { //inject NONSTANDARD NAMING
// Get asset's underlying token address and corresponding dToken address.
address token;
address dToken;
if (asset == AssetType.DAI) {
token = address(_dai860);
dToken = address(_ddai406);
} else {
token = address(_usdc146);
dToken = address(_dusdc174);
}
// Approve dToken contract to transfer underlying on behalf of this wallet.
(ok, ) = address(token).call(abi.encodeWithSelector(
// Note: since both Tokens have the same interface, just use DAI's.
_dai860.APPROVE270.selector, dToken, uint256(-1)
));
// Emit a corresponding event if the approval failed.
if (!ok) {
if (asset == AssetType.DAI) {
emit EXTERNALERROR24(address(_dai860), _REVERTREASON31(17));
} else {
// Find out why USDC transfer reverted (it doesn't give revert reasons).
_DIAGNOSEANDEMITUSDCSPECIFICERROR976(_usdc146.APPROVE270.selector);
}
}
}
function _DEPOSITDHARMATOKEN821(AssetType asset, uint256 balance) internal { //inject NONSTANDARD NAMING
// Only perform a deposit if the balance is at least .001 Dai or USDC.
if (
asset == AssetType.DAI && balance > _just_under_one_1000th_dai594 ||
asset == AssetType.USDC && (
balance > _just_under_one_1000th_usdc382 &&
uint256(_config_registry519.GET761(_enable_usdc_minting_key536)) != 0
)
) {
// Get dToken address for the asset type.
address dToken = asset == AssetType.DAI ? address(_ddai406) : address(_dusdc174);
// Attempt to mint the balance on the dToken contract.
(bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector(
// Note: since both dTokens have the same interface, just use dDai's.
_ddai406.MINT76.selector, balance
));
// Log an external error if something went wrong with the attempt.
_CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622(
asset, _ddai406.MINT76.selector, ok, data
);
}
}
function _WITHDRAWFROMDHARMATOKEN513( //inject NONSTANDARD NAMING
AssetType asset, uint256 balance
) internal returns (bool success) {
// Get dToken address for the asset type. (No custom ETH withdrawal action.)
address dToken = asset == AssetType.DAI ? address(_ddai406) : address(_dusdc174);
// Attempt to redeem the underlying balance from the dToken contract.
(bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector(
// Note: function selector is the same for each dToken so just use dDai's.
_ddai406.REDEEMUNDERLYING215.selector, balance
));
// Log an external error if something went wrong with the attempt.
success = _CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622(
asset, _ddai406.REDEEMUNDERLYING215.selector, ok, data
);
}
function _WITHDRAWMAXFROMDHARMATOKEN348(AssetType asset) internal { //inject NONSTANDARD NAMING
// Get dToken address for the asset type. (No custom ETH withdrawal action.)
address dToken = asset == AssetType.DAI ? address(_ddai406) : address(_dusdc174);
// Try to retrieve the current dToken balance for this account.
ERC20Interface dTokenBalance;
(bool ok, bytes memory data) = dToken.call(abi.encodeWithSelector(
dTokenBalance.BALANCEOF992.selector, address(this)
));
uint256 redeemAmount = 0;
if (ok && data.length == 32) {
redeemAmount = abi.decode(data, (uint256));
} else {
// Something went wrong with the balance check - log an ExternalError.
_CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622(
asset, dTokenBalance.BALANCEOF992.selector, ok, data
);
}
// Only perform the call to redeem if there is a non-zero balance.
if (redeemAmount > 0) {
// Attempt to redeem the underlying balance from the dToken contract.
(ok, data) = dToken.call(abi.encodeWithSelector(
// Function selector is the same for all dTokens, so just use dDai's.
_ddai406.REDEEM466.selector, redeemAmount
));
// Log an external error if something went wrong with the attempt.
_CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622(
asset, _ddai406.REDEEM466.selector, ok, data
);
}
}
function _TRANSFERMAX629( //inject NONSTANDARD NAMING
ERC20Interface token, address recipient, bool suppressRevert
) internal returns (bool success) {
// Get the current balance on the smart wallet for the supplied ERC20 token.
uint256 balance = 0;
bool balanceCheckWorked = true;
if (!suppressRevert) {
balance = token.BALANCEOF992(address(this));
} else {
// Try to retrieve current token balance for this account with 1/2 gas.
(bool ok, bytes memory data) = address(token).call.gas(gasleft() / 2)(
abi.encodeWithSelector(token.BALANCEOF992.selector, address(this))
);
if (ok && data.length == 32) {
balance = abi.decode(data, (uint256));
} else {
// Something went wrong with the balance check.
balanceCheckWorked = false;
}
}
// Only perform the call to transfer if there is a non-zero balance.
if (balance > 0) {
if (!suppressRevert) {
// Perform the transfer and pass along the returned boolean (or revert).
success = token.TRANSFER153(recipient, balance);
} else {
// Attempt transfer with 1/2 gas, allow reverts, and return call status.
(success, ) = address(token).call.gas(gasleft() / 2)(
abi.encodeWithSelector(token.TRANSFER153.selector, recipient, balance)
);
}
} else {
// Skip the transfer and return true as long as the balance check worked.
success = balanceCheckWorked;
}
}
function _TRANSFERETH212( //inject NONSTANDARD NAMING
address payable recipient, uint256 amount
) internal returns (bool success) {
// Attempt to transfer any Ether to caller and emit an event if it fails.
(success, ) = recipient.call.gas(_eth_transfer_gas33).value(amount)("");
if (!success) {
emit EXTERNALERROR24(recipient, _REVERTREASON31(18));
} else {
emit ETHWITHDRAWAL175(amount, recipient);
}
}
function _VALIDATEACTIONANDINCREMENTNONCE883( //inject NONSTANDARD NAMING
ActionType action,
bytes memory arguments,
uint256 minimumActionGas,
bytes memory userSignature,
bytes memory dharmaSignature
) internal returns (bytes32 actionID, uint256 actionNonce) {
// Ensure that the current gas exceeds the minimum required action gas.
// This prevents griefing attacks where an attacker can invalidate a
// signature without providing enough gas for the action to succeed. Also
// note that some gas will be spent before this check is reached - supplying
// ~30,000 additional gas should suffice when submitting transactions. To
// skip this requirement, supply zero for the minimumActionGas argument.
if (minimumActionGas != 0) {
if (gasleft() < minimumActionGas) {
revert(_REVERTREASON31(19));
}
}
// Get the current nonce for the action to be performed.
actionNonce = _nonce;
// Get the user signing key that will be used to verify their signature.
address userSigningKey = _userSigningKey;
// Get the Dharma signing key that will be used to verify their signature.
address dharmaSigningKey = _GETDHARMASIGNINGKEY429();
// Determine the actionID - this serves as the signature hash.
actionID = _GETACTIONID195(
action,
arguments,
actionNonce,
minimumActionGas,
userSigningKey,
dharmaSigningKey
);
// Compute the message hash - the hashed, EIP-191-0x45-prefixed action ID.
bytes32 messageHash = actionID.TOETHSIGNEDMESSAGEHASH603();
// Actions other than Cancel require both signatures; Cancel only needs one.
if (action != ActionType.Cancel) {
// Validate user signing key signature unless it is `msg.sender`.
if (msg.sender != userSigningKey) {
if (
!_VALIDATEUSERSIGNATURE499(
messageHash, action, arguments, userSigningKey, userSignature
)
) {
revert(_REVERTREASON31(20));
}
}
// Validate Dharma signing key signature unless it is `msg.sender`.
if (msg.sender != dharmaSigningKey) {
if (dharmaSigningKey != messageHash.RECOVER845(dharmaSignature)) {
revert(_REVERTREASON31(21));
}
}
} else {
// Validate signing key signature unless user or Dharma is `msg.sender`.
if (msg.sender != userSigningKey && msg.sender != dharmaSigningKey) {
if (
dharmaSigningKey != messageHash.RECOVER845(dharmaSignature) &&
!_VALIDATEUSERSIGNATURE499(
messageHash, action, arguments, userSigningKey, userSignature
)
) {
revert(_REVERTREASON31(22));
}
}
}
// Increment nonce in order to prevent reuse of signatures after the call.
_nonce++;
}
function _MIGRATECTOKENTODTOKEN6(AssetType token) internal { //inject NONSTANDARD NAMING
CTokenInterface cToken;
DTokenInterface dToken;
if (token == AssetType.DAI) {
cToken = _cdai443;
dToken = _ddai406;
} else {
cToken = _cusdc481;
dToken = _dusdc174;
}
// Get the current cToken balance for this account.
uint256 balance = cToken.BALANCEOF992(address(this));
// Only perform the conversion if there is a non-zero balance.
if (balance > 0) {
// If the allowance is insufficient, set it before depositing.
if (cToken.ALLOWANCE583(address(this), address(dToken)) < balance) {
if (!cToken.APPROVE270(address(dToken), uint256(-1))) {
revert(_REVERTREASON31(23));
}
}
// Deposit the new balance on the Dharma Token.
if (dToken.MINTVIACTOKEN796(balance) == 0) {
revert(_REVERTREASON31(24));
}
}
}
function _CHECKDHARMATOKENINTERACTIONANDLOGANYERRORS622( //inject NONSTANDARD NAMING
AssetType asset,
bytes4 functionSelector,
bool ok,
bytes memory data
) internal returns (bool success) {
// Log an external error if something went wrong with the attempt.
if (ok) {
if (data.length == 32) {
uint256 amount = abi.decode(data, (uint256));
if (amount > 0) {
success = true;
} else {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_GETDHARMATOKENDETAILS978(asset, functionSelector)
);
emit EXTERNALERROR24(
account,
string(
abi.encodePacked(
name,
" gave no tokens calling ",
functionName,
"."
)
)
);
}
} else {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_GETDHARMATOKENDETAILS978(asset, functionSelector)
);
emit EXTERNALERROR24(
account,
string(
abi.encodePacked(
name,
" gave bad data calling ",
functionName,
"."
)
)
);
}
} else {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_GETDHARMATOKENDETAILS978(asset, functionSelector)
);
// Decode the revert reason in the event one was returned.
string memory revertReason = _DECODEREVERTREASON288(data);
emit EXTERNALERROR24(
account,
string(
abi.encodePacked(
name,
" reverted calling ",
functionName,
": ",
revertReason
)
)
);
}
}
function _DIAGNOSEANDEMITUSDCSPECIFICERROR976(bytes4 functionSelector) internal { //inject NONSTANDARD NAMING
// Determine the name of the function that was called on USDC.
string memory functionName;
if (functionSelector == _usdc146.TRANSFER153.selector) {
functionName = "transfer";
} else {
functionName = "approve";
}
USDCV1Interface usdcNaughty = USDCV1Interface(address(_usdc146));
// Find out why USDC transfer reverted (it doesn't give revert reasons).
if (usdcNaughty.ISBLACKLISTED453(address(this))) {
emit EXTERNALERROR24(
address(_usdc146),
string(
abi.encodePacked(
functionName, " failed - USDC has blacklisted this user."
)
)
);
} else { // Note: `else if` breaks coverage.
if (usdcNaughty.PAUSED117()) {
emit EXTERNALERROR24(
address(_usdc146),
string(
abi.encodePacked(
functionName, " failed - USDC contract is currently paused."
)
)
);
} else {
emit EXTERNALERROR24(
address(_usdc146),
string(
abi.encodePacked(
"USDC contract reverted on ", functionName, "."
)
)
);
}
}
}
function _ENFORCESELFCALLFROM836(bytes4 selfCallContext) internal { //inject NONSTANDARD NAMING
// Ensure caller is this contract and self-call context is correctly set.
if (msg.sender != address(this) || _selfCallContext != selfCallContext) {
revert(_REVERTREASON31(25));
}
// Clear the self-call context.
delete _selfCallContext;
}
function _VALIDATEUSERSIGNATURE499( //inject NONSTANDARD NAMING
bytes32 messageHash,
ActionType action,
bytes memory arguments,
address userSigningKey,
bytes memory userSignature
) internal view returns (bool valid) {
if (!userSigningKey.ISCONTRACT235()) {
valid = userSigningKey == messageHash.RECOVER845(userSignature);
} else {
bytes memory data = abi.encode(messageHash, action, arguments);
valid = (
ERC1271Interface(userSigningKey).ISVALIDSIGNATURE229(
data, userSignature
) == _erc_1271_magic_value586
);
}
}
function _GETDHARMASIGNINGKEY429() internal view returns ( //inject NONSTANDARD NAMING
address dharmaSigningKey
) {
dharmaSigningKey = _dharma_key_registry438.GETKEY781();
}
function _GETACTIONID195( //inject NONSTANDARD NAMING
ActionType action,
bytes memory arguments,
uint256 nonce,
uint256 minimumActionGas,
address userSigningKey,
address dharmaSigningKey
) internal view returns (bytes32 actionID) {
// actionID is constructed according to EIP-191-0x45 to prevent replays.
actionID = keccak256(
abi.encodePacked(
address(this),
_dharma_smart_wallet_version295,
userSigningKey,
dharmaSigningKey,
nonce,
minimumActionGas,
action,
arguments
)
);
}
function _GETDHARMATOKENDETAILS978( //inject NONSTANDARD NAMING
AssetType asset,
bytes4 functionSelector
) internal pure returns (
address account,
string memory name,
string memory functionName
) {
if (asset == AssetType.DAI) {
account = address(_ddai406);
name = "Dharma Dai";
} else {
account = address(_dusdc174);
name = "Dharma USD Coin";
}
// Note: since both dTokens have the same interface, just use dDai's.
if (functionSelector == _ddai406.MINT76.selector) {
functionName = "mint";
} else {
if (functionSelector == ERC20Interface(account).BALANCEOF992.selector) {
functionName = "balanceOf";
} else {
functionName = string(abi.encodePacked(
"redeem",
functionSelector == _ddai406.REDEEM466.selector ? "" : "Underlying"
));
}
}
}
function _ENSUREVALIDGENERICCALLTARGET978(address to) internal view { //inject NONSTANDARD NAMING
if (!to.ISCONTRACT235()) {
revert(_REVERTREASON31(26));
}
if (to == address(this)) {
revert(_REVERTREASON31(27));
}
if (to == address(_escape_hatch_registry980)) {
revert(_REVERTREASON31(28));
}
}
function _VALIDATECUSTOMACTIONTYPEANDGETARGUMENTS503( //inject NONSTANDARD NAMING
ActionType action, uint256 amount, address recipient
) internal pure returns (bytes memory arguments) {
// Ensure that the action type is a valid custom action type.
bool validActionType = (
action == ActionType.Cancel ||
action == ActionType.SetUserSigningKey ||
action == ActionType.DAIWithdrawal ||
action == ActionType.USDCWithdrawal ||
action == ActionType.ETHWithdrawal ||
action == ActionType.SetEscapeHatch ||
action == ActionType.RemoveEscapeHatch ||
action == ActionType.DisableEscapeHatch
);
if (!validActionType) {
revert(_REVERTREASON31(29));
}
// Use action type to determine parameters to include in returned arguments.
if (
action == ActionType.Cancel ||
action == ActionType.RemoveEscapeHatch ||
action == ActionType.DisableEscapeHatch
) {
// Ignore parameters for Cancel, RemoveEscapeHatch, or DisableEscapeHatch.
arguments = abi.encode();
} else if (
action == ActionType.SetUserSigningKey ||
action == ActionType.SetEscapeHatch
) {
// Ignore `amount` parameter for other, non-withdrawal actions.
arguments = abi.encode(recipient);
} else {
// Use both `amount` and `recipient` parameters for withdrawals.
arguments = abi.encode(amount, recipient);
}
}
function _DECODEREVERTREASON288( //inject NONSTANDARD NAMING
bytes memory revertData
) internal pure returns (string memory revertReason) {
// Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector
if (
revertData.length > 68 && // prefix (4) + position (32) + length (32)
revertData[0] == byte(0x08) &&
revertData[1] == byte(0xc3) &&
revertData[2] == byte(0x79) &&
revertData[3] == byte(0xa0)
) {
// Get the revert reason without the prefix from the revert data.
bytes memory revertReasonBytes = new bytes(revertData.length - 4);
for (uint256 i = 4; i < revertData.length; i++) {
revertReasonBytes[i - 4] = revertData[i];
}
// Decode the resultant revert reason as a string.
revertReason = abi.decode(revertReasonBytes, (string));
} else {
// Simply return the default, with no revert reason.
revertReason = _REVERTREASON31(uint256(-1));
}
}
function _REVERTREASON31( //inject NONSTANDARD NAMING
uint256 code
) internal pure returns (string memory reason) {
reason = _revert_reason_helper415.REASON113(code);
}
}
|
inject NONSTANDARD NAMING
|
function REMOVEESCAPEHATCH653() external;
| 5,492,011
|
./partial_match/1/0xDf2BF3ef4F5c9DC69E3a6642Fa3168327EE1cdd7/sources/BuyBack.sol
|
burns GRO tokens then sets burner storage var to 0
|
function burnTokens() public override {
if (msg.sender != owner || !keepers[msg.sender])
revert BuyBackErrors.NotKeeper();
uint256 _burner = burner;
uint256 amount = uniV2Swap(USDC, GRO, _burner);
IBurner(GRO_BURNER).reVest(amount);
IVester(GRO_VESTER).exit(amount);
emit BurnTokens(_burner, amount);
burner = 0;
}
| 16,195,064
|
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.13;
import { stdError } from "forge-std/test/StdError.t.sol";
import { Vm } from "forge-std/Vm.sol";
import { DSTest } from "ds-test/test.sol";
import { ERC20 } from "@rari-capital/solmate/src/tokens/ERC20.sol";
import { LilFlashloan, FlashBorrower } from "../LilFlashloan.sol";
contract User {}
contract TestToken is ERC20("Test Token", "TEST", 18) {
function mintTo(address to, uint256 amount) public payable {
_mint(to, amount);
}
}
contract TestReceiver is FlashBorrower, DSTest {
bytes32 internal testData;
bool internal shouldRepay = true;
bool internal shouldPayFees = true;
function setTestData(bytes calldata data) public payable {
testData = bytes32(data);
}
function setRepay(bool _shouldRepay) public payable {
shouldRepay = _shouldRepay;
}
function setRespectFees(bool _shouldPayFees) public payable {
shouldPayFees = _shouldPayFees;
}
function onFlashLoan(
ERC20 token,
uint256 amount,
bytes calldata data
) external {
assertEq(testData, bytes32(data));
if (!shouldRepay) return;
token.transfer(msg.sender, amount);
if (!shouldPayFees) return;
uint256 owedFees = LilFlashloan(msg.sender).getFee(token, amount);
TestToken(address(token)).mintTo(msg.sender, owedFees);
}
}
contract LilFlashloanTest is DSTest {
User internal user;
TestToken internal token;
TestReceiver internal receiver;
LilFlashloan internal lilFlashloan;
Vm internal hevm = Vm(HEVM_ADDRESS);
event FeeUpdated(ERC20 indexed token, uint256 fee);
event Withdrawn(ERC20 indexed token, uint256 amount);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Flashloaned(
FlashBorrower indexed receiver,
ERC20 indexed token,
uint256 amount
);
function setUp() public {
user = new User();
token = new TestToken();
receiver = new TestReceiver();
lilFlashloan = new LilFlashloan();
}
function testCanFlashloan() public {
token.mintTo(address(lilFlashloan), 100 ether);
hevm.expectEmit(true, true, false, true);
emit Flashloaned(receiver, token, 100 ether);
hevm.expectEmit(true, true, false, true);
emit Transfer(address(lilFlashloan), address(receiver), 100 ether);
hevm.expectEmit(true, true, false, true);
emit Transfer(address(receiver), address(lilFlashloan), 100 ether);
lilFlashloan.execute(receiver, token, 100 ether, "");
assertEq(token.balanceOf(address(lilFlashloan)), 100 ether);
}
function testDataIsForwarded() public {
receiver.setTestData("forwarded data");
token.mintTo(address(lilFlashloan), 100 ether);
lilFlashloan.execute(receiver, token, 100 ether, "forwarded data");
}
function testCanFlashloanWithFees() public {
token.mintTo(address(lilFlashloan), 100 ether);
// set 10% fee for token
lilFlashloan.setFees(token, 10_00);
lilFlashloan.execute(receiver, token, 100 ether, "");
assertEq(token.balanceOf(address(lilFlashloan)), 110 ether);
}
function testCannotFlasloanIfNotEnoughBalance() public {
token.mintTo(address(lilFlashloan), 1 ether);
hevm.expectRevert(stdError.arithmeticError); // error comes from ERC20 impl. (solmate in this test)
lilFlashloan.execute(receiver, token, 2 ether, "");
assertEq(token.balanceOf(address(lilFlashloan)), 1 ether);
}
function testFlashloanRevertsIfNotRepaid() public {
receiver.setRepay(false);
token.mintTo(address(lilFlashloan), 100 ether);
hevm.expectRevert(abi.encodeWithSignature("TokensNotReturned()"));
lilFlashloan.execute(receiver, token, 100 ether, "");
assertEq(token.balanceOf(address(lilFlashloan)), 100 ether);
}
function testFlashloanRevertsIfNotFeesNotPaid() public {
receiver.setRespectFees(false);
// set 10% fee for token
lilFlashloan.setFees(token, 10_00);
token.mintTo(address(lilFlashloan), 100 ether);
hevm.expectRevert(abi.encodeWithSignature("TokensNotReturned()"));
lilFlashloan.execute(receiver, token, 100 ether, "");
assertEq(token.balanceOf(address(lilFlashloan)), 100 ether);
}
function testManagerCanSetFees() public {
assertEq(lilFlashloan.fees(token), 0);
hevm.expectEmit(true, false, false, true);
emit FeeUpdated(token, 10_00);
// set 10% fee for token
lilFlashloan.setFees(token, 10_00);
assertEq(lilFlashloan.fees(token), 10_00);
}
function testCannotSetFeesHigherThan100Percent() public {
assertEq(lilFlashloan.fees(token), 0);
hevm.expectRevert(abi.encodeWithSignature("InvalidPercentage()"));
lilFlashloan.setFees(token, 101_00);
assertEq(lilFlashloan.fees(token), 0);
}
function testNonManagerCannotSetFees() public {
assertEq(lilFlashloan.fees(token), 0);
hevm.prank(address(user));
hevm.expectRevert(abi.encodeWithSignature("Unauthorized()"));
lilFlashloan.setFees(token, 10_00);
assertEq(lilFlashloan.fees(token), 0);
}
function testManagerCanWithdrawTokens() public {
token.mintTo(address(lilFlashloan), 10 ether);
assertEq(token.balanceOf(address(this)), 0);
hevm.expectEmit(true, false, false, true);
emit Withdrawn(token, 10 ether);
lilFlashloan.withdraw(token, 10 ether);
assertEq(token.balanceOf(address(this)), 10 ether);
assertEq(token.balanceOf(address(lilFlashloan)), 0);
}
function testNonManagerCannotWithdrawTokens() public {
token.mintTo(address(lilFlashloan), 10 ether);
assertEq(token.balanceOf(address(user)), 0);
hevm.prank(address(user));
hevm.expectRevert(abi.encodeWithSignature("Unauthorized()"));
lilFlashloan.withdraw(token, 10 ether);
assertEq(token.balanceOf(address(user)), 0);
assertEq(token.balanceOf(address(lilFlashloan)), 10 ether);
}
}
|
set 10% fee for token
|
function testFlashloanRevertsIfNotFeesNotPaid() public {
receiver.setRespectFees(false);
lilFlashloan.setFees(token, 10_00);
token.mintTo(address(lilFlashloan), 100 ether);
hevm.expectRevert(abi.encodeWithSignature("TokensNotReturned()"));
lilFlashloan.execute(receiver, token, 100 ether, "");
assertEq(token.balanceOf(address(lilFlashloan)), 100 ether);
}
| 6,460,355
|
/**
*Submitted for verification at Etherscan.io on 2021-02-19
*/
/*
.'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''..
.;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,.
';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,.
';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,.
...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''..
.,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. .....
.;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,..
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. ....
..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,.
..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'.
...'.. .';;;;;;;;;;;;;;,,,'.
...............
*/
// https://github.com/trusttoken/smart-contracts
// Dependency 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;
}
}
// Dependency file: contracts/governance/common/ClaimableContract.sol
// pragma solidity 0.6.10;
/**
* @title ClaimableContract
* @dev The ClaimableContract contract is a copy of Claimable Contract by Zeppelin.
and provides basic authorization control functions. Inherits storage layout of
ProxyStorage.
*/
contract ClaimableContract {
address owner_;
address pendingOwner_;
bool initalized;
function owner() public view returns (address) {
return owner_;
}
function pendingOwner() public view returns (address) {
return pendingOwner_;
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev sets the original `owner` of the contract to the sender
* at construction. Must then be reinitialized
*/
constructor() public {
owner_ = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner_, "only owner");
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner_);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner_ = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
address _pendingOwner = pendingOwner_;
emit OwnershipTransferred(owner_, _pendingOwner);
owner_ = _pendingOwner;
pendingOwner_ = address(0);
}
}
// Root file: contracts/governance/Timelock.sol
// AND COPIED FROM https://github.com/compound-finance/compound-protocol/blob/c5fcc34222693ad5f547b14ed01ce719b5f4b000/contracts/Timelock.sol
// Copyright 2020 Compound Labs, Inc.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Ctrl+f for OLD to see all the modifications.
// OLD: pragma solidity ^0.5.16;
pragma solidity ^0.6.10;
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import "contracts/governance/common/ClaimableContract.sol";
contract Timelock is ClaimableContract {
using SafeMath for uint;
event NewAdmin(address indexed newAdmin);
event NewPendingAdmin(address indexed newPendingAdmin);
event NewDelay(uint indexed newDelay);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta);
uint public constant GRACE_PERIOD = 14 days;
uint public constant MINIMUM_DELAY = 2 days;
uint public constant MAXIMUM_DELAY = 30 days;
address public admin;
address public pendingAdmin;
uint public delay;
// OLD: N/A
bool public admin_initialized;
mapping (bytes32 => bool) public queuedTransactions;
/**
* @dev Initialize sets the addresses of admin and the delay timestamp
* @param admin_ The address of admin
* @param delay_ The timestamp of delay for timelock contract
*/
function initialize(address admin_, uint delay_) external {
require(!initalized, "Already initialized");
require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
admin = admin_;
delay = delay_;
owner_ = msg.sender;
initalized = true;
// OLD: N/A
admin_initialized = false;
}
// OLD: function() external payable { }
receive() external payable { }
/**
* @dev Set the timelock delay to a new timestamp
* @param delay_ The timestamp of delay for timelock contract
*/
function setDelay(uint delay_) public {
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NewDelay(delay);
}
/**
* @dev Accept the pendingAdmin as the admin address
*/
function acceptAdmin() public {
require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin.");
admin = msg.sender;
pendingAdmin = address(0);
emit NewAdmin(admin);
}
/**
* @dev Set the pendingAdmin address to a new address
* @param pendingAdmin_ The address of the new pendingAdmin
*/
function setPendingAdmin(address pendingAdmin_) public {
// allows one time setting of admin for deployment purposes
if (admin_initialized) {
require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock.");
} else {
require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin.");
admin_initialized = true;
}
pendingAdmin = pendingAdmin_;
emit NewPendingAdmin(pendingAdmin);
}
/**
* @dev Queue one single proposal transaction
* @param target The target address for call to be made during proposal execution
* @param value The value to be passed to the calls made during proposal execution
* @param signature The function signature to be passed during execution
* @param data The data to be passed to the individual function call
* @param eta The current timestamp plus the timelock delay
*/
function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
/**
* @dev Cancel one single proposal transaction
* @param target The target address for call to be made during proposal execution
* @param value The value to be passed to the calls made during proposal execution
* @param signature The function signature to be passed during execution
* @param data The data to be passed to the individual function call
* @param eta The current timestamp plus the timelock delay
*/
function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public {
require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CancelTransaction(txHash, target, value, signature, data, eta);
}
/**
* @dev Execute one single proposal transaction
* @param target The target address for call to be made during proposal execution
* @param value The value to be passed to the calls made during proposal execution
* @param signature The function signature to be passed during execution
* @param data The data to be passed to the individual function call
* @param eta The current timestamp plus the timelock delay
*/
function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) {
require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returnData) = target.call{value:value}(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(txHash, target, value, signature, data, eta);
return returnData;
}
/**
* @dev Get the current block timestamp
* @return The timestamp of current block
*/
function getBlockTimestamp() internal view returns (uint) {
// solium-disable-next-line security/no-block-members
return block.timestamp;
}
}
|
Queue one single proposal transaction target The target address for call to be made during proposal execution value The value to be passed to the calls made during proposal execution signature The function signature to be passed during execution data The data to be passed to the individual function call eta The current timestamp plus the timelock delay/
|
function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) {
require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin.");
require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QueueTransaction(txHash, target, value, signature, data, eta);
return txHash;
}
| 6,656,522
|
pragma solidity ^0.4.13;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function getOwner() returns(address){
return 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 {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/*
* ΠΠ°Π·ΠΎΠ²ΡΠΉ ΠΊΠΎΠ½ΡΡΠ°ΠΊΡ, ΠΊΠΎΡΠΎΡΡΠΉ ΠΏΠΎΠ΄Π΄Π΅ΡΠΆΠΈΠ²Π°Π΅Ρ ΠΎΡΡΠ°Π½ΠΎΠ²ΠΊΡ ΠΏΡΠΎΠ΄Π°ΠΆ
*/
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
require(!halted);
_;
}
/* ΠΠΎΠ΄ΠΈΡΠΈΠΊΠ°ΡΠΎΡ, ΠΊΠΎΡΠΎΡΡΠΉ Π²ΡΠ·ΡΠ²Π°Π΅ΡΡΡ Π² ΠΏΠΎΡΠΎΠΌΠΊΠ°Ρ
*/
modifier onlyInEmergency {
require(halted);
_;
}
/* ΠΡΠ·ΠΎΠ² ΡΡΠ½ΠΊΡΠΈΠΈ ΠΏΡΠ΅ΡΠ²Π΅Ρ ΠΏΡΠΎΠ΄Π°ΠΆΠΈ, Π²ΡΠ·ΡΠ²Π°ΡΡ ΠΌΠΎΠΆΠ΅Ρ ΡΠΎΠ»ΡΠΊΠΎ Π²Π»Π°Π΄Π΅Π»Π΅Ρ */
function halt() external onlyOwner {
halted = true;
}
/* ΠΡΠ·ΠΎΠ² Π²ΠΎΠ·Π²ΡΠ°ΡΠ°Π΅Ρ ΡΠ΅ΠΆΠΈΠΌ ΠΏΡΠΎΠ΄Π°ΠΆ */
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
/**
* Π Π°Π·Π»ΠΈΡΠ½ΡΠ΅ Π²Π°Π»ΠΈΠ΄Π°ΡΠΎΡΡ
*/
contract ValidationUtil {
function requireNotEmptyAddress(address value) internal{
require(isAddressValid(value));
}
function isAddressValid(address value) internal constant returns (bool result){
return value != 0;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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) returns (bool) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* Π¨Π°Π±Π»ΠΎΠ½ Π΄Π»Ρ ΡΠΎΠΊΠ΅Π½Π°, ΠΊΠΎΡΠΎΡΡΠΉ ΠΌΠΎΠΆΠ½ΠΎ ΡΠΆΠ΅ΡΡ
*/
contract BurnableToken is StandardToken, Ownable, ValidationUtil {
using SafeMath for uint;
address public tokenOwnerBurner;
/** Π‘ΠΎΠ±ΡΡΠΈΠ΅, ΡΠΊΠΎΠ»ΡΠΊΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² ΠΌΡ ΡΠΎΠΆΠ³Π»ΠΈ */
event Burned(address burner, uint burnedAmount);
function setOwnerBurner(address _tokenOwnerBurner) public onlyOwner invalidOwnerBurner{
// ΠΡΠΎΠ²Π΅ΡΠΊΠ°, ΡΡΠΎ Π°Π΄ΡΠ΅Ρ Π½Π΅ ΠΏΡΡΡΠΎΠΉ
requireNotEmptyAddress(_tokenOwnerBurner);
tokenOwnerBurner = _tokenOwnerBurner;
}
/**
* Π‘ΠΆΠΈΠ³Π°Π΅ΠΌ ΡΠΎΠΊΠ΅Π½Ρ Π½Π° Π±Π°Π»Π°Π½ΡΠ΅ Π²Π»Π°Π΄Π΅Π»ΡΡΠ° ΡΠΎΠΊΠ΅Π½ΠΎΠ², Π²ΡΠ·Π²Π°ΡΡ ΠΌΠΎΠΆΠ΅Ρ ΡΠΎΠ»ΡΠΊΠΎ tokenOwnerBurner
*/
function burnOwnerTokens(uint burnAmount) public onlyTokenOwnerBurner validOwnerBurner{
burnTokens(tokenOwnerBurner, burnAmount);
}
/**
* Π‘ΠΆΠΈΠ³Π°Π΅ΠΌ ΡΠΎΠΊΠ΅Π½Ρ Π½Π° Π±Π°Π»Π°Π½ΡΠ΅ Π°Π΄ΡΠ΅ΡΠ° ΡΠΎΠΊΠ΅Π½ΠΎΠ², Π²ΡΠ·Π²Π°ΡΡ ΠΌΠΎΠΆΠ΅Ρ ΡΠΎΠ»ΡΠΊΠΎ tokenOwnerBurner
*/
function burnTokens(address _address, uint burnAmount) public onlyTokenOwnerBurner validOwnerBurner{
balances[_address] = balances[_address].sub(burnAmount);
// ΠΡΠ·ΡΠ²Π°Π΅ΠΌ ΡΠΎΠ±ΡΡΠΈΠ΅
Burned(_address, burnAmount);
}
/**
* Π‘ΠΆΠΈΠ³Π°Π΅ΠΌ Π²ΡΠ΅ ΡΠΎΠΊΠ΅Π½Ρ Π½Π° Π±Π°Π»Π°Π½ΡΠ΅ Π²Π»Π°Π΄Π΅Π»ΡΡΠ°
*/
function burnAllOwnerTokens() public onlyTokenOwnerBurner validOwnerBurner{
uint burnAmount = balances[tokenOwnerBurner];
burnTokens(tokenOwnerBurner, burnAmount);
}
/** ΠΠΎΠ΄ΠΈΡΠΈΠΊΠ°ΡΠΎΡΡ
*/
modifier onlyTokenOwnerBurner() {
require(msg.sender == tokenOwnerBurner);
_;
}
modifier validOwnerBurner() {
// ΠΡΠΎΠ²Π΅ΡΠΊΠ°, ΡΡΠΎ Π°Π΄ΡΠ΅Ρ Π½Π΅ ΠΏΡΡΡΠΎΠΉ
requireNotEmptyAddress(tokenOwnerBurner);
_;
}
modifier invalidOwnerBurner() {
// ΠΡΠΎΠ²Π΅ΡΠΊΠ°, ΡΡΠΎ Π°Π΄ΡΠ΅Ρ Π½Π΅ ΠΏΡΡΡΠΎΠΉ
require(!isAddressValid(tokenOwnerBurner));
_;
}
}
/**
* Π’ΠΎΠΊΠ΅Π½ ΠΏΡΠΎΠ΄Π°ΠΆ
*
* ERC-20 ΡΠΎΠΊΠ΅Π½, Π΄Π»Ρ ICO
*
*/
contract CrowdsaleToken is StandardToken, Ownable {
/* ΠΠΏΠΈΡΠ°Π½ΠΈΠ΅ ΡΠΌ. Π² ΠΊΠΎΠ½ΡΡΡΡΠΊΡΠΎΡΠ΅ */
string public name;
string public symbol;
uint public decimals;
address public mintAgent;
/** Π‘ΠΎΠ±ΡΡΠΈΠ΅ ΠΎΠ±Π½ΠΎΠ²Π»Π΅Π½ΠΈΡ ΡΠΎΠΊΠ΅Π½Π° (ΠΈΠΌΡ ΠΈ ΡΠΈΠΌΠ²ΠΎΠ») */
event UpdatedTokenInformation(string newName, string newSymbol);
/** Π‘ΠΎΠ±ΡΡΠΈΠ΅ Π²ΡΠΏΡΡΠΊΠ° ΡΠΎΠΊΠ΅Π½ΠΎΠ² */
event TokenMinted(uint amount, address toAddress);
/**
* ΠΠΎΠ½ΡΡΡΡΠΊΡΠΎΡ
*
* Π’ΠΎΠΊΠ΅Π½ Π΄ΠΎΠ»ΠΆΠ΅Π½ Π±ΡΡΡ ΡΠΎΠ·Π΄Π°Π½ ΡΠΎΠ»ΡΠΊΠΎ Π²Π»Π°Π΄Π΅Π»ΡΡΠ΅ΠΌ ΡΠ΅ΡΠ΅Π· ΠΊΠΎΡΠ΅Π»Π΅ΠΊ (Π»ΠΈΠ±ΠΎ Ρ ΠΌΡΠ»ΡΡΠΈΠΏΠΎΠ΄ΠΏΠΈΡΡΡ, Π»ΠΈΠ±ΠΎ Π±Π΅Π· Π½Π΅Π΅)
*
* @param _name - ΠΈΠΌΡ ΡΠΎΠΊΠ΅Π½Π°
* @param _symbol - ΡΠΈΠΌΠ²ΠΎΠ» ΡΠΎΠΊΠ΅Π½Π°
* @param _decimals - ΠΊΠΎΠ»-Π²ΠΎ Π·Π½Π°ΠΊΠΎΠ² ΠΏΠΎΡΠ»Π΅ Π·Π°ΠΏΡΡΠΎΠΉ
*/
function CrowdsaleToken(string _name, string _symbol, uint _decimals) {
owner = msg.sender;
name = _name;
symbol = _symbol;
decimals = _decimals;
}
/**
* ΠΠ»Π°Π΄Π΅Π»Π΅Ρ Π΄ΠΎΠ»ΠΆΠ΅Π½ Π²ΡΠ·Π²Π°ΡΡ ΡΡΡ ΡΡΠ½ΠΊΡΠΈΡ, ΡΡΠΎΠ±Ρ Π²ΡΠΏΡΡΡΠΈΡΡ ΡΠΎΠΊΠ΅Π½Ρ Π½Π° Π°Π΄ΡΠ΅Ρ
*/
function mintToAddress(uint amount, address toAddress) onlyMintAgent{
// ΠΏΠ΅ΡΠ΅Π²ΠΎΠ΄ ΡΠΎΠΊΠ΅Π½ΠΎΠ² Π½Π° Π°ΠΊΠΊΠ°ΡΠ½Ρ
balances[toAddress] = amount;
// Π²ΡΠ·ΡΠ²Π°Π΅ΠΌ ΡΠΎΠ±ΡΡΠΈΠ΅
TokenMinted(amount, toAddress);
}
/**
* ΠΠ»Π°Π΄Π΅Π»Π΅Ρ ΠΌΠΎΠΆΠ΅Ρ ΠΎΠ±Π½ΠΎΠ²ΠΈΡΡ ΠΈΠ½ΡΡ ΠΏΠΎ ΡΠΎΠΊΠ΅Π½Ρ
*/
function setTokenInformation(string _name, string _symbol) onlyOwner {
name = _name;
symbol = _symbol;
// ΠΡΠ·ΡΠ²Π°Π΅ΠΌ ΡΠΎΠ±ΡΡΠΈΠ΅
UpdatedTokenInformation(name, symbol);
}
/**
* Π’ΠΎΠ»ΡΠΊΠΎ Π²Π»Π°Π΄Π΅Π»Π΅Ρ ΠΌΠΎΠΆΠ΅Ρ ΠΎΠ±Π½ΠΎΠ²ΠΈΡΡ Π°Π³Π΅Π½ΡΠ° Π΄Π»Ρ ΡΠΎΠ·Π΄Π°Π½ΠΈΡ ΡΠΎΠΊΠ΅Π½ΠΎΠ²
*/
function setMintAgent(address _address) onlyOwner {
mintAgent = _address;
}
modifier onlyMintAgent(){
require(msg.sender == mintAgent);
_;
}
}
/**
* Π¨Π°Π±Π»ΠΎΠ½ Π΄Π»Ρ ΠΏΡΠΎΠ΄Π°ΠΆ ΡΠΎΠΊΠ΅Π½Π°, ΠΊΠΎΡΠΎΡΡΠΉ ΠΌΠΎΠΆΠ½ΠΎ ΡΠΆΠ΅ΡΡ
*
*/
contract BurnableCrowdsaleToken is BurnableToken, CrowdsaleToken {
function BurnableCrowdsaleToken(string _name, string _symbol, uint _decimals) CrowdsaleToken(_name, _symbol, _decimals) BurnableToken(){
}
}
/**
* ΠΠ°Π·ΠΎΠ²ΡΠΉ ΠΊΠΎΠ½ΡΡΠ°ΠΊΡ Π΄Π»Ρ ΠΏΡΠΎΠ΄Π°ΠΆ
*
* Π‘ΠΎΠ΄Π΅ΡΠΆΠΈΡ
* - ΠΠ°ΡΠ° Π½Π°ΡΠ°Π»Π° ΠΈ ΠΊΠΎΠ½ΡΠ°
*/
/* ΠΡΠΎΠ΄Π°ΠΆΠΈ ΠΌΠΎΠ³ΡΡ Π±ΡΡΡ ΠΎΡΡΠ°Π½ΠΎΠ²Π»Π΅Π½Ρ Π² Π»ΡΠ±ΠΎΠΉ ΠΌΠΎΠΌΠ΅Π½Ρ ΠΏΠΎ Π²ΡΠ·ΠΎΠ²Ρ halt() */
contract AllocatedCappedCrowdsale is Haltable, ValidationUtil {
using SafeMath for uint;
// ΠΠΎΠ»-Π²ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² Π΄Π»Ρ ΡΠ°ΡΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΡ
uint public advisorsTokenAmount = 8040817;
uint public supportTokenAmount = 3446064;
uint public marketingTokenAmount = 3446064;
uint public teamTokenAmount = 45947521;
uint public teamTokensIssueDate;
/* Π’ΠΎΠΊΠ΅Π½, ΠΊΠΎΡΠΎΡΡΠΉ ΠΏΡΠΎΠ΄Π°Π΅ΠΌ */
BurnableCrowdsaleToken public token;
/* ΠΠ΄ΡΠ΅Ρ, ΠΊΡΠ΄Π° Π±ΡΠ΄ΡΡ ΠΏΠ΅ΡΠ΅Π²Π΅Π΄Π΅Π½Π° ΡΠΎΠ±ΡΠ°Π½Π½Π°Ρ ΡΡΠΌΠΌΠ°, Π² ΡΠ»ΡΡΠ°Π΅ ΡΡΠΏΠ΅Ρ
Π° */
address public destinationMultisigWallet;
/* ΠΠ΅ΡΠ²Π°Ρ ΡΡΠ°Π΄ΠΈΡ Π² ΡΠΎΡΠΌΠ°ΡΠ΅ UNIX timestamp */
uint public firstStageStartsAt;
/* ΠΠΎΠ½Π΅Ρ ΠΏΡΠΎΠ΄Π°ΠΆ Π² ΡΠΎΡΠΌΠ°ΡΠ΅ UNIX timestamp */
uint public firstStageEndsAt;
/* ΠΡΠΎΡΠ°Ρ ΡΡΠ°Π΄ΠΈΡ Π² ΡΠΎΡΠΌΠ°ΡΠ΅ UNIX timestamp */
uint public secondStageStartsAt;
/* ΠΠΎΠ½Π΅Ρ ΠΏΡΠΎΠ΄Π°ΠΆ Π² ΡΠΎΡΠΌΠ°ΡΠ΅ UNIX timestamp */
uint public secondStageEndsAt;
/* ΠΠΈΠ½ΠΈΠΌΠ°Π»ΡΠ½Π°Ρ ΠΊΠ΅ΠΏΠΊΠ° Π΄Π»Ρ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ Π² ΡΠ΅Π½ΡΠ°Ρ
*/
uint public softCapFundingGoalInCents = 392000000;
/* ΠΠΈΠ½ΠΈΠΌΠ°Π»ΡΠ½Π°Ρ ΠΊΠ΅ΠΏΠΊΠ° Π΄Π»Ρ Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ Π² ΡΠ΅Π½ΡΠ°Ρ
*/
uint public hardCapFundingGoalInCents = 985000000;
/* Π‘ΠΊΠΎΠ»ΡΠΊΠΎ Π²ΡΠ΅Π³ΠΎ Π² wei ΠΌΡ ΠΏΠΎΠ»ΡΡΠΈΠ»ΠΈ 10^18 wei = 1 ether */
uint public weiRaised;
/* Π‘ΠΊΠΎΠ»ΡΠΊΠΎ Π²ΡΠ΅Π³ΠΎ ΡΠΎΠ±ΡΠ°Π»ΠΈ Π² ΡΠ΅Π½Π°Ρ
Π½Π° ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ */
uint public firstStageRaisedInWei;
/* Π‘ΠΊΠΎΠ»ΡΠΊΠΎ Π²ΡΠ΅Π³ΠΎ ΡΠΎΠ±ΡΠ°Π»ΠΈ Π² ΡΠ΅Π½Π°Ρ
Π½Π° Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ */
uint public secondStageRaisedInWei;
/* ΠΠΎΠ»-Π²ΠΎ ΡΠ½ΠΈΠΊΠ°Π»ΡΠ½ΡΡ
Π°Π΄ΡΠ΅ΡΠΎΠ², ΠΊΠΎΡΠΎΡΡΠ΅ Ρ Π½Π°c ΠΏΠΎΠ»ΡΡΠΈΠ»ΠΈ ΡΠΎΠΊΠ΅Π½Ρ */
uint public investorCount;
/* Π‘ΠΊΠΎΠ»ΡΠΊΠΎ wei ΠΎΡΠ΄Π°Π»ΠΈ ΠΈΠ½Π²Π΅ΡΡΠΎΡΠ°ΠΌ Π½Π° refund'Π΅ Π² wei */
uint public weiRefunded;
/* Π‘ΠΊΠΎΠ»ΡΠΊΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² ΠΏΡΠΎΠ΄Π°Π»ΠΈ Π²ΡΠ΅Π³ΠΎ */
uint public tokensSold;
/* Π€Π»Π°Π³ ΡΠΎΠ³ΠΎ, ΡΡΠΎ ΡΡΠ°Π±ΠΎΡΠ°Π» ΡΠΈΠ½Π°Π»ΠΈΠ·Π°ΡΠΎΡ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ */
bool public isFirstStageFinalized;
/* Π€Π»Π°Π³ ΡΠΎΠ³ΠΎ, ΡΡΠΎ ΡΡΠ°Π±ΠΎΡΠ°Π» ΡΠΈΠ½Π°Π»ΠΈΠ·Π°ΡΠΎΡ Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ */
bool public isSecondStageFinalized;
/* Π€Π»Π°Π³ Π½ΠΎΡΠΌΠ°Π»ΡΠ½ΠΎΠ³ΠΎ Π·Π°Π²Π΅ΡΡΠ½Π΅Π½ΠΈΡ ΠΏΡΠΎΠ΄Π°ΠΆ */
bool public isSuccessOver;
/* Π€Π»Π°Π³ ΡΠΎΠ³ΠΎ, ΡΡΠΎ Π½Π°ΡΠ°Π»ΡΡ ΠΏΡΠΎΡΠ΅ΡΡ Π²ΠΎΠ·Π²ΡΠ°ΡΠ° */
bool public isRefundingEnabled;
/* Π‘ΠΊΠΎΠ»ΡΠΊΠΎ ΡΠ΅ΠΉΡΠ°Ρ ΡΡΠΎΠΈΡ 1 eth Π² ΡΠ΅Π½ΡΠ°Ρ
, ΠΎΠΊΡΡΠ³Π»Π΅Π½Π½Π°Ρ Π΄ΠΎ ΡΠ΅Π»ΡΡ
*/
uint public currentEtherRateInCents;
/* Π’Π΅ΠΊΡΡΠ°Ρ ΡΡΠΎΠΈΠΌΠΎΡΡΡ ΡΠΎΠΊΠ΅Π½Π° Π² ΡΠ΅Π½ΡΠ°Ρ
*/
uint public oneTokenInCents = 7;
/* ΠΡΠΏΡΡΠ΅Π½Ρ Π»ΠΈ ΡΠΎΠΊΠ΅Π½Ρ Π΄Π»Ρ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ */
bool public isFirstStageTokensMinted;
/* ΠΡΠΏΡΡΠ΅Π½Ρ Π»ΠΈ ΡΠΎΠΊΠ΅Π½Ρ Π΄Π»Ρ Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ */
bool public isSecondStageTokensMinted;
/* ΠΠΎΠ»-Π²ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² Π΄Π»Ρ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ */
uint public firstStageTotalSupply = 112000000;
/* ΠΠΎΠ»-Π²ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² ΠΏΡΠΎΠ΄Π°Π½Π½ΡΡ
Π½Π° ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ*/
uint public firstStageTokensSold;
/* ΠΠΎΠ»-Π²ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² Π΄Π»Ρ Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ */
uint public secondStageTotalSupply = 229737610;
/* ΠΠΎΠ»-Π²ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² ΠΏΡΠΎΠ΄Π°Π½Π½ΡΡ
Π½Π° Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ*/
uint public secondStageTokensSold;
/* ΠΠΎΠ»-Π²ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ², ΠΊΠΎΡΠΎΡΡΠ΅ Π½Π°Ρ
ΠΎΠ΄ΡΡΡΡ Π² ΡΠ΅Π·Π΅ΡΠ²Π΅ ΠΈ Π½Π΅ ΠΏΡΠΎΠ΄Π°ΡΡΡΡ, ΠΏΠΎΡΠ»Π΅ ΡΡΠΏΠ΅Ρ
Π°, ΠΎΠ½ΠΈ ΡΠ°ΡΠΏΡΠ΅Π΄Π΅Π»ΡΡΡΡΡ Π² ΡΠΎΠΎΡΠ²Π΅ΡΡΠ²ΠΈΠΈ Ρ Token Policy Π½Π° Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ*/
uint public secondStageReserve = 60880466;
/* ΠΠΎΠ»-Π²ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² ΠΏΡΠ΅Π΄Π½Π°Π·Π½Π°ΡΠ΅Π½Π½ΡΡ
Π΄Π»Ρ ΠΏΡΠΎΠ΄Π°ΠΆΠΈ, Π½Π° Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ*/
uint public secondStageTokensForSale;
/* ΠΠ°ΠΏΠ° Π°Π΄ΡΠ΅Ρ ΠΈΠ½Π²Π΅ΡΡΠΎΡΠ° - ΠΊΠΎΠ»-Π²ΠΎ Π²ΡΠ΄Π°Π½Π½ΡΡ
ΡΠΎΠΊΠ΅Π½ΠΎΠ² */
mapping (address => uint) public tokenAmountOf;
/* ΠΠ°ΠΏΠ°, Π°Π΄ΡΠ΅Ρ ΠΈΠ½Π²Π΅ΡΡΠΎΡΠ° - ΠΊΠΎΠ»-Π²ΠΎ ΡΡΠΈΡΠ° */
mapping (address => uint) public investedAmountOf;
/* ΠΠ΄ΡΠ΅ΡΠ°, ΠΊΡΠ΄Π° Π±ΡΠ΄ΡΡ ΡΠ°ΡΠΏΡΠ΅Π΄Π΅Π»Π΅Π½Ρ ΡΠΎΠΊΠ΅Π½Ρ */
address public advisorsAccount;
address public marketingAccount;
address public supportAccount;
address public teamAccount;
/** ΠΠΎΠ·ΠΌΠΎΠΆΠ½ΡΠ΅ ΡΠΎΡΡΠΎΡΠ½ΠΈΡ
*
* - Prefunding: ΠΏΠΎΠ΄Π³ΠΎΡΠΎΠ²ΠΊΠ°, Π·Π°Π»ΠΈΠ»ΠΈ ΠΊΠΎΠ½ΡΡΠ°ΠΊΡ, Π½ΠΎ ΡΠ΅ΠΊΡΡΠ°Ρ Π΄Π°ΡΠ° ΠΌΠ΅Π½ΡΡΠ΅ Π΄Π°ΡΡ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ
* - FirstStageFunding: ΠΡΠΎΠ΄Π°ΠΆΠΈ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ
* - FirstStageEnd: ΠΠΊΠΎΠ½ΡΠ΅Π½Ρ ΠΏΡΠΎΠ΄Π°ΠΆΠΈ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ, Π½ΠΎ Π΅ΡΠ΅ Π½Π΅ Π²ΡΠ·Π²Π°Π½ ΡΠΈΠ½Π°Π»ΠΈΠ·Π°ΡΠΎΡ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ
* - SecondStageFunding: ΠΡΠΎΠ΄Π°ΠΆΠΈ Π²ΡΠΎΡΠΎΠ³ΠΎ ΡΡΠ°ΠΏΠ°
* - SecondStageEnd: ΠΠΊΠΎΠ½ΡΠ΅Π½Ρ ΠΏΡΠΎΠ΄Π°ΠΆΠΈ Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ, Π½ΠΎ Π½Π΅ Π²ΡΠ·Π²Π°Π½ ΡΠΈΠ½Π°Π»ΠΈΠ·Π°ΡΠΎΡ Π²ΡΠΎΡΠΎΠΉ ΡΠ΄Π°Π΄ΠΈΠΈ
* - Success: Π£ΡΠΏΠ΅ΡΠ½ΠΎ Π·Π°ΠΊΡΡΠ»ΠΈ ICO
* - Failure: ΠΠ΅ ΡΠΎΠ±ΡΠ°Π»ΠΈ Soft Cap
* - Refunding: ΠΠΎΠ·Π²ΡΠ°ΡΠ°Π΅ΠΌ ΡΠΎΠ±ΡΠ°Π½Π½ΡΠΉ ΡΡΠΈΡ
*/
enum State{PreFunding, FirstStageFunding, FirstStageEnd, SecondStageFunding, SecondStageEnd, Success, Failure, Refunding}
// Π‘ΠΎΠ±ΡΡΠΈΠ΅ ΠΏΠΎΠΊΡΠΏΠΊΠΈ ΡΠΎΠΊΠ΅Π½Π°
event Invested(address indexed investor, uint weiAmount, uint tokenAmount, uint centAmount, uint txId);
// Π‘ΠΎΠ±ΡΡΠΈΠ΅ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΡ ΠΊΡΡΡΠ° eth
event ExchangeRateChanged(uint oldExchangeRate, uint newExchangeRate);
// Π‘ΠΎΠ±ΡΡΠΈΠ΅ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΡ Π΄Π°ΡΡ ΠΎΠΊΠΎΠ½ΡΠ°Π½ΠΈΡ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ
event FirstStageStartsAtChanged(uint newFirstStageStartsAt);
event FirstStageEndsAtChanged(uint newFirstStageEndsAt);
// Π‘ΠΎΠ±ΡΡΠΈΠ΅ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΡ Π΄Π°ΡΡ ΠΎΠΊΠΎΠ½ΡΠ°Π½ΠΈΡ Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ
event SecondStageStartsAtChanged(uint newSecondStageStartsAt);
event SecondStageEndsAtChanged(uint newSecondStageEndsAt);
// Π‘ΠΎΠ±ΡΡΠΈΠ΅ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΡ Soft Cap'Π°
event SoftCapChanged(uint newGoal);
// Π‘ΠΎΠ±ΡΡΠΈΠ΅ ΠΈΠ·ΠΌΠ΅Π½Π΅Π½ΠΈΡ Hard Cap'Π°
event HardCapChanged(uint newGoal);
// ΠΠΎΠ½ΡΡΡΡΠΊΡΠΎΡ
function AllocatedCappedCrowdsale(uint _currentEtherRateInCents, address _token, address _destinationMultisigWallet, uint _firstStageStartsAt, uint _firstStageEndsAt, uint _secondStageStartsAt, uint _secondStageEndsAt, address _advisorsAccount, address _marketingAccount, address _supportAccount, address _teamAccount, uint _teamTokensIssueDate) {
requireNotEmptyAddress(_destinationMultisigWallet);
// ΠΡΠΎΠ²Π΅ΡΠΊΠ°, ΡΡΠΎ Π΄Π°ΡΡ ΡΡΡΠ°Π½ΠΎΠ²Π»Π΅Π½Ρ
require(_firstStageStartsAt != 0);
require(_firstStageEndsAt != 0);
require(_firstStageStartsAt < _firstStageEndsAt);
require(_secondStageStartsAt != 0);
require(_secondStageEndsAt != 0);
require(_secondStageStartsAt < _secondStageEndsAt);
require(_teamTokensIssueDate != 0);
// Π’ΠΎΠΊΠ΅Π½, ΠΊΠΎΡΠΎΡΡΠΉ ΠΏΠΎΠ΄Π΄Π΅ΡΠΆΠΈΠ²Π°Π΅Ρ ΡΠΆΠΈΠ³Π°Π½ΠΈΠ΅
token = BurnableCrowdsaleToken(_token);
destinationMultisigWallet = _destinationMultisigWallet;
firstStageStartsAt = _firstStageStartsAt;
firstStageEndsAt = _firstStageEndsAt;
secondStageStartsAt = _secondStageStartsAt;
secondStageEndsAt = _secondStageEndsAt;
// ΠΠ΄ΡΠ΅ΡΠ° ΠΊΠΎΡΠ΅Π»ΡΠΊΠΎΠ² Π΄Π»Ρ Π°Π΄Π²ΠΈΠ·ΠΎΡΠΎΠ², ΠΌΠ°ΡΠΊΠ΅ΡΠΈΠ½Π³Π°, ΠΊΠΎΠΌΠ°Π½Π΄Ρ
advisorsAccount = _advisorsAccount;
marketingAccount = _marketingAccount;
supportAccount = _supportAccount;
teamAccount = _teamAccount;
teamTokensIssueDate = _teamTokensIssueDate;
currentEtherRateInCents = _currentEtherRateInCents;
secondStageTokensForSale = secondStageTotalSupply.sub(secondStageReserve);
}
/**
* Π€ΡΠ½ΠΊΡΠΈΡ, ΠΈΠ½ΠΈΡΠΈΠΈΡΡΡΡΠ°Ρ Π½ΡΠΆΠ½ΠΎΠ΅ ΠΊΠΎΠ»-Π²ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² Π΄Π»Ρ ΠΏΠ΅ΡΠ²ΠΎΠ³ΠΎ ΡΡΠ°ΠΏΠ° ΠΏΡΠΎΠ΄Π°ΠΆ, Π²ΡΠ·Π²Π°ΡΡ ΠΌΠΎΠΆΠ½ΠΎ ΡΠΎΠ»ΡΠΊΠΎ 1 ΡΠ°Π·
*/
function mintTokensForFirstStage() public onlyOwner {
// ΠΡΠ»ΠΈ ΡΠΆΠ΅ ΡΠΎΠ·Π΄Π°Π»ΠΈ ΡΠΎΠΊΠ΅Π½Ρ Π΄Π»Ρ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ, Π΄Π΅Π»Π°Π΅ΠΌ ΠΎΡΠΊΠ°Ρ
require(!isFirstStageTokensMinted);
uint tokenMultiplier = 10 ** token.decimals();
token.mintToAddress(firstStageTotalSupply.mul(tokenMultiplier), address(this));
isFirstStageTokensMinted = true;
}
/**
* Π€ΡΠ½ΠΊΡΠΈΡ, ΠΈΠ½ΠΈΡΠΈΠΈΡΡΡΡΠ°Ρ Π½ΡΠΆΠ½ΠΎΠ΅ ΠΊΠΎΠ»-Π²ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² Π΄Π»Ρ Π²ΡΠΎΡΠΎΠ³ΠΎ ΡΡΠ°ΠΏΠ° ΠΏΡΠΎΠ΄Π°ΠΆ, ΡΠΎΠ»ΡΠΊΠΎ Π² ΡΠ»ΡΡΠ°Π΅, Π΅ΡΠ»ΠΈ ΡΡΠΎ Π΅ΡΠ΅ Π½Π΅ ΡΠ΄Π΅Π»Π°Π½ΠΎ ΠΈ Π±ΡΠ»ΠΈ ΡΠΎΠ·Π΄Π°Π½Ρ ΡΠΎΠΊΠ΅Π½Ρ Π΄Π»Ρ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ
*/
function mintTokensForSecondStage() private {
// ΠΡΠ»ΠΈ ΡΠΆΠ΅ ΡΠΎΠ·Π΄Π°Π»ΠΈ ΡΠΎΠΊΠ΅Π½Ρ Π΄Π»Ρ Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ, Π΄Π΅Π»Π°Π΅ΠΌ ΠΎΡΠΊΠ°Ρ
require(!isSecondStageTokensMinted);
require(isFirstStageTokensMinted);
uint tokenMultiplier = 10 ** token.decimals();
token.mintToAddress(secondStageTotalSupply.mul(tokenMultiplier), address(this));
isSecondStageTokensMinted = true;
}
/**
* Π€ΡΠ½ΠΊΡΠΈΡ Π²ΠΎΠ·Π²ΡΠ°ΡΠ°ΡΡΠ°Ρ ΡΠ΅ΠΊΡΡΡΡ ΡΡΠΎΠΈΠΌΠΎΡΡΡ 1 ΡΠΎΠΊΠ΅Π½Π° Π² wei
*/
function getOneTokenInWei() external constant returns(uint){
return oneTokenInCents.mul(10 ** 18).div(currentEtherRateInCents);
}
/**
* Π€ΡΠ½ΠΊΡΠΈΡ, ΠΊΠΎΡΠΎΡΠ°Ρ ΠΏΠ΅ΡΠ΅Π²ΠΎΠ΄ΠΈΡ wei Π² ΡΠ΅Π½ΡΡ ΠΏΠΎ ΡΠ΅ΠΊΡΡΠ΅ΠΌΡ ΠΊΡΡΡΡ
*/
function getWeiInCents(uint value) public constant returns(uint){
return currentEtherRateInCents.mul(value).div(10 ** 18);
}
/**
* ΠΠ΅ΡΠ΅Π²ΠΎΠ΄ ΡΠΎΠΊΠ΅Π½ΠΎΠ² ΠΏΠΎΠΊΡΠΏΠ°ΡΠ΅Π»Ρ
*/
function assignTokens(address receiver, uint tokenAmount) private {
// ΠΡΠ»ΠΈ ΠΏΠ΅ΡΠ΅Π²ΠΎΠ΄ Π½Π΅ ΡΠ΄Π°Π»ΡΡ, ΠΎΡΠΊΠ°ΡΡΠ²Π°Π΅ΠΌ ΡΡΠ°Π½Π·Π°ΠΊΡΠΈΡ
if (!token.transfer(receiver, tokenAmount)) revert();
}
/**
* Fallback ΡΡΠ½ΠΊΡΠΈΡ Π²ΡΠ·ΡΠ²Π°ΡΡΠ°ΡΡΡ ΠΏΡΠΈ ΠΏΠ΅ΡΠ΅Π²ΠΎΠ΄Π΅ ΡΡΠΈΡΠ°
*/
function() payable {
buy();
}
/**
* ΠΠΈΠ·ΠΊΠΎΡΡΠΎΠ²Π½Π΅Π²Π°Ρ ΡΡΠ½ΠΊΡΠΈΡ ΠΏΠ΅ΡΠ΅Π²ΠΎΠ΄Π° ΡΡΠΈΡΠ° ΠΈ Π²ΡΠ΄Π°ΡΠΈ ΡΠΎΠΊΠ΅Π½ΠΎΠ²
*/
function internalAssignTokens(address receiver, uint tokenAmount, uint weiAmount, uint centAmount, uint txId) internal {
// ΠΠ΅ΡΠ΅Π²ΠΎΠ΄ΠΈΠΌ ΡΠΎΠΊΠ΅Π½Ρ ΠΈΠ½Π²Π΅ΡΡΠΎΡΡ
assignTokens(receiver, tokenAmount);
// ΠΡΠ·ΡΠ²Π°Π΅ΠΌ ΡΠΎΠ±ΡΡΠΈΠ΅
Invested(receiver, weiAmount, tokenAmount, centAmount, txId);
// ΠΠΎΠΆΠ΅Ρ ΠΏΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΡΡΡΡ Π² Π½Π°ΡΠ»Π΅Π΄Π½ΠΈΠΊΠ°Ρ
}
/**
* ΠΠ½Π²Π΅ΡΡΠΈΡΠΈΠΈ
* ΠΠΎΠ»ΠΆΠ΅Π½ Π±ΡΡΡ Π²ΠΊΠ»ΡΡΠ΅Π½ ΡΠ΅ΠΆΠΈΠΌ ΠΏΡΠΎΠ΄Π°ΠΆ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΠΈΠ»ΠΈ Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ ΠΈ Π½Π΅ ΡΠΎΠ±ΡΠ°Π½ Hard Cap
* @param receiver - ΡΡΠΈΡΠ½ΡΠΉ Π°Π΄ΡΠ΅Ρ ΠΏΠΎΠ»ΡΡΠ°ΡΠ΅Π»Ρ
* @param txId - id Π²Π½Π΅ΡΠ½Π΅ΠΉ ΡΡΠ°Π½Π·Π°ΠΊΡΠΈΠΈ
*/
function internalInvest(address receiver, uint weiAmount, uint txId) stopInEmergency inFirstOrSecondFundingState notHardCapReached internal {
State currentState = getState();
uint tokenMultiplier = 10 ** token.decimals();
uint amountInCents = getWeiInCents(weiAmount);
// ΠΡΠ΅Π½Ρ Π²Π½ΠΈΠΌΠ°ΡΠ΅Π»ΡΠ½ΠΎ Π½ΡΠΆΠ½ΠΎ ΠΌΠ΅Π½ΡΡΡ Π·Π½Π°ΡΠ΅Π½ΠΈΡ, Ρ.ΠΊ. Π΄Π»Ρ Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ 1000%, ΡΡΠΎΠ±Ρ ΡΡΠ΅ΡΡΡ Π΄ΡΠΎΠ±Π½ΡΠ΅ Π·Π½Π°ΡΠ΅Π½ΠΈΡ
uint bonusPercentage = 0;
uint bonusStateMultiplier = 1;
// Π΅ΡΠ»ΠΈ Π·Π°ΠΏΡΡΠ΅Π½Π° ΠΏΠ΅ΡΠ²Π°Ρ ΡΡΠ°Π΄ΠΈΡ, Π² ΠΊΠΎΠ½ΡΡΡΡΠΊΡΠΎΡΠ΅ ΡΠΆΠ΅ Π²ΡΠΏΡΡΡΠΈΠ»ΠΈ Π½ΡΠΆΠ½ΠΎΠ΅ ΠΊΠΎΠ»-Π²ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² Π΄Π»Ρ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ
if (currentState == State.FirstStageFunding){
// ΠΌΠ΅Π½ΡΡΠ΅ 25000$ Π½Π΅ ΠΏΡΠΈΠ½ΠΈΠΌΠ°Π΅ΠΌ
require(amountInCents >= 2500000);
// [25000$ - 50000$) - 50% Π±ΠΎΠ½ΡΡΠ°
if (amountInCents >= 2500000 && amountInCents < 5000000){
bonusPercentage = 50;
// [50000$ - 100000$) - 75% Π±ΠΎΠ½ΡΡΠ°
}else if(amountInCents >= 5000000 && amountInCents < 10000000){
bonusPercentage = 75;
// >= 100000$ - 100% Π±ΠΎΠ½ΡΡΠ°
}else if(amountInCents >= 10000000){
bonusPercentage = 100;
}else{
revert();
}
// Π΅ΡΠ»ΠΈ Π·Π°ΠΏΡΡΠ΅Π½Π° Π²ΡΠΎΡΠ°Ρ ΡΡΠ°Π΄ΠΈΡ
} else if(currentState == State.SecondStageFunding){
// ΠΡΠΎΡΠ΅Π½Ρ ΠΏΡΠΎΠ΄Π°Π½Π½ΡΡ
ΡΠΎΠΊΠ΅Π½ΠΎΠ², Π±ΡΠ΄Π΅ΠΌ ΡΡΠΈΡΠ°ΡΡ Ρ ΠΌΠ½ΠΎΠΆΠΈΡΠ΅Π»Π΅ΠΌ 10, Ρ.ΠΊ. Π΅ΡΡΡ Π΄ΡΠΎΠ±Π½ΡΠ΅ Π·Π½Π°ΡΠ΅Π½ΠΈΡ
bonusStateMultiplier = 10;
// ΠΠΎΠ»-Π²ΠΎ ΠΏΡΠΎΠ΄Π°Π½Π½ΡΡ
ΡΠΎΠΊΠ΅Π½ΠΎΠ² Π½ΡΠΆΠ½ΠΎ ΡΡΠΈΡΠ°ΡΡ ΠΎΡ Π·Π½Π°ΡΠ΅Π½ΠΈΡ ΡΠ΅Ρ
ΡΠΎΠΊΠ΅Π½ΠΎΠ², ΠΊΠΎΡΠΎΡΡΠ΅ ΠΏΡΠ΅Π΄Π½Π°Π·Π½Π°ΡΠ΅Π½Ρ Π΄Π»Ρ ΠΏΡΠΎΠ΄Π°ΠΆ, Ρ.Π΅. secondStageTokensForSale
uint tokensSoldPercentage = secondStageTokensSold.mul(100).div(secondStageTokensForSale.mul(tokenMultiplier));
// ΠΌΠ΅Π½ΡΡΠ΅ 7$ Π½Π΅ ΠΏΡΠΈΠ½ΠΈΠΌΠ°Π΅ΠΌ
require(amountInCents >= 700);
// (0% - 10%) - 20% Π±ΠΎΠ½ΡΡΠ°
if (tokensSoldPercentage >= 0 && tokensSoldPercentage < 10){
bonusPercentage = 200;
// [10% - 20%) - 17.5% Π±ΠΎΠ½ΡΡΠ°
}else if (tokensSoldPercentage >= 10 && tokensSoldPercentage < 20){
bonusPercentage = 175;
// [20% - 30%) - 15% Π±ΠΎΠ½ΡΡΠ°
}else if (tokensSoldPercentage >= 20 && tokensSoldPercentage < 30){
bonusPercentage = 150;
// [30% - 40%) - 12.5% Π±ΠΎΠ½ΡΡΠ°
}else if (tokensSoldPercentage >= 30 && tokensSoldPercentage < 40){
bonusPercentage = 125;
// [40% - 50%) - 10% Π±ΠΎΠ½ΡΡΠ°
}else if (tokensSoldPercentage >= 40 && tokensSoldPercentage < 50){
bonusPercentage = 100;
// [50% - 60%) - 8% Π±ΠΎΠ½ΡΡΠ°
}else if (tokensSoldPercentage >= 50 && tokensSoldPercentage < 60){
bonusPercentage = 80;
// [60% - 70%) - 6% Π±ΠΎΠ½ΡΡΠ°
}else if (tokensSoldPercentage >= 60 && tokensSoldPercentage < 70){
bonusPercentage = 60;
// [70% - 80%) - 4% Π±ΠΎΠ½ΡΡΠ°
}else if (tokensSoldPercentage >= 70 && tokensSoldPercentage < 80){
bonusPercentage = 40;
// [80% - 90%) - 2% Π±ΠΎΠ½ΡΡΠ°
}else if (tokensSoldPercentage >= 80 && tokensSoldPercentage < 90){
bonusPercentage = 20;
// >= 90% - 0% Π±ΠΎΠ½ΡΡΠ°
}else if (tokensSoldPercentage >= 90){
bonusPercentage = 0;
}else{
revert();
}
} else revert();
// ΡΠΊΠΎΠ»ΡΠΊΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² Π½ΡΠΆΠ½ΠΎ Π²ΡΠ΄Π°ΡΡ Π±Π΅Π· Π±ΠΎΠ½ΡΡΠ°
uint resultValue = amountInCents.mul(tokenMultiplier).div(oneTokenInCents);
// Ρ ΡΡΠ΅ΡΠΎΠΌ Π±ΠΎΠ½ΡΡΠ°
uint tokenAmount = resultValue.mul(bonusStateMultiplier.mul(100).add(bonusPercentage)).div(bonusStateMultiplier.mul(100));
// ΠΊΡΠ°Π΅Π²ΠΎΠΉ ΡΠ»ΡΡΠ°ΠΉ, ΠΊΠΎΠ³Π΄Π° Π·Π°ΠΏΡΠΎΡΠΈΠ»ΠΈ Π±ΠΎΠ»ΡΡΠ΅, ΡΠ΅ΠΌ ΠΌΠΎΠΆΠ΅ΠΌ Π²ΡΠ΄Π°ΡΡ
uint tokensLeft = getTokensLeftForSale(currentState);
if (tokenAmount > tokensLeft){
tokenAmount = tokensLeft;
}
// ΠΠΎΠ»-Π²ΠΎ 0?, Π΄Π΅Π»Π°Π΅ΠΌ ΠΎΡΠΊΠ°Ρ
require(tokenAmount != 0);
// ΠΠΎΠ²ΡΠΉ ΠΈΠ½Π²Π΅ΡΡΠΎΡ?
if (investedAmountOf[receiver] == 0) {
investorCount++;
}
// ΠΠΈΠ΄Π°Π΅ΠΌ ΡΠΎΠΊΠ΅Π½Ρ ΠΈΠ½Π²Π΅ΡΡΠΎΡΡ
internalAssignTokens(receiver, tokenAmount, weiAmount, amountInCents, txId);
// ΠΠ±Π½ΠΎΠ²Π»ΡΠ΅ΠΌ ΡΡΠ°ΡΠΈΡΡΠΈΠΊΡ
updateStat(currentState, receiver, tokenAmount, weiAmount);
// Π¨Π»Π΅ΠΌ Π½Π° ΠΊΠΎΡΠ΅Π»ΡΠΊ ΡΡΠΈΡ
// Π€ΡΠ½ΠΊΡΠΈΡ - ΠΏΡΠΎΡΠ»ΠΎΠΉΠΊΠ° Π΄Π»Ρ Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎΡΡΠΈ ΠΏΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΡ Π² Π΄ΠΎΡΠ΅ΡΠ½ΠΈΡ
ΠΊΠ»Π°ΡΡΠ°Ρ
// ΠΡΠ»ΠΈ ΡΡΠΎ Π²Π½Π΅ΡΠ½ΠΈΠΉ Π²ΡΠ·ΠΎΠ², ΡΠΎ Π΄Π΅ΠΏΠΎΠ·ΠΈΡ Π½Π΅ ΠΊΠ»Π°Π΄Π΅ΠΌ
if (txId == 0){
internalDeposit(destinationMultisigWallet, weiAmount);
}
// ΠΠΎΠΆΠ΅Ρ ΠΏΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΡΡΡΡ Π² Π½Π°ΡΠ»Π΅Π΄Π½ΠΈΠΊΠ°Ρ
}
/**
* ΠΠΈΠ·ΠΊΠΎΡΡΠΎΠ²Π½Π΅Π²Π°Ρ ΡΡΠ½ΠΊΡΠΈΡ ΠΏΠ΅ΡΠ΅Π²ΠΎΠ΄Π° ΡΡΠΈΡΠ° Π½Π° ΠΊΠΎΠ½ΡΡΠ°ΠΊΡ, ΡΡΠ½ΠΊΡΠΈΡ Π΄ΠΎΡΡΡΠΏΠ½Π° Π΄Π»Ρ ΠΏΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΡ Π² Π΄ΠΎΡΠ΅ΡΠ½ΠΈΡ
ΠΊΠ»Π°ΡΡΠ°Ρ
, Π½ΠΎ Π½Π΅ ΠΏΡΠ±Π»ΠΈΡΠ½Π°
*/
function internalDeposit(address receiver, uint weiAmount) internal{
// ΠΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΡΡΡ Π² Π½Π°ΡΠ»Π΅Π΄Π½ΠΈΠΊΠ°Ρ
}
/**
* ΠΠΈΠ·ΠΊΠΎΡΡΠΎΠ²Π½Π΅Π²Π°Ρ ΡΡΠ½ΠΊΡΠΈΡ Π΄Π»Ρ Π²ΠΎΠ·Π²ΡΠ°ΡΠ° ΡΡΠ΅Π΄ΡΡΠ², ΡΡΠ½ΠΊΡΠΈΡ Π΄ΠΎΡΡΡΠΏΠ½Π° Π΄Π»Ρ ΠΏΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΡ Π² Π΄ΠΎΡΠ΅ΡΠ½ΠΈΡ
ΠΊΠ»Π°ΡΡΠ°Ρ
, Π½ΠΎ Π½Π΅ ΠΏΡΠ±Π»ΠΈΡΠ½Π°
*/
function internalRefund(address receiver, uint weiAmount) internal{
// ΠΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΡΡΡ Π² Π½Π°ΡΠ»Π΅Π΄Π½ΠΈΠΊΠ°Ρ
}
/**
* ΠΠΈΠ·ΠΊΠΎΡΡΠΎΠ²Π½Π΅Π²Π°Ρ ΡΡΠ½ΠΊΡΠΈΡ Π΄Π»Ρ Π²ΠΊΠ»ΡΡΠ΅Π½ΠΈΡ ΡΠ΅ΠΆΠΈΠΌΠ° Π²ΠΎΠ·Π²ΡΠ°ΡΠ° ΡΡΠ΅Π΄ΡΡΠ²
*/
function internalEnableRefunds() internal{
// ΠΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΡΡΡ Π² Π½Π°ΡΠ»Π΅Π΄Π½ΠΈΠΊΠ°Ρ
}
/**
* Π‘ΠΏΠ΅Ρ. ΡΡΠ½ΠΊΡΠΈΡ, ΠΊΠΎΡΠΎΡΠ°Ρ ΠΏΠΎΠ·Π²ΠΎΠ»ΡΠ΅Ρ ΠΏΡΠΎΠ΄Π°Π²Π°ΡΡ ΡΠΎΠΊΠ΅Π½Ρ Π²Π½Π΅ ΡΠ΅Π½ΠΎΠ²ΠΎΠΉ ΠΏΠΎΠ»ΠΈΡΠΈΠΊΠΈ, Π΄ΠΎΡΡΡΠΏΠΊΠ° ΡΠΎΠ»ΡΠΊΠΎ Π²Π»Π°Π΄Π΅Π»ΡΡΡ
* Π Π΅Π·ΡΠ»ΡΡΠ°ΡΡ ΠΏΠΈΡΡΡΡΡ Π² ΠΎΠ±ΡΡΡ ΡΡΠ°ΡΠΈΡΡΠΈΠΊΡ, Π±Π΅Π· ΡΠ°Π·Π΄Π΅Π»Π΅Π½ΠΈΡ Π½Π° ΡΡΠ°Π΄ΠΈΠΈ
* @param receiver - ΠΏΠΎΠ»ΡΡΠ°ΡΠ΅Π»Ρ
* @param tokenAmount - ΠΎΠ±ΡΠ΅Π΅ ΠΊΠΎΠ»-Π²ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² c decimals!!!
* @param weiAmount - ΡΠ΅Π½Π° Π² wei
*/
function internalPreallocate(State currentState, address receiver, uint tokenAmount, uint weiAmount) internal {
// CΠΊΠΎΠ»ΡΠΊΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² ΠΎΡΡΠ°Π»ΠΎΡΡ Π΄Π»Ρ ΠΏΡΠΎΠ΄Π°ΠΆΠΈ? ΠΠΎΠ»ΡΡΠ΅ ΡΡΠΎΠ³ΠΎ Π·Π½Π°ΡΠ΅Π½ΠΈΡ Π²ΡΠ΄Π°ΡΡ Π½Π΅ ΠΌΠΎΠΆΠ΅ΠΌ!
require(getTokensLeftForSale(currentState) >= tokenAmount);
// ΠΠΎΠΆΠ΅Ρ Π±ΡΡΡ 0, Π²ΡΠ΄Π°Π΅ΠΌ ΡΠΎΠΊΠ΅Π½Ρ Π±Π΅ΡΠΏΠ»Π°ΡΠ½ΠΎ
internalAssignTokens(receiver, tokenAmount, weiAmount, getWeiInCents(weiAmount), 0);
// ΠΠ±Π½ΠΎΠ²Π»ΡΠ΅ΠΌ ΡΡΠ°ΡΠΈΡΡΠΈΠΊΡ
updateStat(currentState, receiver, tokenAmount, weiAmount);
// ΠΠΎΠΆΠ΅Ρ ΠΏΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΡΡΡΡ Π² Π½Π°ΡΠ»Π΅Π΄Π½ΠΈΠΊΠ°Ρ
}
/**
* ΠΠΈΠ·ΠΊΠΎΡΡΠΎΠ²Π½Π΅Π²Π°Ρ ΡΡΠ½ΠΊΡΠΈΡ Π΄Π»Ρ Π΄Π΅ΠΉΡΡΠ²ΠΈΠΉ, Π² ΡΠ»ΡΡΠ°Π΅ ΡΡΠΏΠ΅Ρ
Π°
*/
function internalSuccessOver() internal {
// ΠΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΡΡΡ Π² Π½Π°ΡΠ»Π΅Π΄Π½ΠΈΠΊΠ°Ρ
}
/**
* Π€ΡΠ½ΠΊΡΠΈΡ, ΠΊΠΎΡΠΎΡΠ°Ρ ΠΏΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΡΡΡ Π² Π½Π°Π΄Π»Π΅Π΄Π½ΠΈΠΊΠ°Ρ
ΠΈ Π²ΡΠΏΠΎΠ»Π½ΡΠ΅ΡΡΡ ΠΏΠΎΡΠ»Π΅ ΡΡΡΠ°Π½ΠΎΠ²ΠΊΠΈ Π°Π΄ΡΠ΅ΡΠ° Π°ΠΊΠΊΠ°ΡΠ½ΡΠ° Π΄Π»Ρ ΠΏΠ΅ΡΠ΅Π²ΠΎΠ΄Π° ΡΡΠ΅Π΄ΡΡΠ²
*/
function internalSetDestinationMultisigWallet(address destinationAddress) internal{
}
/**
* ΠΠ±Π½ΠΎΠ²Π»ΡΠ΅ΠΌ ΡΡΠ°ΡΠΈΡΡΠΈΠΊΡ Π΄Π»Ρ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΠΈΠ»ΠΈ Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ
*/
function updateStat(State currentState, address receiver, uint tokenAmount, uint weiAmount) private{
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokenAmount);
// ΠΡΠ»ΠΈ ΡΡΠΎ ΠΏΠ΅ΡΠ²Π°Ρ ΡΡΠ°Π΄ΠΈΡ
if (currentState == State.FirstStageFunding){
// Π£Π²Π΅Π»ΠΈΡΠΈΠ²Π°Π΅ΠΌ ΡΡΠ°ΡΡ
firstStageRaisedInWei = firstStageRaisedInWei.add(weiAmount);
firstStageTokensSold = firstStageTokensSold.add(tokenAmount);
}
// ΠΡΠ»ΠΈ ΡΡΠΎ Π²ΡΠΎΡΠ°Ρ ΡΡΠ°Π΄ΠΈΡ
if (currentState == State.SecondStageFunding){
// Π£Π²Π΅Π»ΠΈΡΠΈΠ²Π°Π΅ΠΌ ΡΡΠ°ΡΡ
secondStageRaisedInWei = secondStageRaisedInWei.add(weiAmount);
secondStageTokensSold = secondStageTokensSold.add(tokenAmount);
}
investedAmountOf[receiver] = investedAmountOf[receiver].add(weiAmount);
tokenAmountOf[receiver] = tokenAmountOf[receiver].add(tokenAmount);
}
/**
* Π€ΡΠ½ΠΊΡΠΈΡ, ΠΊΠΎΡΠΎΡΠ°Ρ ΠΏΠΎΠ·Π²ΠΎΠ»ΡΠ΅Ρ ΠΌΠ΅Π½ΡΡΡ Π°Π΄ΡΠ΅Ρ Π°ΠΊΠΊΠ°ΡΠ½ΡΠ°, ΠΊΡΠ΄Π° Π±ΡΠ΄ΡΡ ΠΏΠ΅ΡΠ΅Π²Π΅Π΄Π΅Π½Ρ ΡΡΠ΅Π΄ΡΡΠ²Π°, Π² ΡΠ»ΡΡΠ°Π΅ ΡΡΠΏΠ΅Ρ
Π°,
* ΠΌΠ΅Π½ΡΡΡ ΠΌΠΎΠΆΠ΅Ρ ΡΠΎΠ»ΡΠΊΠΎ Π²Π»Π°Π΄Π΅Π»Π΅Ρ ΠΈ ΡΠΎΠ»ΡΠΊΠΎ Π² ΡΠ»ΡΡΠ°Π΅ Π΅ΡΠ»ΠΈ ΠΏΡΠΎΠ΄Π°ΠΆΠΈ Π΅ΡΠ΅ Π½Π΅ Π·Π°Π²Π΅ΡΡΠ΅Π½Ρ ΡΡΠΏΠ΅Ρ
ΠΎΠΌ
*/
function setDestinationMultisigWallet(address destinationAddress) public onlyOwner canSetDestinationMultisigWallet{
destinationMultisigWallet = destinationAddress;
internalSetDestinationMultisigWallet(destinationAddress);
}
/**
* Π€ΡΠ½ΠΊΡΠΈΡ, ΠΊΠΎΡΠΎΡΠ°Ρ Π·Π°Π΄Π°Π΅Ρ ΡΠ΅ΠΊΡΡΠΈΠΉ ΠΊΡΡΡ eth Π² ΡΠ΅Π½ΡΠ°Ρ
*/
function changeCurrentEtherRateInCents(uint value) public onlyOwner {
// ΠΡΠ»ΠΈ ΡΠ»ΡΡΠ°ΠΉΠ½ΠΎ Π·Π°Π΄Π°Π»ΠΈ 0, Π½Π΅ ΠΎΡΠΊΠ°ΡΡΠ²Π°Π΅ΠΌ ΡΡΠ°Π½Π·Π°ΠΊΡΠΈΡ
require(value > 0);
currentEtherRateInCents = value;
ExchangeRateChanged(currentEtherRateInCents, value);
}
/**
* Π Π°Π·Π΄Π΅Π»ΠΈΠ» Π½Π° 2 ΠΌΠ΅ΡΠΎΠ΄Π°, ΡΡΠΎΠ±Ρ Π½Π΅ Π·Π°ΠΏΡΡΠ°ΡΡΡΡ ΠΏΡΠΈ Π²ΡΠ·ΠΎΠ²Π΅
* ΠΡΠΈ ΡΡΠ½ΠΊΡΠΈΠΈ Π½ΡΠΆΠ½Ρ Π² 2-Ρ
ΡΠ»ΡΡΠ°ΡΡ
: Π½Π΅ΠΌΠ½ΠΎΠ³ΠΎ Π½Π΅ ΡΠΎΠ±ΡΠ°Π»ΠΈ Π΄ΠΎ Cap'Π°, ΡΠ°ΠΌΠΈ Π΄ΠΎΠΊΠΈΠ΄ΡΠ²Π°Π΅ΠΌ Π½Π΅ΠΎΠ±Ρ
ΠΎΠ΄ΠΈΠΌΡΡ ΡΡΠΌΠΌΡ, Π΅ΡΡΡ ΠΏΡΠΈΠ²Π°ΡΠ½ΡΠ΅ ΠΈΠ½Π²Π΅ΡΡΠΎΡΡ, Π΄Π»Ρ ΠΊΠΎΡΠΎΡΡΡ
ΡΡΡΠ΅ΡΡΠ²ΡΡΡ ΠΎΡΠΎΠ±ΡΠ΅ ΡΡΠ»ΠΎΠ²ΠΈΡ
*/
/* ΠΠ»Ρ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ */
function preallocateFirstStage(address receiver, uint tokenAmount, uint weiAmount) public onlyOwner isFirstStageFundingOrEnd {
internalPreallocate(State.FirstStageFunding, receiver, tokenAmount, weiAmount);
}
/* ΠΠ»Ρ Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ, Π²ΡΠ΄Π°ΡΡ ΠΌΠΎΠΆΠ΅ΠΌ Π½Π΅ Π±ΠΎΠ»ΡΡΠ΅ ΠΎΡΡΠ°ΡΠΊΠ° Π΄Π»Ρ ΠΏΡΠΎΠ΄Π°ΠΆΠΈ */
function preallocateSecondStage(address receiver, uint tokenAmount, uint weiAmount) public onlyOwner isSecondStageFundingOrEnd {
internalPreallocate(State.SecondStageFunding, receiver, tokenAmount, weiAmount);
}
/* Π ΡΠ»ΡΡΠ°Π΅ ΡΡΠΏΠ΅Ρ
Π°, Π·Π°Π±Π»ΠΎΠΊΠΈΡΠΎΠ²Π°Π½Π½ΡΠ΅ ΡΠΎΠΊΠ΅Π½Ρ Π΄Π»Ρ ΠΊΠΎΠΌΠ°Π½Π΄Ρ ΠΌΠΎΠ³ΡΡ Π±ΡΡΡ Π²ΠΎΡΡΡΠ΅Π±ΠΎΠ²Π°Π½Ρ ΡΠΎΠ»ΡΠΊΠΎ Π΅ΡΠ»ΠΈ Π½Π°ΡΡΡΠΏΠΈΠ»Π° ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½Π½Π°Ρ Π΄Π°ΡΠ° */
function issueTeamTokens() public onlyOwner inState(State.Success) {
require(block.timestamp >= teamTokensIssueDate);
uint teamTokenTransferAmount = teamTokenAmount.mul(10 ** token.decimals());
if (!token.transfer(teamAccount, teamTokenTransferAmount)) revert();
}
/**
* ΠΠΊΠ»ΡΡΠ°Π΅Ρ ΡΠ΅ΠΆΠΈΠΌ Π²ΠΎΠ·Π²ΡΠ°ΡΠΎΠ², ΡΠΎΠ»ΡΠΊΠΎ Π² ΡΠ»ΡΡΠ°Π΅ Π΅ΡΠ»ΠΈ ΡΠ΅ΠΆΠΈΠΌ Π²ΠΎΠ·Π²ΡΠ°ΡΠ° Π΅ΡΠ΅ Π½Π΅ ΡΡΡΠ°Π½ΠΎΠ²Π»Π΅Π½ ΠΈ ΠΏΡΠΎΠ΄Π°ΠΆΠΈ Π½Π΅ Π·Π°Π²Π΅ΡΡΠ΅Π½Ρ ΡΡΠΏΠ΅Ρ
ΠΎΠΌ
* ΠΡΠ·Π²Π°ΡΡ ΠΌΠΎΠΆΠ½ΠΎ ΡΠΎΠ»ΡΠΊΠΎ 1 ΡΠ°Π·
*/
function enableRefunds() public onlyOwner canEnableRefunds{
isRefundingEnabled = true;
// Π‘ΠΆΠΈΠ³Π°Π΅ΠΌ ΠΎΡΡΠ°ΡΠΊΠΈ Π½Π° Π±Π°Π»Π°Π½ΡΠ΅ ΡΠ΅ΠΊΡΡΠ΅Π³ΠΎ ΠΊΠΎΠ½ΡΡΠ°ΠΊΡΠ°
token.burnAllOwnerTokens();
internalEnableRefunds();
}
/**
* ΠΠΎΠΊΡΠΏΠΊΠ° ΡΠΎΠΊΠ΅Π½ΠΎΠ², ΠΊΠΈΠ΄Π°Π΅ΠΌ ΡΠΎΠΊΠ΅Π½Ρ Π½Π° Π°Π΄ΡΠ΅Ρ ΠΎΡΠΏΡΠ°Π²ΠΈΡΠ΅Π»Ρ
*/
function buy() public payable {
internalInvest(msg.sender, msg.value, 0);
}
/**
* ΠΠΎΠΊΡΠΏΠΊΠ° ΡΠΎΠΊΠ΅Π½ΠΎΠ² ΡΠ΅ΡΠ΅Π· Π²Π½Π΅ΡΠ½ΠΈΠ΅ ΡΠΈΡΡΠ΅ΠΌΡ
*/
function externalBuy(address buyerAddress, uint weiAmount, uint txId) external onlyOwner {
require(txId != 0);
internalInvest(buyerAddress, weiAmount, txId);
}
/**
* ΠΠ½Π²Π΅ΡΡΠΎΡΡ ΠΌΠΎΠ³ΡΡ Π·Π°ΡΡΠ΅Π±ΠΎΠ²Π°ΡΡ Π²ΠΎΠ·Π²ΡΠ°Ρ ΡΡΠ΅Π΄ΡΡΠ², ΡΠΎΠ»ΡΠΊΠΎ Π² ΡΠ»ΡΡΠ°Π΅, Π΅ΡΠ»ΠΈ ΡΠ΅ΠΊΡΡΠ΅Π΅ ΡΠΎΡΡΠΎΡΠ½ΠΈΠ΅ - Refunding
*/
function refund() public inState(State.Refunding) {
// ΠΠΎΠ»ΡΡΠ°Π΅ΠΌ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅, ΠΊΠΎΡΠΎΡΠΎΠ΅ Π½Π°ΠΌ Π±ΡΠ»ΠΎ ΠΏΠ΅ΡΠ΅Π²Π΅Π΄Π΅Π½ΠΎ Π² ΡΡΠΈΡΠ΅
uint weiValue = investedAmountOf[msg.sender];
require(weiValue != 0);
// ΠΠΎΠ»-Π²ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² Π½Π° Π±Π°Π»Π°Π½ΡΠ΅, Π±Π΅ΡΠ΅ΠΌ 2 Π·Π½Π°ΡΠ΅Π½ΠΈΡ: ΠΊΠΎΠ½ΡΡΠ°ΠΊΡ ΠΏΡΠΎΠ΄Π°ΠΆ ΠΈ ΠΊΠΎΠ½ΡΡΠ°ΠΊΡ ΡΠΎΠΊΠ΅Π½Π°.
// ΠΠ΅ΡΠ½ΡΡΡ wei ΠΌΠΎΠΆΠ΅ΠΌ ΡΠΎΠ»ΡΠΊΠΎ ΡΠΎΠ³Π΄Π°, ΠΊΠΎΠ³Π΄Π° ΡΡΠΈ Π·Π½Π°ΡΠ΅Π½ΠΈΡ ΡΠΎΠ²ΠΏΠ°Π΄Π°ΡΡ, Π΅ΡΠ»ΠΈ Π½Π΅ ΡΠΎΠ²ΠΏΠ°Π΄Π°ΡΡ, Π·Π½Π°ΡΠΈΡ Π±ΡΠ»ΠΈ ΠΊΠ°ΠΊΠΈΠ΅-ΡΠΎ
// ΠΌΠ°Π½ΠΈΠΏΡΠ»ΡΡΠΈΠΈ Ρ ΡΠΎΠΊΠ΅Π½Π°ΠΌΠΈ ΠΈ ΡΠ°ΠΊΠΈΠ΅ ΡΠΈΡΡΠ°ΡΠΈΠΈ Π±ΡΠ΄ΡΡ ΡΠ΅ΡΠ°ΡΡΡΡ Π² ΠΈΠ½Π΄ΠΈΠ²ΠΈΠ΄ΡΠ°Π»ΡΠ½ΠΎΠΌ ΠΏΠΎΡΡΠ΄ΠΊΠ΅, ΠΏΠΎ Π·Π°ΠΏΡΠΎΡΡ
uint saleContractTokenCount = tokenAmountOf[msg.sender];
uint tokenContractTokenCount = token.balanceOf(msg.sender);
require(saleContractTokenCount <= tokenContractTokenCount);
investedAmountOf[msg.sender] = 0;
weiRefunded = weiRefunded.add(weiValue);
// Π‘ΠΎΠ±ΡΡΠΈΠ΅ Π³Π΅Π½Π΅ΡΠΈΡΡΠ΅ΡΡΡ Π² Π½Π°ΡΠ»Π΅Π΄Π½ΠΈΠΊΠ°Ρ
internalRefund(msg.sender, weiValue);
}
/**
* Π€ΠΈΠ½Π°Π»ΠΈΠ·Π°ΡΠΎΡ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ, Π²ΡΠ·Π²Π°ΡΡ ΠΌΠΎΠΆΠ΅Ρ ΡΠΎΠ»ΡΠΊΠΎ Π²Π»Π°Π΄Π΅Π»Π΅Ρ ΠΏΡΠΈ ΡΡΠ»ΠΎΠ²ΠΈΠΈ Π΅ΡΠ΅ Π½Π΅Π·Π°Π²Π΅ΡΡΠΈΠ²ΡΠ΅ΠΉΡΡ ΠΏΡΠΎΠ΄Π°ΠΆΠΈ
* ΠΡΠ»ΠΈ Π²ΡΠ·Π²Π°Π½ halt, ΡΠΎ ΡΠΈΠ½Π°Π»ΠΈΠ·Π°ΡΠΎΡ Π²ΡΠ·Π²Π°ΡΡ Π½Π΅ ΠΌΠΎΠΆΠ΅ΠΌ
* ΠΡΠ·Π²Π°ΡΡ ΠΌΠΎΠΆΠ½ΠΎ ΡΠΎΠ»ΡΠΊΠΎ 1 ΡΠ°Π·
*/
function finalizeFirstStage() public onlyOwner isNotSuccessOver {
require(!isFirstStageFinalized);
// Π‘ΠΆΠΈΠ³Π°Π΅ΠΌ ΠΎΡΡΠ°ΡΠΊΠΈ
// ΠΡΠ΅Π³ΠΎ ΠΌΠΎΠΆΠ΅ΠΌ ΠΏΡΠΎΠ΄Π°ΡΡ firstStageTotalSupply
// ΠΡΠΎΠ΄Π°Π»ΠΈ - firstStageTokensSold
// ΠΡΠ΅ ΡΠΎΠΊΠ΅Π½Ρ Π½Π° Π±Π°Π»Π°Π½ΡΠ΅ ΠΊΠΎΠ½ΡΡΠ°ΠΊΡΠ° ΡΠΆΠΈΠ³Π°Π΅ΠΌ - ΡΡΠΎ Π±ΡΠ΄Π΅Ρ ΠΎΡΡΠ°ΡΠΎΠΊ
token.burnAllOwnerTokens();
// ΠΠ΅ΡΠ΅Ρ
ΠΎΠ΄ΠΈΠΌ ΠΊΠΎ Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ
// ΠΡΠ»ΠΈ ΠΏΠΎΠ²ΡΠΎΡΠ½ΠΎ Π²ΡΠ·Π²Π°ΡΡ ΡΠΈΠ½Π°Π»ΠΈΠ·Π°ΡΠΎΡ, ΡΠΎ Π΅ΡΠ΅ ΡΠ°Π· ΡΠΎΠΊΠ΅Π½Ρ Π½Π΅ ΡΠΎΠ·Π΄Π°Π΄ΡΡΡΡ, ΡΡΠ»ΠΎΠ²ΠΈΠ΅ Π²Π½ΡΡΡΠΈ
mintTokensForSecondStage();
isFirstStageFinalized = true;
}
/**
* Π€ΠΈΠ½Π°Π»ΠΈΠ·Π°ΡΠΎΡ Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ, Π²ΡΠ·Π²Π°ΡΡ ΠΌΠΎΠΆΠ΅Ρ ΡΠΎΠ»ΡΠΊΠΎ Π²Π»Π°Π΄Π΅Π»Π΅Ρ, ΠΈ ΡΠΎΠ»ΡΠΊΠΎ Π² ΡΠ»ΡΡΠ°Π΅ ΡΠΈΠ½ΠΈΠ»ΠΈΠ·ΠΈΡΠΎΠ²Π°Π½Π½ΠΎΠΉ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ
* ΠΈ ΡΠΎΠ»ΡΠΊΠΎ Π² ΡΠ»ΡΡΠ°Π΅, Π΅ΡΠ»ΠΈ ΡΠ±ΠΎΡΡ Π΅ΡΠ΅ Π½Π΅ Π·Π°Π²Π΅ΡΡΠΈΠ»ΠΈΡΡ ΡΡΠΏΠ΅Ρ
ΠΎΠΌ. ΠΡΠ»ΠΈ Π²ΡΠ·Π²Π°Π½ halt, ΡΠΎ ΡΠΈΠ½Π°Π»ΠΈΠ·Π°ΡΠΎΡ Π²ΡΠ·Π²Π°ΡΡ Π½Π΅ ΠΌΠΎΠΆΠ΅ΠΌ.
* ΠΡΠ·Π²Π°ΡΡ ΠΌΠΎΠΆΠ½ΠΎ ΡΠΎΠ»ΡΠΊΠΎ 1 ΡΠ°Π·
*/
function finalizeSecondStage() public onlyOwner isNotSuccessOver {
require(isFirstStageFinalized && !isSecondStageFinalized);
// Π‘ΠΆΠΈΠ³Π°Π΅ΠΌ ΠΎΡΡΠ°ΡΠΊΠΈ
// ΠΡΠ΅Π³ΠΎ ΠΌΠΎΠΆΠ΅ΠΌ ΠΏΡΠΎΠ΄Π°ΡΡ secondStageTokensForSale
// ΠΡΠΎΠ΄Π°Π»ΠΈ - secondStageTokensSold
// Π Π°Π·Π½ΠΈΡΡ Π½ΡΠΆΠ½ΠΎ ΡΠΆΠ΅ΡΡ, Π² Π»ΡΠ±ΠΎΠΌ ΡΠ»ΡΡΠ°Π΅
// ΠΡΠ»ΠΈ Π΄ΠΎΡΡΠΈΠ³Π½ΡΡ Soft Cap, ΡΠΎ ΡΡΠΈΡΠ°Π΅ΠΌ Π²ΡΠΎΡΡΡ ΡΡΠ°Π΄ΠΈΡ ΡΡΠΏΠ΅ΡΠ½ΠΎΠΉ
if (isSoftCapGoalReached()){
uint tokenMultiplier = 10 ** token.decimals();
uint remainingTokens = secondStageTokensForSale.mul(tokenMultiplier).sub(secondStageTokensSold);
// ΠΡΠ»ΠΈ ΠΊΠΎΠ»-Π²ΠΎ ΠΎΡΡΠ°Π²ΡΠΈΡ
ΡΡ ΡΠΎΠΊΠ΅Π½ΠΎΠ² > 0, ΡΠΎ ΡΠΆΠΈΠ³Π°Π΅ΠΌ ΠΈΡ
if (remainingTokens > 0){
token.burnOwnerTokens(remainingTokens);
}
// ΠΠ΅ΡΠ΅Π²ΠΎΠ΄ΠΈΠΌ Π½Π° ΠΏΠΎΠ΄Π³ΠΎΡΠΎΠ²Π»Π΅Π½Π½ΡΠ΅ Π°ΠΊΠΊΠ°ΡΠ½ΡΡ: advisorsWalletAddress, marketingWalletAddress, teamWalletAddress
uint advisorsTokenTransferAmount = advisorsTokenAmount.mul(tokenMultiplier);
uint marketingTokenTransferAmount = marketingTokenAmount.mul(tokenMultiplier);
uint supportTokenTransferAmount = supportTokenAmount.mul(tokenMultiplier);
// Π’ΠΎΠΊΠ΅Π½Ρ Π΄Π»Ρ ΠΊΠΎΠΌΠ°Π½Π΄Ρ Π·Π°Π±Π»ΠΎΠΊΠΈΡΠΎΠ²Π°Π½Ρ Π΄ΠΎ Π΄Π°ΡΡ teamTokensIssueDate ΠΈ ΠΌΠΎΠ³ΡΡ Π±ΡΡΡ Π²ΠΎΡΡΡΠ΅Π±ΠΎΠ²Π°Π½Ρ, ΡΠΎΠ»ΡΠΊΠΎ ΠΏΡΠΈ Π²ΡΠ·ΠΎΠ²Π΅ ΡΠΏΠ΅Ρ. ΡΡΠ½ΠΊΡΠΈΠΈ
// issueTeamTokens
if (!token.transfer(advisorsAccount, advisorsTokenTransferAmount)) revert();
if (!token.transfer(marketingAccount, marketingTokenTransferAmount)) revert();
if (!token.transfer(supportAccount, supportTokenTransferAmount)) revert();
// ΠΠΎΠ½ΡΡΠ°ΠΊΡ Π²ΡΠΏΠΎΠ»Π½Π΅Π½!
isSuccessOver = true;
// ΠΡΠ·ΡΠ²Π°Π΅ΠΌ ΠΌΠ΅ΡΠΎΠ΄ ΡΡΠΏΠ΅Ρ
Π°
internalSuccessOver();
}else{
// ΠΡΠ»ΠΈ Π½Π΅ ΡΠΎΠ±ΡΠ°Π»ΠΈ Soft Cap, ΡΠΎ ΡΠΆΠΈΠ³Π°Π΅ΠΌ Π²ΡΠ΅ ΡΠΎΠΊΠ΅Π½Ρ Π½Π° Π±Π°Π»Π°Π½ΡΠ΅ ΠΊΠΎΠ½ΡΡΠ°ΠΊΡΠ°
token.burnAllOwnerTokens();
}
isSecondStageFinalized = true;
}
/**
* ΠΠΎΠ·Π²ΠΎΠ»ΡΠ΅Ρ ΠΌΠ΅Π½ΡΡΡ Π²Π»Π°Π΄Π΅Π»ΡΡΡ Π΄Π°ΡΡ ΡΡΠ°Π΄ΠΈΠΉ
*/
function setFirstStageStartsAt(uint time) public onlyOwner {
firstStageStartsAt = time;
// ΠΡΠ·ΡΠ²Π°Π΅ΠΌ ΡΠΎΠ±ΡΡΠΈΠ΅
FirstStageStartsAtChanged(firstStageStartsAt);
}
function setFirstStageEndsAt(uint time) public onlyOwner {
firstStageEndsAt = time;
// ΠΡΠ·ΡΠ²Π°Π΅ΠΌ ΡΠΎΠ±ΡΡΠΈΠ΅
FirstStageEndsAtChanged(firstStageEndsAt);
}
function setSecondStageStartsAt(uint time) public onlyOwner {
secondStageStartsAt = time;
// ΠΡΠ·ΡΠ²Π°Π΅ΠΌ ΡΠΎΠ±ΡΡΠΈΠ΅
SecondStageStartsAtChanged(secondStageStartsAt);
}
function setSecondStageEndsAt(uint time) public onlyOwner {
secondStageEndsAt = time;
// ΠΡΠ·ΡΠ²Π°Π΅ΠΌ ΡΠΎΠ±ΡΡΠΈΠ΅
SecondStageEndsAtChanged(secondStageEndsAt);
}
/**
* ΠΠΎΠ·Π²ΠΎΠ»ΡΠ΅Ρ ΠΌΠ΅Π½ΡΡΡ Π²Π»Π°Π΄Π΅Π»ΡΡΡ Cap'Ρ
*/
function setSoftCapInCents(uint value) public onlyOwner {
require(value > 0);
softCapFundingGoalInCents = value;
// ΠΡΠ·ΡΠ²Π°Π΅ΠΌ ΡΠΎΠ±ΡΡΠΈΠ΅
SoftCapChanged(softCapFundingGoalInCents);
}
function setHardCapInCents(uint value) public onlyOwner {
require(value > 0);
hardCapFundingGoalInCents = value;
// ΠΡΠ·ΡΠ²Π°Π΅ΠΌ ΡΠΎΠ±ΡΡΠΈΠ΅
HardCapChanged(hardCapFundingGoalInCents);
}
/**
* ΠΡΠΎΠ²Π΅ΡΠΊΠ° ΡΠ±ΠΎΡΠ° Soft Cap'Π°
*/
function isSoftCapGoalReached() public constant returns (bool) {
// ΠΡΠΎΠ²Π΅ΡΠΊΠ° ΠΏΠΎ ΡΠ΅ΠΊΡΡΠ΅ΠΌΡ ΠΊΡΡΡΡ Π² ΡΠ΅Π½ΡΠ°Ρ
, ΡΡΠΈΡΠ°Π΅Ρ ΠΎΡ ΠΎΠ±ΡΠΈΡ
ΠΏΡΠΎΠ΄Π°ΠΆ
return getWeiInCents(weiRaised) >= softCapFundingGoalInCents;
}
/**
* ΠΡΠΎΠ²Π΅ΡΠΊΠ° ΡΠ±ΠΎΡΠ° Hard Cap'Π°
*/
function isHardCapGoalReached() public constant returns (bool) {
// ΠΡΠΎΠ²Π΅ΡΠΊΠ° ΠΏΠΎ ΡΠ΅ΠΊΡΡΠ΅ΠΌΡ ΠΊΡΡΡΡ Π² ΡΠ΅Π½ΡΠ°Ρ
, ΡΡΠΈΡΠ°Π΅Ρ ΠΎΡ ΠΎΠ±ΡΠΈΡ
ΠΏΡΠΎΠ΄Π°ΠΆ
return getWeiInCents(weiRaised) >= hardCapFundingGoalInCents;
}
/**
* ΠΠΎΠ·Π²ΡΠ°ΡΠ°Π΅Ρ ΠΊΠΎΠ»-Π²ΠΎ Π½Π΅ΡΠ°ΡΠΏΡΠΎΠ΄Π°Π½Π½ΡΡ
ΡΠΎΠΊΠ΅Π½ΠΎΠ², ΠΊΠΎΡΠΎΡΡΠ΅ ΠΌΠΎΠΆΠ½ΠΎ ΠΏΡΠΎΠ΄Π°ΡΡ, Π² Π·Π°Π²ΠΈΡΠΈΠΌΠΎΡΡΠΈ ΠΎΡ ΡΡΠ°Π΄ΠΈΠΈ
*/
function getTokensLeftForSale(State forState) public constant returns (uint) {
// ΠΠΎΠ»-Π²ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ², ΠΊΠΎΡΠΎΡΠΎΠ΅ Π°Π΄ΡΠ΅Ρ ΠΊΠΎΠ½ΡΡΠ°ΠΊΡΠ° ΠΌΠΎΠΆΠ΅ΡΡ ΡΠ½ΡΡΡ Ρ owner'Π° ΠΈ Π΅ΡΡΡ ΠΊΠΎΠ»-Π²ΠΎ ΠΎΡΡΠ°Π²ΡΠΈΡ
ΡΡ ΡΠΎΠΊΠ΅Π½ΠΎΠ², ΠΈΠ· ΡΡΠΎΠΉ ΡΡΠΌΠΌΡ Π½ΡΠΆΠ½ΠΎ Π²ΡΡΠ΅ΡΡΡ ΠΊΠΎΠ»-Π²ΠΎ ΠΊΠΎΡΠΎΡΠΎΠ΅ Π½Π΅ ΡΡΠ°ΡΡΠ²ΡΠ΅Ρ Π² ΠΏΡΠΎΠ΄Π°ΠΆΠ΅
uint tokenBalance = token.balanceOf(address(this));
uint tokensReserve = 0;
if (forState == State.SecondStageFunding) tokensReserve = secondStageReserve.mul(10 ** token.decimals());
if (tokenBalance <= tokensReserve){
return 0;
}
return tokenBalance.sub(tokensReserve);
}
/**
* ΠΠΎΠ»ΡΡΠ°Π΅ΠΌ ΡΡΠ΅ΠΉΡ
*
* ΠΠ΅ ΠΏΠΈΡΠ΅ΠΌ Π² ΠΏΠ΅ΡΠ΅ΠΌΠ΅Π½Π½ΡΡ, ΡΡΠΎΠ±Ρ Π½Π΅ Π±ΡΠ»ΠΎ Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎΡΡΠΈ ΠΏΠΎΠΌΠ΅Π½ΡΡΡ ΠΈΠ·Π²Π½Π΅, ΡΠΎΠ»ΡΠΊΠΎ Π²ΡΠ·ΠΎΠ² ΡΡΠ½ΠΊΡΠΈΠΈ ΠΌΠΎΠΆΠ΅Ρ ΠΎΡΡΠ°Π·ΠΈΡΡ ΡΠ΅ΠΊΡΡΠ΅Π΅ ΡΠΎΡΡΠΎΡΠ½ΠΈΠ΅
* Π‘ΠΌ. Π³ΡΠ°Ρ ΡΠΎΡΡΠΎΡΠ½ΠΈΠΉ
*/
function getState() public constant returns (State) {
// ΠΠΎΠ½ΡΡΠ°ΠΊΡ Π²ΡΠΏΠΎΠ»Π½Π΅Π½
if (isSuccessOver) return State.Success;
// ΠΠΎΠ½ΡΡΠ°ΠΊΡ Π½Π°Ρ
ΠΎΠ΄ΠΈΡΡΡ Π² ΡΠ΅ΠΆΠΈΠΌΠ΅ Π²ΠΎΠ·Π²ΡΠ°ΡΠ°
if (isRefundingEnabled) return State.Refunding;
// ΠΠΎΠ½ΡΡΠ°ΠΊΡ Π΅ΡΠ΅ Π½Π΅ Π½Π°ΡΠ°Π» Π΄Π΅ΠΉΡΡΠ²ΠΎΠ²Π°ΡΡ
if (block.timestamp < firstStageStartsAt) return State.PreFunding;
//ΠΡΠ»ΠΈ ΠΏΠ΅ΡΠ²Π°Ρ ΡΡΠ°Π΄ΠΈΡ - Π½Π΅ ΡΠΈΠ½Π°Π»ΠΈΠ·ΠΈΡΠΎΠ²Π°Π½Π°
if (!isFirstStageFinalized){
// Π€Π»Π°Π³ ΡΠΎΠ³ΠΎ, ΡΡΠΎ ΡΠ΅ΠΊΡΡΠ°Ρ Π΄Π°ΡΠ° Π½Π°Ρ
ΠΎΠ΄ΠΈΡΡΡ Π² ΠΈΠ½ΡΠ΅ΡΠ²Π°Π»Π΅ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ
bool isFirstStageTime = block.timestamp >= firstStageStartsAt && block.timestamp <= firstStageEndsAt;
// ΠΡΠ»ΠΈ ΠΈΠ΄Π΅Ρ ΠΏΠ΅ΡΠ²Π°Ρ ΡΡΠ°Π΄ΠΈΡ
if (isFirstStageTime) return State.FirstStageFunding;
// ΠΠ½Π°ΡΠ΅ ΠΏΠ΅ΡΠ²ΡΠΉ ΡΡΠ°ΠΏ - Π·Π°ΠΊΠΎΠ½ΡΠ΅Π½
else return State.FirstStageEnd;
} else {
// ΠΡΠ»ΠΈ ΠΏΠ΅ΡΠ²Π°Ρ ΡΡΠ°Π΄ΠΈΡ ΡΠΈΠ½Π°Π»ΠΈΠ·ΠΈΡΠΎΠ²Π°Π½Π° ΠΈ ΡΠ΅ΠΊΡΡΠ΅Π΅ Π²ΡΠ΅ΠΌΡ Π±Π»ΠΎΠΊ ΡΠ΅ΠΉΠ½Π° ΠΌΠ΅Π½ΡΡΠ΅ Π½Π°ΡΠ°Π»Π° Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ, ΡΠΎ ΡΡΠΎ ΠΎΠ·Π½Π°ΡΠ°Π΅Ρ, ΡΡΠΎ ΠΏΠ΅ΡΠ²Π°Ρ ΡΡΠ°Π΄ΠΈΡ - ΠΎΠΊΠΎΠ½ΡΠ΅Π½Π°
if(block.timestamp < secondStageStartsAt)return State.FirstStageEnd;
// Π€Π»Π°Π³ ΡΠΎΠ³ΠΎ, ΡΡΠΎ ΡΠ΅ΠΊΡΡΠ°Ρ Π΄Π°ΡΠ° Π½Π°Ρ
ΠΎΠ΄ΠΈΡΡΡ Π² ΠΈΠ½ΡΠ΅ΡΠ²Π°Π»Π΅ Π²ΡΠΎΡΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ
bool isSecondStageTime = block.timestamp >= secondStageStartsAt && block.timestamp <= secondStageEndsAt;
// ΠΠ΅ΡΠ²Π°Ρ ΡΡΠ°Π΄ΠΈΡ ΡΠΈΠ½Π°Π»ΠΈΠ·ΠΈΡΠΎΠ²Π°Π½Π°, Π²ΡΠΎΡΠ°Ρ - ΡΠΈΠ½Π°Π»ΠΈΠ·ΠΈΡΠΎΠ²Π°Π½Π°
if (isSecondStageFinalized){
// ΠΡΠ»ΠΈ Π½Π°Π±ΡΠ°Π»ΠΈ Soft Cap ΠΏΡΠΈ ΡΡΠ»ΠΎΠ²ΠΈΠΈ ΡΠΈΠ½Π°Π»ΠΈΠ·Π°ΡΠΈΠΈ Π²ΡΠΎΡΠΎΠΉ ΡΠ΄Π°Π΄ΠΈΠΈ - ΡΡΠΎ ΡΡΠΏΠ΅ΡΠ½ΠΎΠ΅ Π·Π°ΠΊΡΡΡΠΈΠ΅ ΠΏΡΠΎΠ΄Π°ΠΆ
if (isSoftCapGoalReached())return State.Success;
// Π‘ΠΎΠ±ΡΠ°ΡΡ Soft Cap Π½Π΅ ΡΠ΄Π°Π»ΠΎΡΡ, ΡΠ΅ΠΊΡΡΠ΅Π΅ ΡΠΎΡΡΠΎΡΠ½ΠΈΠ΅ - ΠΏΡΠΎΠ²Π°Π»
else return State.Failure;
}else{
// ΠΡΠΎΡΠ°Ρ ΡΡΠ°Π΄ΠΈΡ - Π½Π΅ ΡΠΈΠ½Π°Π»ΠΈΠ·ΠΈΡΠΎΠ²Π°Π½Π°
if (isSecondStageTime)return State.SecondStageFunding;
// ΠΡΠΎΡΠ°Ρ ΡΡΠ°Π΄ΠΈΡ - Π·Π°ΠΊΠΎΠ½ΡΠΈΠ»Π°ΡΡ
else return State.SecondStageEnd;
}
}
}
/**
* ΠΠΎΠ΄ΠΈΡΠΈΠΊΠ°ΡΠΎΡΡ
*/
/** Π’ΠΎΠ»ΡΠΊΠΎ, Π΅ΡΠ»ΠΈ ΡΠ΅ΠΊΡΡΠ΅Π΅ ΡΠΎΡΡΠΎΡΠ½ΠΈΠ΅ ΡΠΎΠΎΡΠ²Π΅ΡΡΠ²ΡΠ΅Ρ ΡΠΎΡΡΠΎΡΠ½ΠΈΡ */
modifier inState(State state) {
require(getState() == state);
_;
}
/** Π’ΠΎΠ»ΡΠΊΠΎ, Π΅ΡΠ»ΠΈ ΡΠ΅ΠΊΡΡΠ΅Π΅ ΡΠΎΡΡΠΎΡΠ½ΠΈΠ΅ - ΠΏΡΠΎΠ΄Π°ΠΆΠΈ: ΠΏΠ΅ΡΠ²Π°Ρ ΠΈΠ»ΠΈ Π²ΡΠΎΡΠ°Ρ ΡΡΠ°Π΄ΠΈΡ */
modifier inFirstOrSecondFundingState() {
State curState = getState();
require(curState == State.FirstStageFunding || curState == State.SecondStageFunding);
_;
}
/** Π’ΠΎΠ»ΡΠΊΠΎ, Π΅ΡΠ»ΠΈ Π½Π΅ Π΄ΠΎΡΡΠΈΠ³Π½ΡΡ Hard Cap */
modifier notHardCapReached(){
require(!isHardCapGoalReached());
_;
}
/** Π’ΠΎΠ»ΡΠΊΠΎ, Π΅ΡΠ»ΠΈ ΡΠ΅ΠΊΡΡΠ΅Π΅ ΡΠΎΡΡΠΎΡΠ½ΠΈΠ΅ - ΠΏΡΠΎΠ΄Π°ΠΆΠΈ ΠΏΠ΅ΡΠ²ΠΎΠΉ ΡΡΠ°Π΄ΠΈΠΈ ΠΈΠ»ΠΈ ΠΏΠ΅ΡΠ²Π°Ρ ΡΡΠ°Π΄ΠΈΡ Π·Π°ΠΊΠΎΠ½ΡΠΈΠ»Π°ΡΡ */
modifier isFirstStageFundingOrEnd() {
State curState = getState();
require(curState == State.FirstStageFunding || curState == State.FirstStageEnd);
_;
}
/** Π’ΠΎΠ»ΡΠΊΠΎ, Π΅ΡΠ»ΠΈ ΠΊΠΎΠ½ΡΡΠ°ΠΊΡ Π½Π΅ ΡΠΈΠ½Π°Π»ΠΈΠ·ΠΈΡΠΎΠ²Π°Π½ */
modifier isNotSuccessOver() {
require(!isSuccessOver);
_;
}
/** Π’ΠΎΠ»ΡΠΊΠΎ, Π΅ΡΠ»ΠΈ ΠΈΠ΄Π΅Ρ Π²ΡΠΎΡΠ°Ρ ΡΡΠ°Π΄ΠΈΡ ΠΈΠ»ΠΈ Π²ΡΠΎΡΠ°Ρ ΡΡΠ°Π΄ΠΈΡ Π·Π°Π²Π΅ΡΡΠΈΠ»Π°ΡΡ */
modifier isSecondStageFundingOrEnd() {
State curState = getState();
require(curState == State.SecondStageFunding || curState == State.SecondStageEnd);
_;
}
/** Π’ΠΎΠ»ΡΠΊΠΎ, Π΅ΡΠ»ΠΈ Π΅ΡΠ΅ Π½Π΅ Π²ΠΊΠ»ΡΡΠ΅Π½ ΡΠ΅ΠΆΠΈΠΌ Π²ΠΎΠ·Π²ΡΠ°ΡΠ° ΠΈ ΠΏΡΠΎΠ΄Π°ΠΆΠΈ Π½Π΅ Π·Π°Π²Π΅ΡΡΠ΅Π½Ρ ΡΡΠΏΠ΅Ρ
ΠΎΠΌ */
modifier canEnableRefunds(){
require(!isRefundingEnabled && getState() != State.Success);
_;
}
/** Π’ΠΎΠ»ΡΠΊΠΎ, Π΅ΡΠ»ΠΈ ΠΏΡΠΎΠ΄Π°ΠΆΠΈ Π½Π΅ Π·Π°Π²Π΅ΡΡΠ΅Π½Ρ ΡΡΠΏΠ΅Ρ
ΠΎΠΌ */
modifier canSetDestinationMultisigWallet(){
require(getState() != State.Success);
_;
}
}
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
/**
* Π¨Π°Π±Π»ΠΎΠ½ ΠΊΠ»Π°ΡΡΠ° Ρ
ΡΠ°Π½ΠΈΠ»ΠΈΡΠ° ΡΡΠ΅Π΄ΡΡΠ², ΠΊΠΎΡΠΎΡΠΎΠ΅ ΠΈΡΠΏΠΎΠ»ΡΠ·ΡΠ΅ΡΡΡ Π² ΠΊΠΎΠ½ΡΡΠ°ΠΊΡΠ΅ ΠΏΡΠΎΠ΄Π°ΠΆ
* ΠΠΎΠ΄Π΄Π΅ΡΠΆΠΈΠ²Π°Π΅Ρ Π²ΠΎΠ·Π²ΡΠ°Ρ ΡΡΠ΅Π΄ΡΡΠ², Π° ΡΠ°ΠΊΡΠ΅ ΠΏΠ΅ΡΠ΅Π²ΠΎΠ΄ ΡΡΠ΅Π΄ΡΡΠ² Π½Π° ΠΊΠΎΡΠ΅Π»Π΅ΠΊ, Π² ΡΠ»ΡΡΠ°Π΅ ΡΡΠΏΠ΅ΡΠ½ΠΎΠ³ΠΎ ΠΏΡΠΎΠ²Π΅Π΄Π΅Π½ΠΈΡ ΠΏΡΠΎΠ΄Π°ΠΆ
*/
contract FundsVault is Ownable, ValidationUtil {
using SafeMath for uint;
using Math for uint;
enum State {Active, Refunding, Closed}
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
/**
* Π£ΠΊΠ°Π·ΡΠ²Π°Π΅ΠΌ Π½Π° ΠΊΠ°ΠΊΠΎΠΉ ΠΊΠΎΡΠ΅Π»Π΅ΠΊ Π±ΡΠ΄ΡΡ ΠΏΠΎΡΠΎΠΌ ΠΏΠ΅ΡΠ΅Π²Π΅Π΄Π΅Π½Ρ ΡΠΎΠ±ΡΠ°Π½Π½ΡΠ΅ ΡΡΠ΅Π΄ΡΡΠ²Π°, Π² ΡΠ»ΡΡΠ°Π΅, Π΅ΡΠ»ΠΈ Π±ΡΠ΄Π΅Ρ Π²ΡΠ·Π²Π°Π½Π° ΡΡΠ½ΠΊΡΠΈΡ close()
* ΠΠΎΠ΄Π΄Π΅ΡΠΆΠΈΠ²Π°Π΅Ρ Π²ΠΎΠ·Π²ΡΠ°Ρ ΡΡΠ΅Π΄ΡΡΠ², Π° ΡΠ°ΠΊΡΠ΅ ΠΏΠ΅ΡΠ΅Π²ΠΎΠ΄ ΡΡΠ΅Π΄ΡΡΠ² Π½Π° ΠΊΠΎΡΠ΅Π»Π΅ΠΊ, Π² ΡΠ»ΡΡΠ°Π΅ ΡΡΠΏΠ΅ΡΠ½ΠΎΠ³ΠΎ ΠΏΡΠΎΠ²Π΅Π΄Π΅Π½ΠΈΡ ΠΏΡΠΎΠ΄Π°ΠΆ
*/
function FundsVault(address _wallet) {
requireNotEmptyAddress(_wallet);
wallet = _wallet;
state = State.Active;
}
/**
* ΠΠΎΠ»ΠΎΠΆΠΈΡΡ Π΄Π΅ΠΏΠΎΠ·ΠΈΡ Π² Ρ
ΡΠ°Π½ΠΈΠ»ΠΈΡΠ΅
*/
function deposit(address investor) public payable onlyOwner inState(State.Active) {
deposited[investor] = deposited[investor].add(msg.value);
}
/**
* ΠΠ΅ΡΠ΅Π²ΠΎΠ΄ ΡΠΎΠ±ΡΠ°Π½Π½ΡΡ
ΡΡΠ΅Π΄ΡΡΠ² Π½Π° ΡΠΊΠ°Π·Π°Π½Π½ΡΠΉ ΠΊΠΎΡΠ΅Π»Π΅ΠΊ
*/
function close() public onlyOwner inState(State.Active) {
state = State.Closed;
Closed();
wallet.transfer(this.balance);
}
/**
* Π£ΡΡΠ°Π½ΠΎΠ²Π»ΠΈΠ²Π°Π΅ΠΌ ΠΊΠΎΡΠ΅Π»Π΅ΠΊ
*/
function setWallet(address newWalletAddress) public onlyOwner inState(State.Active) {
wallet = newWalletAddress;
}
/**
* Π£ΡΡΠ°Π½ΠΎΠ²ΠΈΡΡ ΡΠ΅ΠΆΠΈΠΌ Π²ΠΎΠ·Π²ΡΠ°ΡΠ° Π΄Π΅Π½Π΅Π³
*/
function enableRefunds() public onlyOwner inState(State.Active) {
state = State.Refunding;
RefundsEnabled();
}
/**
* Π€ΡΠ½ΠΊΡΠΈΡ Π²ΠΎΠ·Π²ΡΠ°ΡΠ° ΡΡΠ΅Π΄ΡΡΠ²
*/
function refund(address investor, uint weiAmount) public onlyOwner inState(State.Refunding){
uint256 depositedValue = weiAmount.min256(deposited[investor]);
deposited[investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
/** Π’ΠΎΠ»ΡΠΊΠΎ, Π΅ΡΠ»ΠΈ ΡΠ΅ΠΊΡΡΠ΅Π΅ ΡΠΎΡΡΠΎΡΠ½ΠΈΠ΅ ΡΠΎΠΎΡΠ²Π΅ΡΡΠ²ΡΠ΅Ρ ΡΠΎΡΡΠΎΡΠ½ΠΈΡ */
modifier inState(State _state) {
require(state == _state);
_;
}
}
/**
* ΠΠΎΠ½ΡΡΠ°ΠΊΡ ΠΏΡΠΎΠ΄Π°ΠΆΠΈ
* ΠΠΎΠ·Π²ΡΠ°Ρ ΡΡΠ΅Π΄ΡΡΠ² ΠΏΠΎΠ΄Π΄Π΅ΡΠΆΠΌΠ²Π°Π΅ΡΡΡ ΡΠΎΠ»ΡΠΊΠΎ ΡΠ΅ΠΌ, ΠΊΡΠΎ ΠΊΡΠΏΠΈΠ» ΡΠΎΠΊΠ΅Π½Ρ ΡΠ΅ΡΠ΅Π· ΡΡΠ½ΠΊΡΠΈΡ internalInvest
* Π’Π°ΠΊΠΈΠΌ ΠΎΠ±ΡΠ°Π·ΠΎΠΌ, Π΅ΡΠ»ΠΈ ΠΈΠ½Π²Π΅ΡΡΠΎΡΡ Π±ΡΠ΄ΡΡ ΠΎΠ±ΠΌΠ΅Π½ΠΈΠ²Π°ΡΡΡΡ ΡΠΎΠΊΠ΅Π½Π°ΠΌΠΈ, ΡΠΎ Π²Π΅ΡΠ½ΡΡΡ ΠΌΠΎΠΆΠ½ΠΎ Π±ΡΠ΄Π΅Ρ ΡΠΎΠ»ΡΠΊΠΎ ΡΠ΅ΠΌ, Ρ ΠΊΠΎΠ³ΠΎ Π² ΠΊΠΎΠ½ΡΡΠ°ΠΊΡΠ΅ ΠΏΡΠΎΠ΄Π°ΠΆ
* ΡΠ°ΠΊΠ°Ρ ΠΆΠ΅ ΡΡΠΌΠΌΠ° ΡΠΎΠΊΠ΅Π½ΠΎΠ², ΠΊΠ°ΠΊ ΠΈ Π² ΠΊΠΎΠ½ΡΡΠ°ΠΊΡΠ΅ ΡΠΎΠΊΠ΅Π½Π°, Π² ΠΏΡΠΎΡΠΈΠ²Π½ΠΎΠΌ ΡΠ»ΡΡΠ°Π΅ ΠΏΠ΅ΡΠ΅Π²Π΅Π΄Π΅Π½Π½ΡΠΉ ΡΡΠΈΡ ΠΎΡΡΠ°Π΅ΡΡΡ Π½Π°Π²ΡΠ΅Π³Π΄Π° Π² ΡΠΈΡΡΠ΅ΠΌΠ΅ ΠΈ Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ Π±ΡΡΡ Π²ΡΠ²Π΅Π΄Π΅Π½
*/
contract RefundableAllocatedCappedCrowdsale is AllocatedCappedCrowdsale {
/**
* Π₯ΡΠ°Π½ΠΈΠ»ΠΈΡΠ΅, ΠΊΡΠ΄Π° Π±ΡΠ΄ΡΡ ΡΠΎΠ±ΠΈΡΠ°ΡΡΡΡ ΡΡΠ΅Π΄ΡΡΠ²Π°, Π΄Π΅Π»Π°Π΅ΡΡΡ Π΄Π»Ρ ΡΠΎΠ³ΠΎ, ΡΡΠΎΠ±Ρ Π³Π°ΡΠ°Π½ΡΠΈΡΠΎΠ²Π°ΡΡ Π²ΠΎΠ·Π²ΡΠ°ΡΡ
*/
FundsVault public fundsVault;
/** ΠΠ°ΠΏΠ° Π°Π΄ΡΠ΅Ρ ΠΈΠ½Π²Π΅ΡΡΠΎΡΠ° - Π±ΡΠ» Π»ΠΈ ΡΠΎΠ²Π΅ΡΡΠ΅Π½ Π²ΠΎΠ·Π²ΡΠ°Ρ ΡΡΠ΅ΡΡΠ² */
mapping (address => bool) public refundedInvestors;
function RefundableAllocatedCappedCrowdsale(uint _currentEtherRateInCents, address _token, address _destinationMultisigWallet, uint _firstStageStartsAt, uint _firstStageEndsAt, uint _secondStageStartsAt, uint _secondStageEndsAt, address _advisorsAccount, address _marketingAccount, address _supportAccount, address _teamAccount, uint _teamTokensIssueDate) AllocatedCappedCrowdsale(_currentEtherRateInCents, _token, _destinationMultisigWallet, _firstStageStartsAt, _firstStageEndsAt, _secondStageStartsAt, _secondStageEndsAt, _advisorsAccount, _marketingAccount, _supportAccount, _teamAccount, _teamTokensIssueDate) {
// Π‘ΠΎΠ·Π΄Π°Π΅ΠΌ ΠΎΡ ΠΊΠΎΠ½ΡΡΠ°ΠΊΡΠ° ΠΏΡΠΎΠ΄Π°ΠΆ Π½ΠΎΠ²ΠΎΠ΅ Ρ
ΡΠ°Π½ΠΈΠ»ΠΈΡΠ΅, Π΄ΠΎΡΡΡΠΏ ΠΊ Π½Π΅ΠΌΡ ΠΈΠΌΠ΅Π΅Ρ ΡΠΎΠ»ΡΠΊΠΎ ΠΊΠΎΠ½ΡΡΠ°ΠΊΡ ΠΏΡΠΎΠ΄Π°ΠΆ
// ΠΡΠΈ ΡΡΠΏΠ΅ΡΠ½ΠΎΠΌ Π·Π°Π²Π΅ΡΡΠ΅Π½ΠΈΠΈ ΠΏΡΠΎΠ΄Π°ΠΆ, Π²ΡΠ΅ ΡΠΎΠ±ΡΠ°Π½Π½ΡΠ΅ ΡΡΠ΅Π΄ΡΡΠ²Π° ΠΏΠΎΡΡΡΠΏΡΡ Π½Π° _destinationMultisigWallet
// Π ΠΏΡΠΎΡΠΈΠ²Π½ΠΎΠΌ ΡΠ»ΡΡΠ°Π΅ ΠΌΠΎΠ³ΡΡ Π±ΡΡΡ ΠΏΠ΅ΡΠ΅Π²Π΅Π΄Π΅Π½Ρ ΠΎΠ±ΡΠ°ΡΠ½ΠΎ ΠΈΠ½Π²Π΅ΡΡΠΎΡΠ°ΠΌ
fundsVault = new FundsVault(_destinationMultisigWallet);
}
/** Π£ΡΡΠ°Π½Π°Π²Π»ΠΈΠ²Π°Π΅ΠΌ Π½ΠΎΠ²ΡΠΉ ΠΊΠΎΡΠ΅Π»Π΅ΠΊ Π΄Π»Ρ ΡΠΈΠ½Π°Π»ΡΠ½ΠΎΠ³ΠΎ ΠΏΠ΅ΡΠ΅Π²ΠΎΠ΄Π°
*/
function internalSetDestinationMultisigWallet(address destinationAddress) internal{
fundsVault.setWallet(destinationAddress);
super.internalSetDestinationMultisigWallet(destinationAddress);
}
/** Π€ΠΈΠ½Π°Π»ΠΈΠ·Π°ΡΠΈΡ Π²ΡΠΎΡΠΎΠ³ΠΎ ΡΡΠ°ΠΏΠ°
*/
function internalSuccessOver() internal {
// Π£ΡΠΏΠ΅ΡΠ½ΠΎ Π·Π°ΠΊΡΡΠ²Π°Π΅ΠΌ Ρ
ΡΠ°Π½ΠΈΠ»ΠΈΡΠ΅ ΡΡΠ΅Π΄ΡΡΠ² ΠΈ ΠΏΠ΅ΡΠ΅Π²ΠΎΠ΄ΠΈΠΌ ΡΡΠΈΡ Π½Π° ΡΠΊΠ°Π·Π°Π½Π½ΡΠΉ ΠΊΠΎΡΠ΅Π»Π΅ΠΊ
fundsVault.close();
super.internalSuccessOver();
}
/** ΠΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΠ΅ ΡΡΠ½ΠΊΡΠΈΠΈ ΠΏΡΠΈΠ½ΡΡΠΈΡ Π΄ΠΎΠΏΠΎΠ·ΠΈΡΠ° Π½Π° ΡΡΠ΅Ρ, Π² Π΄Π°Π½Π½ΠΎΠΌ ΡΠ»ΡΡΠ°Π΅, ΠΈΠ΄ΡΠΈ Π±ΡΠ΄Π΅Ρ ΡΠ΅ΡΠ΅Π· vault
*/
function internalDeposit(address receiver, uint weiAmount) internal{
// Π¨Π»Π΅ΠΌ Π½Π° ΠΊΠΎΡΠ΅Π»ΡΠΊ ΡΡΠΈΡ
fundsVault.deposit.value(weiAmount)(msg.sender);
}
/** ΠΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΠ΅ ΡΡΠ½ΠΊΡΠΈΠΈ Π²ΠΊΠ»ΡΡΠ΅Π½ΠΈΡ ΡΠΎΡΡΠΎΡΠ½ΠΈΡ Π²ΠΎΠ·Π²ΡΠ°ΡΠ°
*/
function internalEnableRefunds() internal{
super.internalEnableRefunds();
fundsVault.enableRefunds();
}
/** ΠΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΠ΅ ΡΡΠ½ΠΊΡΠΈΠΈ Π²ΠΎΠ·Π²ΡΠ°ΡΠ°, Π²ΠΎΠ·Π²ΡΠ°Ρ ΠΌΠΎΠΆΠ½ΠΎ ΡΠ΄Π΅Π»Π°ΡΡ ΡΠΎΠ»ΡΠΊΠΎ ΡΠ°Π·
*/
function internalRefund(address receiver, uint weiAmount) internal{
// ΠΠ΅Π»Π°Π΅ΠΌ Π²ΠΎΠ·Π²ΡΠ°Ρ
// ΠΠΎΠ΄Π΄Π΅ΡΠΆΠΈΠ²Π°Π΅ΠΌ ΡΠΎΠ»ΡΠΊΠΎ 1 Π²ΠΎΠ·Π²ΡΠ°Ρ
if (refundedInvestors[receiver]) revert();
fundsVault.refund(receiver, weiAmount);
refundedInvestors[receiver] = true;
}
}
|
Π‘ΠΏΠ΅Ρ. ΡΡΠ½ΠΊΡΠΈΡ, ΠΊΠΎΡΠΎΡΠ°Ρ ΠΏΠΎΠ·Π²ΠΎΠ»ΡΠ΅Ρ ΠΏΡΠΎΠ΄Π°Π²Π°ΡΡ ΡΠΎΠΊΠ΅Π½Ρ Π²Π½Π΅ ΡΠ΅Π½ΠΎΠ²ΠΎΠΉ ΠΏΠΎΠ»ΠΈΡΠΈΠΊΠΈ, Π΄ΠΎΡΡΡΠΏΠΊΠ° ΡΠΎΠ»ΡΠΊΠΎ Π²Π»Π°Π΄Π΅Π»ΡΡΡ Π Π΅Π·ΡΠ»ΡΡΠ°ΡΡ ΠΏΠΈΡΡΡΡΡ Π² ΠΎΠ±ΡΡΡ ΡΡΠ°ΡΠΈΡΡΠΈΠΊΡ, Π±Π΅Π· ΡΠ°Π·Π΄Π΅Π»Π΅Π½ΠΈΡ Π½Π° ΡΡΠ°Π΄ΠΈΠΈ receiver - ΠΏΠΎΠ»ΡΡΠ°ΡΠ΅Π»Ρ tokenAmount - ΠΎΠ±ΡΠ΅Π΅ ΠΊΠΎΠ»-Π²ΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² c decimals!!! weiAmount - ΡΠ΅Π½Π° Π² wei/ CΠΊΠΎΠ»ΡΠΊΠΎ ΡΠΎΠΊΠ΅Π½ΠΎΠ² ΠΎΡΡΠ°Π»ΠΎΡΡ Π΄Π»Ρ ΠΏΡΠΎΠ΄Π°ΠΆΠΈ? ΠΠΎΠ»ΡΡΠ΅ ΡΡΠΎΠ³ΠΎ Π·Π½Π°ΡΠ΅Π½ΠΈΡ Π²ΡΠ΄Π°ΡΡ Π½Π΅ ΠΌΠΎΠΆΠ΅ΠΌ! ΠΠΎΠΆΠ΅Ρ Π±ΡΡΡ 0, Π²ΡΠ΄Π°Π΅ΠΌ ΡΠΎΠΊΠ΅Π½Ρ Π±Π΅ΡΠΏΠ»Π°ΡΠ½ΠΎ ΠΠ±Π½ΠΎΠ²Π»ΡΠ΅ΠΌ ΡΡΠ°ΡΠΈΡΡΠΈΠΊΡ ΠΠΎΠΆΠ΅Ρ ΠΏΠ΅ΡΠ΅ΠΎΠΏΡΠ΅Π΄Π΅Π»ΡΠ΅ΡΡΡΡ Π² Π½Π°ΡΠ»Π΅Π΄Π½ΠΈΠΊΠ°Ρ
|
function internalPreallocate(State currentState, address receiver, uint tokenAmount, uint weiAmount) internal {
require(getTokensLeftForSale(currentState) >= tokenAmount);
internalAssignTokens(receiver, tokenAmount, weiAmount, getWeiInCents(weiAmount), 0);
updateStat(currentState, receiver, tokenAmount, weiAmount);
}
| 13,009,123
|
//Address: 0x2f97dc94317760c7204e72a5bd058c10b409dc12
//Contract name: BCSCrowdsale
//Balance: 0 Ether
//Verification Date: 10/8/2017
//Transacion Count: 12
// CODE STARTS HERE
/*************************************************************************
* This contract has been merged with solidify
* https://github.com/tiesnetwork/solidify
*************************************************************************/
pragma solidity ^0.4.10;
/*************************************************************************
* import "../token/ITokenPool.sol" : start
*************************************************************************/
/*************************************************************************
* import "./ERC20StandardToken.sol" : start
*************************************************************************/
/*************************************************************************
* import "./IERC20Token.sol" : start
*************************************************************************/
/**@dev ERC20 compliant token interface.
https://theethereum.wiki/w/index.php/ERC20_Token_Standard
https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md */
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public constant returns (string _name) { _name; }
function symbol() public constant returns (string _symbol) { _symbol; }
function decimals() public constant returns (uint8 _decimals) { _decimals; }
function totalSupply() constant returns (uint total) {total;}
function balanceOf(address _owner) constant returns (uint balance) {_owner; balance;}
function allowance(address _owner, address _spender) constant returns (uint remaining) {_owner; _spender; remaining;}
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value) returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/*************************************************************************
* import "./IERC20Token.sol" : end
*************************************************************************/
/*************************************************************************
* import "../common/SafeMath.sol" : start
*************************************************************************/
/**dev Utility methods for overflow-proof arithmetic operations
*/
contract SafeMath {
/**dev Returns the sum of a and b. Throws an exception if it exceeds uint256 limits*/
function safeAdd(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
/**dev Returns the difference of a and b. Throws an exception if a is less than b*/
function safeSub(uint256 a, uint256 b) internal returns (uint256) {
assert(a >= b);
return a - b;
}
/**dev Returns the product of a and b. Throws an exception if it exceeds uint256 limits*/
function safeMult(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x * y;
assert((x == 0) || (z / x == y));
return z;
}
function safeDiv(uint256 x, uint256 y) internal returns (uint256) {
assert(y != 0);
return x / y;
}
}/*************************************************************************
* import "../common/SafeMath.sol" : end
*************************************************************************/
/**@dev Standard ERC20 compliant token implementation */
contract ERC20StandardToken is IERC20Token, SafeMath {
string public name;
string public symbol;
uint8 public decimals;
//tokens already issued
uint256 tokensIssued;
//balances for each account
mapping (address => uint256) balances;
//one account approves the transfer of an amount to another account
mapping (address => mapping (address => uint256)) allowed;
function ERC20StandardToken() {
}
//
//IERC20Token implementation
//
function totalSupply() constant returns (uint total) {
total = tokensIssued;
}
function balanceOf(address _owner) constant returns (uint balance) {
balance = balances[_owner];
}
function transfer(address _to, uint256 _value) returns (bool) {
require(_to != address(0));
// safeSub inside doTransfer will throw if there is not enough balance.
doTransfer(msg.sender, _to, _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
require(_to != address(0));
// Check for allowance is not needed because sub(_allowance, _value) will throw if this condition is not met
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value);
// safeSub inside doTransfer will throw if there is not enough balance.
doTransfer(_from, _to, _value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
remaining = allowed[_owner][_spender];
}
//
// Additional functions
//
/**@dev Gets real token amount in the smallest token units */
function getRealTokenAmount(uint256 tokens) constant returns (uint256) {
return tokens * (uint256(10) ** decimals);
}
//
// Internal functions
//
function doTransfer(address _from, address _to, uint256 _value) internal {
balances[_from] = safeSub(balances[_from], _value);
balances[_to] = safeAdd(balances[_to], _value);
}
}/*************************************************************************
* import "./ERC20StandardToken.sol" : end
*************************************************************************/
/**@dev Token pool that manages its tokens by designating trustees */
contract ITokenPool {
/**@dev Token to be managed */
ERC20StandardToken public token;
/**@dev Changes trustee state */
function setTrustee(address trustee, bool state);
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
/**@dev Returns remaining token amount */
function getTokenAmount() constant returns (uint256 tokens) {tokens;}
}/*************************************************************************
* import "../token/ITokenPool.sol" : end
*************************************************************************/
/*************************************************************************
* import "../token/ReturnTokenAgent.sol" : start
*************************************************************************/
/*************************************************************************
* import "../common/Manageable.sol" : start
*************************************************************************/
/*************************************************************************
* import "../common/Owned.sol" : start
*************************************************************************/
contract Owned {
address public owner;
function Owned() {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**@dev allows transferring the contract ownership. */
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
owner = _newOwner;
}
}
/*************************************************************************
* import "../common/Owned.sol" : end
*************************************************************************/
///A token that have an owner and a list of managers that can perform some operations
///Owner is always a manager too
contract Manageable is Owned {
event ManagerSet(address manager, bool state);
mapping (address => bool) public managers;
function Manageable() Owned() {
managers[owner] = true;
}
/**@dev Allows execution by managers only */
modifier managerOnly {
assert(managers[msg.sender]);
_;
}
function transferOwnership(address _newOwner) public ownerOnly {
super.transferOwnership(_newOwner);
managers[_newOwner] = true;
managers[msg.sender] = false;
}
function setManager(address manager, bool state) ownerOnly {
managers[manager] = state;
ManagerSet(manager, state);
}
}/*************************************************************************
* import "../common/Manageable.sol" : end
*************************************************************************/
/*************************************************************************
* import "../token/ReturnableToken.sol" : start
*************************************************************************/
///Token that when sent to specified contract (returnAgent) invokes additional actions
contract ReturnableToken is Manageable, ERC20StandardToken {
/**@dev List of return agents */
mapping (address => bool) public returnAgents;
function ReturnableToken() {}
/**@dev Sets new return agent */
function setReturnAgent(ReturnTokenAgent agent) managerOnly {
returnAgents[address(agent)] = true;
}
/**@dev Removes return agent from list */
function removeReturnAgent(ReturnTokenAgent agent) managerOnly {
returnAgents[address(agent)] = false;
}
function doTransfer(address _from, address _to, uint256 _value) internal {
super.doTransfer(_from, _to, _value);
if (returnAgents[_to]) {
ReturnTokenAgent(_to).returnToken(_from, _value);
}
}
}/*************************************************************************
* import "../token/ReturnableToken.sol" : end
*************************************************************************/
///Returnable tokens receiver
contract ReturnTokenAgent is Manageable {
//ReturnableToken public returnableToken;
/**@dev List of returnable tokens in format token->flag */
mapping (address => bool) public returnableTokens;
/**@dev Allows only token to execute method */
//modifier returnableTokenOnly {require(msg.sender == address(returnableToken)); _;}
modifier returnableTokenOnly {require(returnableTokens[msg.sender]); _;}
/**@dev Executes when tokens are transferred to this */
function returnToken(address from, uint256 amountReturned);
/**@dev Sets token that can call returnToken method */
function setReturnableToken(ReturnableToken token) managerOnly {
returnableTokens[address(token)] = true;
}
/**@dev Removes token that can call returnToken method */
function removeReturnableToken(ReturnableToken token) managerOnly {
returnableTokens[address(token)] = false;
}
}/*************************************************************************
* import "../token/ReturnTokenAgent.sol" : end
*************************************************************************/
/*************************************************************************
* import "./IInvestRestrictions.sol" : start
*************************************************************************/
/** @dev Restrictions on investment */
contract IInvestRestrictions is Manageable {
/**@dev Returns true if investmet is allowed */
function canInvest(address investor, uint amount, uint tokensLeft) constant returns (bool result) {
investor; amount; result; tokensLeft;
}
/**@dev Called when investment was made */
function investHappened(address investor, uint amount) managerOnly {}
}/*************************************************************************
* import "./IInvestRestrictions.sol" : end
*************************************************************************/
/*************************************************************************
* import "./ICrowdsaleFormula.sol" : start
*************************************************************************/
/**@dev Abstraction of crowdsale token calculation function */
contract ICrowdsaleFormula {
/**@dev Returns amount of tokens that can be bought with given weiAmount */
function howManyTokensForEther(uint256 weiAmount) constant returns(uint256 tokens, uint256 excess) {
weiAmount; tokens; excess;
}
/**@dev Returns how many tokens left for sale */
function tokensLeft() constant returns(uint256 _left) { _left;}
}/*************************************************************************
* import "./ICrowdsaleFormula.sol" : end
*************************************************************************/
/**@dev Crowdsale base contract, used for PRE-TGE and TGE stages
* Token holder should also be the owner of this contract */
contract BCSCrowdsale is ICrowdsaleFormula, Manageable, SafeMath {
enum State {Unknown, BeforeStart, Active, FinishedSuccess, FinishedFailure}
ITokenPool public tokenPool;
IInvestRestrictions public restrictions; //restrictions on investment
address public beneficiary; //address of contract to collect ether
uint256 public startTime; //unit timestamp of start time
uint256 public endTime; //unix timestamp of end date
uint256 public minimumGoalInWei; //TODO or in tokens
uint256 public tokensForOneEther; //how many tokens can you buy for 1 ether
uint256 realAmountForOneEther; //how many tokens can you buy for 1 ether * 10**decimals
uint256 bonusPct; //additional percent of tokens
bool public withdrew; //true if beneficiary already withdrew
uint256 public weiCollected;
uint256 public tokensSold;
bool public failure; //true if some error occurred during crowdsale
mapping (address => uint256) public investedFrom; //how many wei specific address invested
mapping (address => uint256) public tokensSoldTo; //how many tokens sold to specific addreess
mapping (address => uint256) public overpays; //overpays for send value excesses
// A new investment was made
event Invested(address investor, uint weiAmount, uint tokenAmount);
// Refund was processed for a contributor
event Refund(address investor, uint weiAmount);
// Overpay refund was processed for a contributor
event OverpayRefund(address investor, uint weiAmount);
/**@dev Crowdsale constructor, can specify startTime as 0 to start crowdsale immediately
_tokensForOneEther - doesn't depend on token decimals */
function BCSCrowdsale(
ITokenPool _tokenPool,
IInvestRestrictions _restrictions,
address _beneficiary,
uint256 _startTime,
uint256 _durationInHours,
uint256 _goalInWei,
uint256 _tokensForOneEther,
uint256 _bonusPct)
{
require(_beneficiary != 0x0);
require(address(_tokenPool) != 0x0);
require(_durationInHours > 0);
require(_tokensForOneEther > 0);
tokenPool = _tokenPool;
beneficiary = _beneficiary;
restrictions = _restrictions;
if (_startTime == 0) {
startTime = now;
} else {
startTime = _startTime;
}
endTime = (_durationInHours * 1 hours) + startTime;
tokensForOneEther = _tokensForOneEther;
minimumGoalInWei = _goalInWei;
bonusPct = _bonusPct;
weiCollected = 0;
tokensSold = 0;
failure = false;
withdrew = false;
realAmountForOneEther = tokenPool.token().getRealTokenAmount(tokensForOneEther);
}
function() payable {
invest();
}
function invest() payable {
require(canInvest(msg.sender, msg.value));
uint256 excess;
uint256 weiPaid = msg.value;
uint256 tokensToBuy;
(tokensToBuy, excess) = howManyTokensForEther(weiPaid);
require(tokensToBuy <= tokensLeft() && tokensToBuy > 0);
if (excess > 0) {
overpays[msg.sender] = safeAdd(overpays[msg.sender], excess);
weiPaid = safeSub(weiPaid, excess);
}
investedFrom[msg.sender] = safeAdd(investedFrom[msg.sender], weiPaid);
tokensSoldTo[msg.sender] = safeAdd(tokensSoldTo[msg.sender], tokensToBuy);
tokensSold = safeAdd(tokensSold, tokensToBuy);
weiCollected = safeAdd(weiCollected, weiPaid);
if(address(restrictions) != 0x0) {
restrictions.investHappened(msg.sender, msg.value);
}
require(tokenPool.token().transferFrom(tokenPool, msg.sender, tokensToBuy));
Invested(msg.sender, weiPaid, tokensToBuy);
}
/**@dev Returns true if it is possible to invest */
function canInvest(address investor, uint256 amount) constant returns(bool) {
return getState() == State.Active &&
(address(restrictions) == 0x0 ||
restrictions.canInvest(investor, amount, tokensLeft()));
}
/**@dev ICrowdsaleFormula override */
function howManyTokensForEther(uint256 weiAmount) constant returns(uint256 tokens, uint256 excess) {
uint256 bpct = getCurrentBonusPct();
uint256 maxTokens = (tokensLeft() * 100) / (100 + bpct);
tokens = weiAmount * realAmountForOneEther / 1 ether;
if (tokens > maxTokens) {
tokens = maxTokens;
}
excess = weiAmount - tokens * 1 ether / realAmountForOneEther;
tokens = (tokens * 100 + tokens * bpct) / 100;
}
/**@dev Returns current bonus percent [0-100] */
function getCurrentBonusPct() constant returns (uint256) {
return bonusPct;
}
/**@dev Returns how many tokens left for sale */
function tokensLeft() constant returns(uint256) {
return tokenPool.getTokenAmount();
}
/**@dev Returns funds that should be sent to beneficiary */
function amountToBeneficiary() constant returns (uint256) {
return weiCollected;
}
/**@dev Returns crowdsale current state */
function getState() constant returns (State) {
if (failure) {
return State.FinishedFailure;
}
if (now < startTime) {
return State.BeforeStart;
} else if (now < endTime && tokensLeft() > 0) {
return State.Active;
} else if (weiCollected >= minimumGoalInWei || tokensLeft() <= 0) {
return State.FinishedSuccess;
} else {
return State.FinishedFailure;
}
}
/**@dev Allows investors to withdraw funds and overpays in case of crowdsale failure */
function refund() {
require(getState() == State.FinishedFailure);
uint amount = investedFrom[msg.sender];
if (amount > 0) {
investedFrom[msg.sender] = 0;
weiCollected = safeSub(weiCollected, amount);
msg.sender.transfer(amount);
Refund(msg.sender, amount);
}
}
/**@dev Allows investor to withdraw overpay */
function withdrawOverpay() {
uint amount = overpays[msg.sender];
overpays[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
OverpayRefund(msg.sender, amount);
} else {
overpays[msg.sender] = amount; //restore funds in case of failed send
}
}
}
/**@dev Transfers all collected funds to beneficiary*/
function transferToBeneficiary() {
require(getState() == State.FinishedSuccess && !withdrew);
withdrew = true;
uint256 amount = amountToBeneficiary();
beneficiary.transfer(amount);
Refund(beneficiary, amount);
}
/**@dev Makes crowdsale failed/ok, for emergency reasons */
function makeFailed(bool state) managerOnly {
failure = state;
}
/**@dev Sets new beneficiary */
function changeBeneficiary(address newBeneficiary) managerOnly {
beneficiary = newBeneficiary;
}
}
|
dev Returns the difference of a and b. Throws an exception if a is less than b/
|
function safeSub(uint256 a, uint256 b) internal returns (uint256) {
assert(a >= b);
return a - b;
}
| 1,004,072
|
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10;
import "../helpers/LiquityHelper.sol";
import "../../../utils/TokenUtils.sol";
import "../../ActionBase.sol";
contract LiquityWithdraw is ActionBase, LiquityHelper {
using TokenUtils for address;
struct Params {
uint256 collAmount; // Amount of WETH tokens to withdraw
address to; // Address that will receive the tokens
address upperHint;
address lowerHint;
}
/// @inheritdoc ActionBase
function executeAction(
bytes memory _callData,
bytes32[] memory _subData,
uint8[] memory _paramMapping,
bytes32[] memory _returnValues
) public payable virtual override returns (bytes32) {
Params memory params = parseInputs(_callData);
params.collAmount = _parseParamUint(
params.collAmount,
_paramMapping[0],
_subData,
_returnValues
);
params.to = _parseParamAddr(params.to, _paramMapping[1], _subData, _returnValues);
(uint256 withdrawnAmount, bytes memory logData) = _liquityWithdraw(params);
emit ActionEvent("LiquityWithdraw", logData);
return bytes32(withdrawnAmount);
}
/// @inheritdoc ActionBase
function executeActionDirect(bytes memory _callData) public payable virtual override {
Params memory params = parseInputs(_callData);
(, bytes memory logData) = _liquityWithdraw(params);
logger.logActionDirectEvent("LiquityWithdraw", logData);
}
/// @inheritdoc ActionBase
function actionType() public pure virtual override returns (uint8) {
return uint8(ActionType.STANDARD_ACTION);
}
//////////////////////////// ACTION LOGIC ////////////////////////////
/// @notice Withdraws collateral from the trove
function _liquityWithdraw(Params memory _params) internal returns (uint256, bytes memory) {
BorrowerOperations.withdrawColl(_params.collAmount, _params.upperHint, _params.lowerHint);
TokenUtils.depositWeth(_params.collAmount);
TokenUtils.WETH_ADDR.withdrawTokens(_params.to, _params.collAmount);
bytes memory logData = abi.encode(_params.collAmount, _params.to);
return (_params.collAmount, logData);
}
function parseInputs(bytes memory _callData) public pure returns (Params memory params) {
params = abi.decode(_callData, (Params));
}
}
|
@inheritdoc ActionBase
|
function executeActionDirect(bytes memory _callData) public payable virtual override {
Params memory params = parseInputs(_callData);
(, bytes memory logData) = _liquityWithdraw(params);
logger.logActionDirectEvent("LiquityWithdraw", logData);
}
| 12,993,264
|
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.4;
import {
MintableBurnableIERC20
} from '../../../tokens/interfaces/MintableBurnableIERC20.sol';
import {ISynthereumFinder} from '../../../core/interfaces/IFinder.sol';
import {
ISelfMintingController
} from '../common/interfaces/ISelfMintingController.sol';
import {SynthereumInterfaces} from '../../../core/Constants.sol';
import {
FinderInterface
} from '@uma/core/contracts/oracle/interfaces/FinderInterface.sol';
import {
IdentifierWhitelistInterface
} from '@uma/core/contracts/oracle/interfaces/IdentifierWhitelistInterface.sol';
import {
OracleInterfaces
} from '@uma/core/contracts/oracle/implementation/Constants.sol';
import {
FixedPoint
} from '@uma/core/contracts/common/implementation/FixedPoint.sol';
import {
SelfMintingPerpetualMultiPartyLib
} from './SelfMintingPerpetualMultiPartyLib.sol';
import {
SelfMintingPerpetualMultiParty
} from './SelfMintingPerpetualMultiParty.sol';
import {
ContractCreator
} from '@uma/core/contracts/oracle/implementation/ContractCreator.sol';
import {Testable} from '@uma/core/contracts/common/implementation/Testable.sol';
import {Lockable} from '@uma/core/contracts/common/implementation/Lockable.sol';
/**
* @title Self-Minting Perpetual Contract creator.
* @notice Factory contract to create and register new instances of self-minting perpetual contracts.
* Responsible for constraining the parameters used to construct a new self-minting perpetual. This creator contains a number of constraints
* that are applied to newly created contracts. 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 SelfMintingPerpetutalMultiPartyCreator is
ContractCreator,
Testable,
Lockable
{
using FixedPoint for FixedPoint.Unsigned;
struct Params {
address collateralAddress;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
address syntheticToken;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address excessTokenBeneficiary;
uint8 version;
ISelfMintingController.DaoFee daoFee;
uint256 capMintAmount;
uint256 capDepositRatio;
}
// Address of Synthereum Finder
ISynthereumFinder public synthereumFinder;
//----------------------------------------
// Events
//----------------------------------------
event CreatedPerpetual(
address indexed perpetualAddress,
address indexed deployerAddress
);
//----------------------------------------
// Constructor
//----------------------------------------
/**
* @notice Constructs the Perpetual contract.
* @param _umaFinderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _synthereumFinder Synthereum Finder address used to discover other contracts
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _umaFinderAddress,
address _synthereumFinder,
address _timerAddress
) ContractCreator(_umaFinderAddress) Testable(_timerAddress) nonReentrant() {
synthereumFinder = ISynthereumFinder(_synthereumFinder);
}
//----------------------------------------
// External functions
//----------------------------------------
/**
* @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 calldata params)
public
virtual
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'
);
require(
params.syntheticToken != address(0),
'Synthetic token address cannot be 0x00'
);
address derivative;
// 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.
MintableBurnableIERC20 tokenCurrency =
MintableBurnableIERC20(params.syntheticToken);
require(
keccak256(abi.encodePacked(tokenCurrency.name())) ==
keccak256(abi.encodePacked(params.syntheticName)),
'Wrong synthetic token name'
);
require(
keccak256(abi.encodePacked(tokenCurrency.symbol())) ==
keccak256(abi.encodePacked(params.syntheticSymbol)),
'Wrong synthetic token symbol'
);
require(
tokenCurrency.decimals() == uint8(18),
'Decimals of synthetic token must be 18'
);
derivative = SelfMintingPerpetualMultiPartyLib.deploy(
_convertParams(params)
);
_setControllerValues(
derivative,
params.daoFee,
params.capMintAmount,
params.capDepositRatio
);
_registerContract(new address[](0), address(derivative));
emit CreatedPerpetual(address(derivative), msg.sender);
return address(derivative);
}
//----------------------------------------
// Internal functions
//----------------------------------------
// Converts createPerpetual params to Perpetual constructor params.
function _convertParams(Params calldata params)
internal
view
returns (
SelfMintingPerpetualMultiParty.ConstructorParams memory constructorParams
)
{
// Known from creator deployment.
constructorParams.positionManagerParams.finderAddress = finderAddress;
constructorParams.positionManagerParams.synthereumFinder = synthereumFinder;
constructorParams.positionManagerParams.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.excessTokenBeneficiary != address(0),
'Token Beneficiary cannot be 0x00'
);
require(
params.daoFee.feeRecipient != address(0),
'Fee recipient cannot be 0x00'
);
// 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'
);
// Input from function call.
constructorParams.positionManagerParams.tokenAddress = params
.syntheticToken;
constructorParams.positionManagerParams.collateralAddress = params
.collateralAddress;
constructorParams.positionManagerParams.priceFeedIdentifier = params
.priceFeedIdentifier;
constructorParams.liquidatableParams.collateralRequirement = params
.collateralRequirement;
constructorParams.liquidatableParams.disputeBondPct = params.disputeBondPct;
constructorParams.liquidatableParams.sponsorDisputeRewardPct = params
.sponsorDisputeRewardPct;
constructorParams.liquidatableParams.disputerDisputeRewardPct = params
.disputerDisputeRewardPct;
constructorParams.positionManagerParams.minSponsorTokens = params
.minSponsorTokens;
constructorParams.positionManagerParams.withdrawalLiveness = params
.withdrawalLiveness;
constructorParams.liquidatableParams.liquidationLiveness = params
.liquidationLiveness;
constructorParams.positionManagerParams.excessTokenBeneficiary = params
.excessTokenBeneficiary;
constructorParams.positionManagerParams.version = params.version;
}
/** @notice Sets the controller values for a self-minting derivative
* @param derivative Address of the derivative to set controller values
* @param daoFee The DAO fee that will be paid when interacting with the self-minting derivative
* @param capMintAmount Cap on mint amount. How much synthetic tokens can be minted through a self-minting derivative.
* This value is updatable
* @param capDepositRatio The cap set on the deposit ratio for a self-minting derivative. This value is updatable.
*/
function _setControllerValues(
address derivative,
ISelfMintingController.DaoFee calldata daoFee,
uint256 capMintAmount,
uint256 capDepositRatio
) internal {
ISelfMintingController selfMintingController =
ISelfMintingController(
synthereumFinder.getImplementationAddress(
SynthereumInterfaces.SelfMintingController
)
);
address[] memory inputAddress = new address[](1);
inputAddress[0] = derivative;
ISelfMintingController.DaoFee[] memory inuptFee =
new ISelfMintingController.DaoFee[](1);
inuptFee[0] = daoFee;
uint256[] memory inputCapMint = new uint256[](1);
inputCapMint[0] = capMintAmount;
uint256[] memory inputCapRatio = new uint256[](1);
inputCapRatio[0] = capDepositRatio;
selfMintingController.setDaoFee(inputAddress, inuptFee);
selfMintingController.setCapMintAmount(inputAddress, inputCapMint);
selfMintingController.setCapDepositRatio(inputAddress, inputCapRatio);
}
}
|
Creates an instance of perpetual and registers it within the registry. params is a `ConstructorParams` object from Perpetual. return address of the deployed contract./ Create a new synthetic token using the params. 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.
|
function createPerpetual(Params calldata params)
public
virtual
nonReentrant()
returns (address)
{
require(bytes(params.syntheticName).length != 0, 'Missing synthetic name');
require(
bytes(params.syntheticSymbol).length != 0,
'Missing synthetic symbol'
);
require(
params.syntheticToken != address(0),
'Synthetic token address cannot be 0x00'
);
address derivative;
MintableBurnableIERC20 tokenCurrency =
MintableBurnableIERC20(params.syntheticToken);
require(
keccak256(abi.encodePacked(tokenCurrency.name())) ==
keccak256(abi.encodePacked(params.syntheticName)),
'Wrong synthetic token name'
);
require(
keccak256(abi.encodePacked(tokenCurrency.symbol())) ==
keccak256(abi.encodePacked(params.syntheticSymbol)),
'Wrong synthetic token symbol'
);
require(
tokenCurrency.decimals() == uint8(18),
'Decimals of synthetic token must be 18'
);
derivative = SelfMintingPerpetualMultiPartyLib.deploy(
_convertParams(params)
);
_setControllerValues(
derivative,
params.daoFee,
params.capMintAmount,
params.capDepositRatio
);
_registerContract(new address[](0), address(derivative));
emit CreatedPerpetual(address(derivative), msg.sender);
return address(derivative);
}
| 6,463,077
|
./partial_match/1/0xca942F2bA3F0Fa446E0b6Db88f1EfDc3e7E35c53/sources/MPondLogic.sol
|
enableAllTranfers = true; This is only for testing, will be false
|
function createConstants() internal {
name = "Marlin";
symbol = "MPOND";
decimals = 18;
totalSupply = 10000e18;
bridgeSupply = 7000e18;
DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,uint256 chainId,address verifyingContract)"
);
DELEGATION_TYPEHASH = keccak256(
"Delegation(address delegatee,uint256 nonce,uint256 expiry,uint96 amount)"
);
UNDELEGATION_TYPEHASH = keccak256(
"Unelegation(address delegatee,uint256 nonce,uint256 expiry,uint96 amount)"
);
admin = msg.sender;
}
| 9,354,626
|
/**
*Submitted for verification at Etherscan.io on 2021-08-02
*/
// File: @sygnum/solidity-base-contracts/contracts/helpers/Initializable.sol
pragma solidity 0.5.12;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(
initializing || isConstructor() || !initialized,
"Initializable: Contract instance has already been initialized"
);
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
// solhint-disable-next-line
assembly {
cs := extcodesize(address)
}
return cs == 0;
}
function isInitialized() public view returns (bool) {
return initialized;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @sygnum/solidity-base-contracts/contracts/role/interface/IBaseOperators.sol
/**
* @title IBaseOperators
* @notice Interface for BaseOperators contract
*/
pragma solidity 0.5.12;
interface IBaseOperators {
function isOperator(address _account) external view returns (bool);
function isAdmin(address _account) external view returns (bool);
function isSystem(address _account) external view returns (bool);
function isRelay(address _account) external view returns (bool);
function isMultisig(address _contract) external view returns (bool);
function confirmFor(address _address) external;
function addOperator(address _account) external;
function removeOperator(address _account) external;
function addAdmin(address _account) external;
function removeAdmin(address _account) external;
function addSystem(address _account) external;
function removeSystem(address _account) external;
function addRelay(address _account) external;
function removeRelay(address _account) external;
function addOperatorAndAdmin(address _account) external;
function removeOperatorAndAdmin(address _account) external;
}
// File: @sygnum/solidity-base-contracts/contracts/role/base/Operatorable.sol
/**
* @title Operatorable
* @author Team 3301 <[emailΒ protected]>
* @dev Operatorable contract stores the BaseOperators contract address, and modifiers for
* contracts.
*/
pragma solidity 0.5.12;
contract Operatorable is Initializable {
IBaseOperators internal operatorsInst;
address private operatorsPending;
event OperatorsContractChanged(address indexed caller, address indexed operatorsAddress);
event OperatorsContractPending(address indexed caller, address indexed operatorsAddress);
/**
* @dev Reverts if sender does not have operator role associated.
*/
modifier onlyOperator() {
require(isOperator(msg.sender), "Operatorable: caller does not have the operator role");
_;
}
/**
* @dev Reverts if sender does not have admin role associated.
*/
modifier onlyAdmin() {
require(isAdmin(msg.sender), "Operatorable: caller does not have the admin role");
_;
}
/**
* @dev Reverts if sender does not have system role associated.
*/
modifier onlySystem() {
require(isSystem(msg.sender), "Operatorable: caller does not have the system role");
_;
}
/**
* @dev Reverts if sender does not have multisig privileges.
*/
modifier onlyMultisig() {
require(isMultisig(msg.sender), "Operatorable: caller does not have multisig role");
_;
}
/**
* @dev Reverts if sender does not have admin or system role associated.
*/
modifier onlyAdminOrSystem() {
require(isAdminOrSystem(msg.sender), "Operatorable: caller does not have the admin role nor system");
_;
}
/**
* @dev Reverts if sender does not have operator or system role associated.
*/
modifier onlyOperatorOrSystem() {
require(isOperatorOrSystem(msg.sender), "Operatorable: caller does not have the operator role nor system");
_;
}
/**
* @dev Reverts if sender does not have the relay role associated.
*/
modifier onlyRelay() {
require(isRelay(msg.sender), "Operatorable: caller does not have relay role associated");
_;
}
/**
* @dev Reverts if sender does not have relay or operator role associated.
*/
modifier onlyOperatorOrRelay() {
require(
isOperator(msg.sender) || isRelay(msg.sender),
"Operatorable: caller does not have the operator role nor relay"
);
_;
}
/**
* @dev Reverts if sender does not have relay or admin role associated.
*/
modifier onlyAdminOrRelay() {
require(
isAdmin(msg.sender) || isRelay(msg.sender),
"Operatorable: caller does not have the admin role nor relay"
);
_;
}
/**
* @dev Reverts if sender does not have the operator, or system, or relay role associated.
*/
modifier onlyOperatorOrSystemOrRelay() {
require(
isOperator(msg.sender) || isSystem(msg.sender) || isRelay(msg.sender),
"Operatorable: caller does not have the operator role nor system nor relay"
);
_;
}
/**
* @dev Initialization instead of constructor, called once. The setOperatorsContract function can be called only by Admin role with
* confirmation through the operators contract.
* @param _baseOperators BaseOperators contract address.
*/
function initialize(address _baseOperators) public initializer {
_setOperatorsContract(_baseOperators);
}
/**
* @dev Set the new the address of Operators contract, should be confirmed from operators contract by calling confirmFor(addr)
* where addr is the address of current contract instance. This is done to prevent the case when the new contract address is
* broken and control of the contract can be lost in such case
* @param _baseOperators BaseOperators contract address.
*/
function setOperatorsContract(address _baseOperators) public onlyAdmin {
require(_baseOperators != address(0), "Operatorable: address of new operators contract can not be zero");
operatorsPending = _baseOperators;
emit OperatorsContractPending(msg.sender, _baseOperators);
}
/**
* @dev The function should be called from new operators contract by admin to ensure that operatorsPending address
* is the real contract address.
*/
function confirmOperatorsContract() public {
require(operatorsPending != address(0), "Operatorable: address of new operators contract can not be zero");
require(msg.sender == operatorsPending, "Operatorable: should be called from new operators contract");
_setOperatorsContract(operatorsPending);
}
/**
* @return The address of the BaseOperators contract.
*/
function getOperatorsContract() public view returns (address) {
return address(operatorsInst);
}
/**
* @return The pending address of the BaseOperators contract.
*/
function getOperatorsPending() public view returns (address) {
return operatorsPending;
}
/**
* @return If '_account' has operator privileges.
*/
function isOperator(address _account) public view returns (bool) {
return operatorsInst.isOperator(_account);
}
/**
* @return If '_account' has admin privileges.
*/
function isAdmin(address _account) public view returns (bool) {
return operatorsInst.isAdmin(_account);
}
/**
* @return If '_account' has system privileges.
*/
function isSystem(address _account) public view returns (bool) {
return operatorsInst.isSystem(_account);
}
/**
* @return If '_account' has relay privileges.
*/
function isRelay(address _account) public view returns (bool) {
return operatorsInst.isRelay(_account);
}
/**
* @return If '_contract' has multisig privileges.
*/
function isMultisig(address _contract) public view returns (bool) {
return operatorsInst.isMultisig(_contract);
}
/**
* @return If '_account' has admin or system privileges.
*/
function isAdminOrSystem(address _account) public view returns (bool) {
return (operatorsInst.isAdmin(_account) || operatorsInst.isSystem(_account));
}
/**
* @return If '_account' has operator or system privileges.
*/
function isOperatorOrSystem(address _account) public view returns (bool) {
return (operatorsInst.isOperator(_account) || operatorsInst.isSystem(_account));
}
/** INTERNAL FUNCTIONS */
function _setOperatorsContract(address _baseOperators) internal {
require(_baseOperators != address(0), "Operatorable: address of new operators contract cannot be zero");
operatorsInst = IBaseOperators(_baseOperators);
emit OperatorsContractChanged(msg.sender, _baseOperators);
}
}
// File: zos-lib/contracts/upgradeability/Proxy.sol
pragma solidity ^0.5.0;
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
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 Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
// File: zos-lib/contracts/utils/Address.sol
pragma solidity ^0.5.0;
/**
* Utility library of inline functions on addresses
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
*/
library ZOSLibAddress {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: zos-lib/contracts/upgradeability/BaseUpgradeabilityProxy.sol
pragma solidity ^0.5.0;
/**
* @title BaseUpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(ZOSLibAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
// File: zos-lib/contracts/upgradeability/UpgradeabilityProxy.sol
pragma solidity ^0.5.0;
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
// File: zos-lib/contracts/upgradeability/BaseAdminUpgradeabilityProxy.sol
pragma solidity ^0.5.0;
/**
* @title BaseAdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
// File: zos-lib/contracts/upgradeability/AdminUpgradeabilityProxy.sol
pragma solidity ^0.5.0;
/**
* @title AdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for
* initializing the implementation, admin, and init data.
*/
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable {
assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
_setAdmin(_admin);
}
}
// File: contracts/token/SygnumTokenProxy.sol
/**
* @title SygnumTokenProxy
* @author Team 3301 <[emailΒ protected]>
* @dev Proxies SygnumToken calls and enables SygnumToken upgradability.
*/
pragma solidity 0.5.12;
contract SygnumTokenProxy is AdminUpgradeabilityProxy {
/* solhint-disable no-empty-blocks */
constructor(
address implementation,
address proxyOwnerAddr,
bytes memory data
) public AdminUpgradeabilityProxy(implementation, proxyOwnerAddr, data) {}
/* solhint-enable no-empty-blocks */
}
// File: contracts/factory/ProxyDeployer.sol
/**
* @title ProxyDeployer
* @author Team 3301 <[emailΒ protected]>
* @dev Library to deploy a proxy instance for a Sygnum.
*/
pragma solidity 0.5.12;
library ProxyDeployer {
/**
* @dev Deploy the proxy instance and initialize it
* @param _tokenImplementation Address of the logic contract
* @param _proxyAdmin Address of the admin for the proxy
* @param _data Bytecode needed for initialization
* @return address New instance address
*/
function deployTokenProxy(
address _tokenImplementation,
address _proxyAdmin,
bytes memory _data
) public returns (address) {
SygnumTokenProxy proxy = new SygnumTokenProxy(_tokenImplementation, _proxyAdmin, _data);
return address(proxy);
}
}
// File: contracts/token/ERC20/ERC20Detailed.sol
/**
* @title ERC20Detailed
* @author OpenZeppelin-Solidity = "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol", and rmeoval
* of IERC20 due to " contract binary not set. Can't deploy new instance.
* This contract may be abstract, not implement an abstract parent's methods completely
* or not invoke an inherited contract's constructor correctly"
*/
pragma solidity 0.5.12;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed {
string internal _name;
string internal _symbol;
uint8 internal _decimals;
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* > Note that this information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* `IERC20.balanceOf` and `IERC20.transfer`.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: contracts/token/ERC20/ERC20SygnumDetailed.sol
/**
* @title ERC20SygnumDetailed
* @author Team 3301 <[emailΒ protected]>
* @dev ERC20 Standard Token with additional details and role set.
*/
pragma solidity 0.5.12;
contract ERC20SygnumDetailed is ERC20Detailed, Operatorable {
bytes4 private _category;
string private _class;
address private _issuer;
event NameUpdated(address issuer, string name, address token);
event SymbolUpdated(address issuer, string symbol, address token);
event CategoryUpdated(address issuer, bytes4 category, address token);
event ClassUpdated(address issuer, string class, address token);
event IssuerUpdated(address issuer, address newIssuer, address token);
/**
* @dev Sets the values for `name`, `symbol`, `decimals`, `category`, `class` and `issuer`. All are
* mutable apart from `issuer`, which is immutable.
* @param name string
* @param symbol string
* @param decimals uint8
* @param category bytes4
* @param class string
* @param issuer address
*/
function _setDetails(
string memory name,
string memory symbol,
uint8 decimals,
bytes4 category,
string memory class,
address issuer
) internal {
_name = name;
_symbol = symbol;
_decimals = decimals;
_category = category;
_class = class;
_issuer = issuer;
}
/**
* @dev Returns the category of the token.
*/
function category() public view returns (bytes4) {
return _category;
}
/**
* @dev Returns the class of the token.
*/
function class() public view returns (string memory) {
return _class;
}
/**
* @dev Returns the issuer of the token.
*/
function issuer() public view returns (address) {
return _issuer;
}
/**
* @dev Updates the name of the token, only callable by Sygnum operator.
* @param name_ The new name.
*/
function updateName(string memory name_) public onlyOperator {
_name = name_;
emit NameUpdated(msg.sender, _name, address(this));
}
/**
* @dev Updates the symbol of the token, only callable by Sygnum operator.
* @param symbol_ The new symbol.
*/
function updateSymbol(string memory symbol_) public onlyOperator {
_symbol = symbol_;
emit SymbolUpdated(msg.sender, symbol_, address(this));
}
/**
* @dev Updates the category of the token, only callable by Sygnum operator.
* @param category_ The new cateogry.
*/
function updateCategory(bytes4 category_) public onlyOperator {
_category = category_;
emit CategoryUpdated(msg.sender, _category, address(this));
}
/**
* @dev Updates the class of the token, only callable by Sygnum operator.
* @param class_ The new class.
*/
function updateClass(string memory class_) public onlyOperator {
_class = class_;
emit ClassUpdated(msg.sender, _class, address(this));
}
/**
* @dev Updates issuer ownership, only callable by Sygnum operator.
* @param issuer_ The new issuer.
*/
function updateIssuer(address issuer_) public onlyOperator {
_issuer = issuer_;
emit IssuerUpdated(msg.sender, _issuer, address(this));
}
}
// File: openzeppelin-solidity/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Overload/ERC20.sol
pragma solidity 0.5.12;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(
account,
_msgSender(),
_allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")
);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/interface/IWhitelist.sol
pragma solidity 0.5.12;
/**
* @title IWhitelist
* @notice Interface for Whitelist contract
*/
contract IWhitelist {
function isWhitelisted(address _account) external view returns (bool);
function toggleWhitelist(address _account, bool _toggled) external;
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/instance/Whitelistable.sol
/**
* @title Whitelistable
* @author Team 3301 <[emailΒ protected]>
* @dev Whitelistable contract stores the Whitelist contract address, and modifiers for
* contracts.
*/
pragma solidity 0.5.12;
contract Whitelistable is Initializable, Operatorable {
IWhitelist internal whitelistInst;
address private whitelistPending;
event WhitelistContractChanged(address indexed caller, address indexed whitelistAddress);
event WhitelistContractPending(address indexed caller, address indexed whitelistAddress);
/**
* @dev Reverts if _account is not whitelisted.
* @param _account address to determine if whitelisted.
*/
modifier whenWhitelisted(address _account) {
require(isWhitelisted(_account), "Whitelistable: account is not whitelisted");
_;
}
/**
* @dev Initialization instead of constructor, called once. The setWhitelistContract function can be called only by Admin role with
* confirmation through the whitelist contract.
* @param _whitelist Whitelist contract address.
* @param _baseOperators BaseOperators contract address.
*/
function initialize(address _baseOperators, address _whitelist) public initializer {
_setOperatorsContract(_baseOperators);
_setWhitelistContract(_whitelist);
}
/**
* @dev Set the new the address of Whitelist contract, should be confirmed from whitelist contract by calling confirmFor(addr)
* where addr is the address of current contract instance. This is done to prevent the case when the new contract address is
* broken and control of the contract can be lost in such case
* @param _whitelist Whitelist contract address.
*/
function setWhitelistContract(address _whitelist) public onlyAdmin {
require(_whitelist != address(0), "Whitelistable: address of new whitelist contract can not be zero");
whitelistPending = _whitelist;
emit WhitelistContractPending(msg.sender, _whitelist);
}
/**
* @dev The function should be called from new whitelist contract by admin to insure that whitelistPending address
* is the real contract address.
*/
function confirmWhitelistContract() public {
require(whitelistPending != address(0), "Whitelistable: address of new whitelist contract can not be zero");
require(msg.sender == whitelistPending, "Whitelistable: should be called from new whitelist contract");
_setWhitelistContract(whitelistPending);
}
/**
* @return The address of the Whitelist contract.
*/
function getWhitelistContract() public view returns (address) {
return address(whitelistInst);
}
/**
* @return The pending address of the Whitelist contract.
*/
function getWhitelistPending() public view returns (address) {
return whitelistPending;
}
/**
* @return If '_account' is whitelisted.
*/
function isWhitelisted(address _account) public view returns (bool) {
return whitelistInst.isWhitelisted(_account);
}
/** INTERNAL FUNCTIONS */
function _setWhitelistContract(address _whitelist) internal {
require(_whitelist != address(0), "Whitelistable: address of new whitelist contract cannot be zero");
whitelistInst = IWhitelist(_whitelist);
emit WhitelistContractChanged(msg.sender, _whitelist);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Whitelist.sol
/**
* @title ERC20Whitelist
* @author Team 3301 <[emailΒ protected]>
* @dev Overloading ERC20 functions to ensure that addresses attempting to particular
* actions are whitelisted.
*/
pragma solidity 0.5.12;
contract ERC20Whitelist is ERC20, Whitelistable {
/**
* @dev Overload transfer function to validate sender and receiver are whitelisted.
* @param to address that recieves the funds.
* @param value amount of funds.
*/
function transfer(address to, uint256 value) public whenWhitelisted(msg.sender) whenWhitelisted(to) returns (bool) {
return super.transfer(to, value);
}
/**
* @dev Overload approve function to validate sender and spender are whitelisted.
* @param spender address that can spend the funds.
* @param value amount of funds.
*/
function approve(address spender, uint256 value)
public
whenWhitelisted(msg.sender)
whenWhitelisted(spender)
returns (bool)
{
return super.approve(spender, value);
}
/**
* @dev Overload transferFrom function to validate sender, from and receiver are whitelisted.
* @param from address that funds will be transferred from.
* @param to address that funds will be transferred to.
* @param value amount of funds.
*/
function transferFrom(
address from,
address to,
uint256 value
) public whenWhitelisted(msg.sender) whenWhitelisted(from) whenWhitelisted(to) returns (bool) {
return super.transferFrom(from, to, value);
}
/**
* @dev Overload increaseAllowance validate sender and spender are whitelisted.
* @param spender address that will be allowed to transfer funds.
* @param addedValue amount of funds to added to current allowance.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
whenWhitelisted(spender)
whenWhitelisted(msg.sender)
returns (bool)
{
return super.increaseAllowance(spender, addedValue);
}
/**
* @dev Overload decreaseAllowance validate sender and spender are whitelisted.
* @param spender address that will be allowed to transfer funds.
* @param subtractedValue amount of funds to be deducted to current allowance.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
whenWhitelisted(spender)
whenWhitelisted(msg.sender)
returns (bool)
{
return super.decreaseAllowance(spender, subtractedValue);
}
/**
* @dev Overload _burn function to ensure that account has been whitelisted.
* @param account address that funds will be burned from.
* @param value amount of funds that will be burned.
*/
function _burn(address account, uint256 value) internal whenWhitelisted(account) {
super._burn(account, value);
}
/**
* @dev Overload _burnFrom function to ensure sender and account have been whitelisted.
* @param account address that funds will be burned from allowance.
* @param amount amount of funds that will be burned.
*/
function _burnFrom(address account, uint256 amount) internal whenWhitelisted(msg.sender) whenWhitelisted(account) {
super._burnFrom(account, amount);
}
/**
* @dev Overload _mint function to ensure account has been whitelisted.
* @param account address that funds will be minted to.
* @param amount amount of funds that will be minted.
*/
function _mint(address account, uint256 amount) internal whenWhitelisted(account) {
super._mint(account, amount);
}
}
// File: @sygnum/solidity-base-contracts/contracts/role/interface/ITraderOperators.sol
/**
* @title ITraderOperators
* @notice Interface for TraderOperators contract
*/
pragma solidity 0.5.12;
contract ITraderOperators {
function isTrader(address _account) external view returns (bool);
function addTrader(address _account) external;
function removeTrader(address _account) external;
}
// File: @sygnum/solidity-base-contracts/contracts/role/trader/TraderOperatorable.sol
/**
* @title TraderOperatorable
* @author Team 3301 <[emailΒ protected]>
* @dev TraderOperatorable contract stores TraderOperators contract address, and modifiers for
* contracts.
*/
pragma solidity 0.5.12;
contract TraderOperatorable is Operatorable {
ITraderOperators internal traderOperatorsInst;
address private traderOperatorsPending;
event TraderOperatorsContractChanged(address indexed caller, address indexed traderOperatorsAddress);
event TraderOperatorsContractPending(address indexed caller, address indexed traderOperatorsAddress);
/**
* @dev Reverts if sender does not have the trader role associated.
*/
modifier onlyTrader() {
require(isTrader(msg.sender), "TraderOperatorable: caller is not trader");
_;
}
/**
* @dev Reverts if sender does not have the operator or trader role associated.
*/
modifier onlyOperatorOrTraderOrSystem() {
require(
isOperator(msg.sender) || isTrader(msg.sender) || isSystem(msg.sender),
"TraderOperatorable: caller is not trader or operator or system"
);
_;
}
/**
* @dev Initialization instead of constructor, called once. The setTradersOperatorsContract function can be called only by Admin role with
* confirmation through the operators contract.
* @param _baseOperators BaseOperators contract address.
* @param _traderOperators TraderOperators contract address.
*/
function initialize(address _baseOperators, address _traderOperators) public initializer {
super.initialize(_baseOperators);
_setTraderOperatorsContract(_traderOperators);
}
/**
* @dev Set the new the address of Operators contract, should be confirmed from operators contract by calling confirmFor(addr)
* where addr is the address of current contract instance. This is done to prevent the case when the new contract address is
* broken and control of the contract can be lost in such case
* @param _traderOperators TradeOperators contract address.
*/
function setTraderOperatorsContract(address _traderOperators) public onlyAdmin {
require(
_traderOperators != address(0),
"TraderOperatorable: address of new traderOperators contract can not be zero"
);
traderOperatorsPending = _traderOperators;
emit TraderOperatorsContractPending(msg.sender, _traderOperators);
}
/**
* @dev The function should be called from new operators contract by admin to insure that traderOperatorsPending address
* is the real contract address.
*/
function confirmTraderOperatorsContract() public {
require(
traderOperatorsPending != address(0),
"TraderOperatorable: address of pending traderOperators contract can not be zero"
);
require(
msg.sender == traderOperatorsPending,
"TraderOperatorable: should be called from new traderOperators contract"
);
_setTraderOperatorsContract(traderOperatorsPending);
}
/**
* @return The address of the TraderOperators contract.
*/
function getTraderOperatorsContract() public view returns (address) {
return address(traderOperatorsInst);
}
/**
* @return The pending TraderOperators contract address
*/
function getTraderOperatorsPending() public view returns (address) {
return traderOperatorsPending;
}
/**
* @return If '_account' has trader privileges.
*/
function isTrader(address _account) public view returns (bool) {
return traderOperatorsInst.isTrader(_account);
}
/** INTERNAL FUNCTIONS */
function _setTraderOperatorsContract(address _traderOperators) internal {
require(
_traderOperators != address(0),
"TraderOperatorable: address of new traderOperators contract can not be zero"
);
traderOperatorsInst = ITraderOperators(_traderOperators);
emit TraderOperatorsContractChanged(msg.sender, _traderOperators);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/Pausable.sol
/**
* @title Pausable
* @author Team 3301 <[emailΒ protected]>
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account in the TraderOperatorable
* contract.
*/
pragma solidity 0.5.12;
contract Pausable is TraderOperatorable {
event Paused(address indexed account);
event Unpaused(address indexed account);
bool internal _paused;
constructor() internal {
_paused = false;
}
/**
* @dev Reverts if contract is paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Reverts if contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by operator to pause child contract. The contract
* must not already be paused.
*/
function pause() public onlyOperatorOrTraderOrSystem whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/** @dev Called by operator to pause child contract. The contract
* must already be paused.
*/
function unpause() public onlyOperatorOrTraderOrSystem whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
/**
* @return If child contract is already paused or not.
*/
function isPaused() public view returns (bool) {
return _paused;
}
/**
* @return If child contract is not paused.
*/
function isNotPaused() public view returns (bool) {
return !_paused;
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Pausable.sol
/**
* @title ERC20Pausable
* @author Team 3301 <[emailΒ protected]>
* @dev Overloading ERC20 functions to ensure that the contract has not been paused.
*/
pragma solidity 0.5.12;
contract ERC20Pausable is ERC20, Pausable {
/**
* @dev Overload transfer function to ensure contract has not been paused.
* @param to address that recieves the funds.
* @param value amount of funds.
*/
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
/**
* @dev Overload approve function to ensure contract has not been paused.
* @param spender address that can spend the funds.
* @param value amount of funds.
*/
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
/**
* @dev Overload transferFrom function to ensure contract has not been paused.
* @param from address that funds will be transferred from.
* @param to address that funds will be transferred to.
* @param value amount of funds.
*/
function transferFrom(
address from,
address to,
uint256 value
) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
/**
* @dev Overload increaseAllowance function to ensure contract has not been paused.
* @param spender address that will be allowed to transfer funds.
* @param addedValue amount of funds to added to current allowance.
*/
function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
/**
* @dev Overload decreaseAllowance function to ensure contract has not been paused.
* @param spender address that will be allowed to transfer funds.
* @param subtractedValue amount of funds to be deducted to current allowance.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
/**
* @dev Overload _burn function to ensure contract has not been paused.
* @param account address that funds will be burned from.
* @param value amount of funds that will be burned.
*/
function _burn(address account, uint256 value) internal whenNotPaused {
super._burn(account, value);
}
/**
* @dev Overload _burnFrom function to ensure contract has not been paused.
* @param account address that funds will be burned from allowance.
* @param amount amount of funds that will be burned.
*/
function _burnFrom(address account, uint256 amount) internal whenNotPaused {
super._burnFrom(account, amount);
}
/**
* @dev Overload _mint function to ensure contract has not been paused.
* @param account address that funds will be minted to.
* @param amount amount of funds that will be minted.
*/
function _mint(address account, uint256 amount) internal whenNotPaused {
super._mint(account, amount);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Mintable.sol
/**
* @title ERC20Mintable
* @author Team 3301 <[emailΒ protected]>
* @dev For blocking and unblocking particular user funds.
*/
pragma solidity 0.5.12;
contract ERC20Mintable is ERC20, Operatorable {
/**
* @dev Overload _mint to ensure only operator or system can mint funds.
* @param account address that will recieve new funds.
* @param amount of funds to be minted.
*/
function _mint(address account, uint256 amount) internal onlyOperatorOrSystem {
require(amount > 0, "ERC20Mintable: amount has to be greater than 0");
super._mint(account, amount);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Snapshot.sol
/**
* @title ERC20Snapshot
* @author Team 3301 <[emailΒ protected]>
* @notice Records historical balances.
*/
pragma solidity 0.5.12;
contract ERC20Snapshot is ERC20 {
using SafeMath for uint256;
/**
* @dev `Snapshot` is the structure that attaches a block number to a
* given value. The block number attached is the one that last changed the value
*/
struct Snapshot {
uint256 fromBlock; // `fromBlock` is the block number at which the value was generated from
uint256 value; // `value` is the amount of tokens at a specific block number
}
/**
* @dev `_snapshotBalances` is the map that tracks the balance of each address, in this
* contract when the balance changes the block number that the change
* occurred is also included in the map
*/
mapping(address => Snapshot[]) private _snapshotBalances;
// Tracks the history of the `totalSupply` of the token
Snapshot[] private _snapshotTotalSupply;
/**
* @dev Queries the balance of `_owner` at a specific `_blockNumber`
* @param _owner The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at `_blockNumber`
*/
function balanceOfAt(address _owner, uint256 _blockNumber) public view returns (uint256) {
return getValueAt(_snapshotBalances[_owner], _blockNumber);
}
/**
* @dev Total amount of tokens at a specific `_blockNumber`.
* @param _blockNumber The block number when the totalSupply is queried
* @return The total amount of tokens at `_blockNumber`
*/
function totalSupplyAt(uint256 _blockNumber) public view returns (uint256) {
return getValueAt(_snapshotTotalSupply, _blockNumber);
}
/**
* @dev `getValueAt` retrieves the number of tokens at a given block number
* @param checkpoints The history of values being queried
* @param _block The block number to retrieve the value at
* @return The number of tokens being queried
*/
function getValueAt(Snapshot[] storage checkpoints, uint256 _block) internal view returns (uint256) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length.sub(1)].fromBlock) {
return checkpoints[checkpoints.length.sub(1)].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
// Binary search of the value in the array
uint256 min;
uint256 max = checkpoints.length.sub(1);
while (max > min) {
uint256 mid = (max.add(min).add(1)).div(2);
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid.sub(1);
}
}
return checkpoints[min].value;
}
/**
* @dev `updateValueAtNow` used to update the `_snapshotBalances` map and the `_snapshotTotalSupply`
* @param checkpoints The history of data being updated
* @param _value The new number of tokens
*/
function updateValueAtNow(Snapshot[] storage checkpoints, uint256 _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length.sub(1)].fromBlock < block.number)) {
checkpoints.push(Snapshot(block.number, _value));
} else {
checkpoints[checkpoints.length.sub(1)].value = _value;
}
}
/**
* @dev Internal function that transfers an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param to The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function transfer(address to, uint256 value) public returns (bool result) {
result = super.transfer(to, value);
updateValueAtNow(_snapshotTotalSupply, totalSupply());
updateValueAtNow(_snapshotBalances[msg.sender], balanceOf(msg.sender));
updateValueAtNow(_snapshotBalances[to], balanceOf(to));
}
/**
* @dev Internal function that transfers an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param from The account that funds will be taken from.
* @param to The account that funds will be given too.
* @param value The amount of funds to be transferred..
*/
function transferFrom(
address from,
address to,
uint256 value
) public returns (bool result) {
result = super.transferFrom(from, to, value);
updateValueAtNow(_snapshotTotalSupply, totalSupply());
updateValueAtNow(_snapshotBalances[from], balanceOf(from));
updateValueAtNow(_snapshotBalances[to], balanceOf(to));
}
/**
* @dev Internal function that confiscates an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param confiscatee The account that funds will be taken from.
* @param receiver The account that funds will be given too.
* @param amount The amount of funds to be transferred..
*/
function _confiscate(
address confiscatee,
address receiver,
uint256 amount
) internal {
super._transfer(confiscatee, receiver, amount);
updateValueAtNow(_snapshotTotalSupply, totalSupply());
updateValueAtNow(_snapshotBalances[confiscatee], balanceOf(confiscatee));
updateValueAtNow(_snapshotBalances[receiver], balanceOf(receiver));
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
super._mint(account, amount);
updateValueAtNow(_snapshotTotalSupply, totalSupply());
updateValueAtNow(_snapshotBalances[account], balanceOf(account));
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
super._burn(account, amount);
updateValueAtNow(_snapshotTotalSupply, totalSupply());
updateValueAtNow(_snapshotBalances[account], balanceOf(account));
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burnFor(address account, uint256 amount) internal {
super._burn(account, amount);
updateValueAtNow(_snapshotTotalSupply, totalSupply());
updateValueAtNow(_snapshotBalances[account], balanceOf(account));
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burnFrom(address account, uint256 amount) internal {
super._burnFrom(account, amount);
updateValueAtNow(_snapshotTotalSupply, totalSupply());
updateValueAtNow(_snapshotBalances[account], balanceOf(account));
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Burnable.sol
/**
* @title ERC20Burnable
* @author Team 3301 <[emailΒ protected]>
* @dev For burning funds from particular user addresses.
*/
pragma solidity 0.5.12;
contract ERC20Burnable is ERC20Snapshot, Operatorable {
/**
* @dev Overload ERC20 _burnFor, burning funds from a particular users address.
* @param account address to burn funds from.
* @param amount of funds to burn.
*/
function _burnFor(address account, uint256 amount) internal onlyOperator {
super._burn(account, amount);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/Freezable.sol
/**
* @title Freezable
* @author Team 3301 <[emailΒ protected]>
* @dev Freezable contract to freeze functionality for particular addresses. Freezing/unfreezing is controlled
* by operators in Operatorable contract which is initialized with the relevant BaseOperators address.
*/
pragma solidity 0.5.12;
contract Freezable is Operatorable {
mapping(address => bool) public frozen;
event FreezeToggled(address indexed account, bool frozen);
/**
* @dev Reverts if address is empty.
* @param _address address to validate.
*/
modifier onlyValidAddress(address _address) {
require(_address != address(0), "Freezable: Empty address");
_;
}
/**
* @dev Reverts if account address is frozen.
* @param _account address to validate is not frozen.
*/
modifier whenNotFrozen(address _account) {
require(!frozen[_account], "Freezable: account is frozen");
_;
}
/**
* @dev Reverts if account address is not frozen.
* @param _account address to validate is frozen.
*/
modifier whenFrozen(address _account) {
require(frozen[_account], "Freezable: account is not frozen");
_;
}
/**
* @dev Getter to determine if address is frozen.
* @param _account address to determine if frozen or not.
* @return bool is frozen
*/
function isFrozen(address _account) public view returns (bool) {
return frozen[_account];
}
/**
* @dev Toggle freeze/unfreeze on _account address, with _toggled being true/false.
* @param _account address to toggle.
* @param _toggled freeze/unfreeze.
*/
function toggleFreeze(address _account, bool _toggled) public onlyValidAddress(_account) onlyOperator {
frozen[_account] = _toggled;
emit FreezeToggled(_account, _toggled);
}
/**
* @dev Batch freeze/unfreeze multiple addresses, with _toggled being true/false.
* @param _addresses address array.
* @param _toggled freeze/unfreeze.
*/
function batchToggleFreeze(address[] memory _addresses, bool _toggled) public {
require(_addresses.length <= 256, "Freezable: batch count is greater than 256");
for (uint256 i = 0; i < _addresses.length; i++) {
toggleFreeze(_addresses[i], _toggled);
}
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Freezable.sol
/**
* @title ERC20Freezable
* @author Team 3301 <[emailΒ protected]>
* @dev Overloading ERC20 functions to ensure client addresses are not frozen for particular actions.
*/
pragma solidity 0.5.12;
contract ERC20Freezable is ERC20, Freezable {
/**
* @dev Overload transfer function to ensure sender and receiver have not been frozen.
* @param to address that recieves the funds.
* @param value amount of funds.
*/
function transfer(address to, uint256 value) public whenNotFrozen(msg.sender) whenNotFrozen(to) returns (bool) {
return super.transfer(to, value);
}
/**
* @dev Overload approve function to ensure sender and receiver have not been frozen.
* @param spender address that can spend the funds.
* @param value amount of funds.
*/
function approve(address spender, uint256 value)
public
whenNotFrozen(msg.sender)
whenNotFrozen(spender)
returns (bool)
{
return super.approve(spender, value);
}
/**
* @dev Overload transferFrom function to ensure sender, approver and receiver have not been frozen.
* @param from address that funds will be transferred from.
* @param to address that funds will be transferred to.
* @param value amount of funds.
*/
function transferFrom(
address from,
address to,
uint256 value
) public whenNotFrozen(msg.sender) whenNotFrozen(from) whenNotFrozen(to) returns (bool) {
return super.transferFrom(from, to, value);
}
/**
* @dev Overload increaseAllowance function to ensure sender and spender have not been frozen.
* @param spender address that will be allowed to transfer funds.
* @param addedValue amount of funds to added to current allowance.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
whenNotFrozen(msg.sender)
whenNotFrozen(spender)
returns (bool)
{
return super.increaseAllowance(spender, addedValue);
}
/**
* @dev Overload decreaseAllowance function to ensure sender and spender have not been frozen.
* @param spender address that will be allowed to transfer funds.
* @param subtractedValue amount of funds to be deducted to current allowance.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
whenNotFrozen(msg.sender)
whenNotFrozen(spender)
returns (bool)
{
return super.decreaseAllowance(spender, subtractedValue);
}
/**
* @dev Overload _burnfrom function to ensure sender and user to be burned from have not been frozen.
* @param account account that funds will be burned from.
* @param amount amount of funds to be burned.
*/
function _burnFrom(address account, uint256 amount) internal whenNotFrozen(msg.sender) whenNotFrozen(account) {
super._burnFrom(account, amount);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Destroyable.sol
/**
* @title ERC20Destroyable
* @author Team 3301 <[emailΒ protected]>
* @notice Allows operator to destroy contract.
*/
pragma solidity 0.5.12;
contract ERC20Destroyable is Operatorable {
event Destroyed(address indexed caller, address indexed account, address indexed contractAddress);
function destroy(address payable to) public onlyOperator {
emit Destroyed(msg.sender, to, address(this));
selfdestruct(to);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Tradeable.sol
/**
* @title ERC20Tradeable
* @author Team 3301 <[emailΒ protected]>
* @dev Trader accounts can approve particular addresses on behalf of a user.
*/
pragma solidity 0.5.12;
contract ERC20Tradeable is ERC20, TraderOperatorable {
/**
* @dev Trader can approve users balance to a particular address for a particular amount.
* @param _owner address that approves the funds.
* @param _spender address that spends the funds.
* @param _value amount of funds.
*/
function approveOnBehalf(
address _owner,
address _spender,
uint256 _value
) public onlyTrader {
super._approve(_owner, _spender, _value);
}
}
// File: @sygnum/solidity-base-contracts/contracts/role/interface/IBlockerOperators.sol
/**
* @title IBlockerOperators
* @notice Interface for BlockerOperators contract
*/
pragma solidity 0.5.12;
contract IBlockerOperators {
function isBlocker(address _account) external view returns (bool);
function addBlocker(address _account) external;
function removeBlocker(address _account) external;
}
// File: @sygnum/solidity-base-contracts/contracts/role/blocker/BlockerOperatorable.sol
/**
* @title BlockerOperatorable
* @author Team 3301 <[emailΒ protected]>
* @dev BlockerOperatorable contract stores BlockerOperators contract address, and modifiers for
* contracts.
*/
pragma solidity 0.5.12;
contract BlockerOperatorable is Operatorable {
IBlockerOperators internal blockerOperatorsInst;
address private blockerOperatorsPending;
event BlockerOperatorsContractChanged(address indexed caller, address indexed blockerOperatorAddress);
event BlockerOperatorsContractPending(address indexed caller, address indexed blockerOperatorAddress);
/**
* @dev Reverts if sender does not have the blocker role associated.
*/
modifier onlyBlocker() {
require(isBlocker(msg.sender), "BlockerOperatorable: caller is not blocker role");
_;
}
/**
* @dev Reverts if sender does not have the blocker or operator role associated.
*/
modifier onlyBlockerOrOperator() {
require(
isBlocker(msg.sender) || isOperator(msg.sender),
"BlockerOperatorable: caller is not blocker or operator role"
);
_;
}
/**
* @dev Initialization instead of constructor, called once. The setBlockerOperatorsContract function can be called only by Admin role with
* confirmation through the operators contract.
* @param _baseOperators BaseOperators contract address.
* @param _blockerOperators BlockerOperators contract address.
*/
function initialize(address _baseOperators, address _blockerOperators) public initializer {
super.initialize(_baseOperators);
_setBlockerOperatorsContract(_blockerOperators);
}
/**
* @dev Set the new the address of BlockerOperators contract, should be confirmed from BlockerOperators contract by calling confirmFor(addr)
* where addr is the address of current contract instance. This is done to prevent the case when the new contract address is
* broken and control of the contract can be lost in such case.
* @param _blockerOperators BlockerOperators contract address.
*/
function setBlockerOperatorsContract(address _blockerOperators) public onlyAdmin {
require(
_blockerOperators != address(0),
"BlockerOperatorable: address of new blockerOperators contract can not be zero."
);
blockerOperatorsPending = _blockerOperators;
emit BlockerOperatorsContractPending(msg.sender, _blockerOperators);
}
/**
* @dev The function should be called from new BlockerOperators contract by admin to insure that blockerOperatorsPending address
* is the real contract address.
*/
function confirmBlockerOperatorsContract() public {
require(
blockerOperatorsPending != address(0),
"BlockerOperatorable: address of pending blockerOperators contract can not be zero"
);
require(
msg.sender == blockerOperatorsPending,
"BlockerOperatorable: should be called from new blockerOperators contract"
);
_setBlockerOperatorsContract(blockerOperatorsPending);
}
/**
* @return The address of the BlockerOperators contract.
*/
function getBlockerOperatorsContract() public view returns (address) {
return address(blockerOperatorsInst);
}
/**
* @return The pending BlockerOperators contract address
*/
function getBlockerOperatorsPending() public view returns (address) {
return blockerOperatorsPending;
}
/**
* @return If '_account' has blocker privileges.
*/
function isBlocker(address _account) public view returns (bool) {
return blockerOperatorsInst.isBlocker(_account);
}
/** INTERNAL FUNCTIONS */
function _setBlockerOperatorsContract(address _blockerOperators) internal {
require(
_blockerOperators != address(0),
"BlockerOperatorable: address of new blockerOperators contract can not be zero"
);
blockerOperatorsInst = IBlockerOperators(_blockerOperators);
emit BlockerOperatorsContractChanged(msg.sender, _blockerOperators);
}
}
// File: @sygnum/solidity-base-contracts/contracts/helpers/ERC20/ERC20Blockable.sol
/**
* @title ERC20Blockable
* @author Team 3301 <[emailΒ protected]>
* @dev For blocking and unblocking particular user funds.
*/
pragma solidity 0.5.12;
contract ERC20Blockable is ERC20, BlockerOperatorable {
uint256 public totalBlockedBalance;
mapping(address => uint256) public _blockedBalances;
event Blocked(address indexed blocker, address indexed account, uint256 value);
event UnBlocked(address indexed blocker, address indexed account, uint256 value);
/**
* @dev Block funds, and move funds from _balances into _blockedBalances.
* @param _account address to block funds.
* @param _amount of funds to block.
*/
function block(address _account, uint256 _amount) public onlyBlockerOrOperator {
_balances[_account] = _balances[_account].sub(_amount);
_blockedBalances[_account] = _blockedBalances[_account].add(_amount);
totalBlockedBalance = totalBlockedBalance.add(_amount);
emit Blocked(msg.sender, _account, _amount);
}
/**
* @dev Unblock funds, and move funds from _blockedBalances into _balances.
* @param _account address to unblock funds.
* @param _amount of funds to unblock.
*/
function unblock(address _account, uint256 _amount) public onlyBlockerOrOperator {
_balances[_account] = _balances[_account].add(_amount);
_blockedBalances[_account] = _blockedBalances[_account].sub(_amount);
totalBlockedBalance = totalBlockedBalance.sub(_amount);
emit UnBlocked(msg.sender, _account, _amount);
}
/**
* @dev Getter for the amount of blocked balance for a particular address.
* @param _account address to get blocked balance.
* @return amount of blocked balance.
*/
function blockedBalanceOf(address _account) public view returns (uint256) {
return _blockedBalances[_account];
}
/**
* @dev Getter for the total amount of blocked funds for all users.
* @return amount of total blocked balance.
*/
function getTotalBlockedBalance() public view returns (uint256) {
return totalBlockedBalance;
}
}
// File: contracts/token/SygnumToken.sol
/**
* @title SygnumToken
* @author Team 3301 <[emailΒ protected]>
* @notice ERC20 token with additional features.
*/
pragma solidity 0.5.12;
contract SygnumToken is
ERC20Snapshot,
ERC20SygnumDetailed,
ERC20Pausable,
ERC20Mintable,
ERC20Whitelist,
ERC20Tradeable,
ERC20Blockable,
ERC20Burnable,
ERC20Freezable,
ERC20Destroyable
{
event Minted(address indexed minter, address indexed account, uint256 value);
event Burned(address indexed burner, uint256 value);
event BurnedFor(address indexed burner, address indexed account, uint256 value);
event Confiscated(address indexed account, uint256 amount, address indexed receiver);
uint16 internal constant BATCH_LIMIT = 256;
/**
* @dev Initialize contracts.
* @param _baseOperators Base operators contract address.
* @param _whitelist Whitelist contract address.
* @param _traderOperators Trader operators contract address.
* @param _blockerOperators Blocker operators contract address.
*/
function initializeContractsAndConstructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
bytes4 _category,
string memory _class,
address _issuer,
address _baseOperators,
address _whitelist,
address _traderOperators,
address _blockerOperators
) public initializer {
super.initialize(_baseOperators);
_setWhitelistContract(_whitelist);
_setTraderOperatorsContract(_traderOperators);
_setBlockerOperatorsContract(_blockerOperators);
_setDetails(_name, _symbol, _decimals, _category, _class, _issuer);
}
/**
* @dev Burn.
* @param _amount Amount of tokens to burn.
*/
function burn(uint256 _amount) public {
require(!isFrozen(msg.sender), "SygnumToken: Account must not be frozen.");
super._burn(msg.sender, _amount);
emit Burned(msg.sender, _amount);
}
/**
* @dev BurnFor.
* @param _account Address to burn tokens for.
* @param _amount Amount of tokens to burn.
*/
function burnFor(address _account, uint256 _amount) public {
super._burnFor(_account, _amount);
emit BurnedFor(msg.sender, _account, _amount);
}
/**
* @dev BurnFrom.
* @param _account Address to burn tokens from.
* @param _amount Amount of tokens to burn.
*/
function burnFrom(address _account, uint256 _amount) public {
super._burnFrom(_account, _amount);
emit Burned(_account, _amount);
}
/**
* @dev Mint.
* @param _account Address to mint tokens to.
* @param _amount Amount to mint.
*/
function mint(address _account, uint256 _amount) public {
if (isSystem(msg.sender)) {
require(!isFrozen(_account), "SygnumToken: Account must not be frozen if system calling.");
}
super._mint(_account, _amount);
emit Minted(msg.sender, _account, _amount);
}
/**
* @dev Confiscate.
* @param _confiscatee Account to confiscate funds from.
* @param _receiver Account to transfer confiscated funds to.
* @param _amount Amount of tokens to confiscate.
*/
function confiscate(
address _confiscatee,
address _receiver,
uint256 _amount
) public onlyOperator whenNotPaused whenWhitelisted(_receiver) whenWhitelisted(_confiscatee) {
super._confiscate(_confiscatee, _receiver, _amount);
emit Confiscated(_confiscatee, _amount, _receiver);
}
/**
* @dev Batch burn for.
* @param _amounts Array of all values to burn.
* @param _accounts Array of all addresses to burn from.
*/
function batchBurnFor(address[] memory _accounts, uint256[] memory _amounts) public {
require(_accounts.length == _amounts.length, "SygnumToken: values and recipients are not equal.");
require(_accounts.length <= BATCH_LIMIT, "SygnumToken: batch count is greater than BATCH_LIMIT.");
for (uint256 i = 0; i < _accounts.length; i++) {
burnFor(_accounts[i], _amounts[i]);
}
}
/**
* @dev Batch mint.
* @param _accounts Array of all addresses to mint to.
* @param _amounts Array of all values to mint.
*/
function batchMint(address[] memory _accounts, uint256[] memory _amounts) public {
require(_accounts.length == _amounts.length, "SygnumToken: values and recipients are not equal.");
require(_accounts.length <= BATCH_LIMIT, "SygnumToken: batch count is greater than BATCH_LIMIT.");
for (uint256 i = 0; i < _accounts.length; i++) {
mint(_accounts[i], _amounts[i]);
}
}
/**
* @dev Batch confiscate to a maximum of 256 addresses.
* @param _confiscatees array of addresses whose funds are being confiscated
* @param _receivers array of addresses who's receiving the funds
* @param _values array of values of funds being confiscated
*/
function batchConfiscate(
address[] memory _confiscatees,
address[] memory _receivers,
uint256[] memory _values
) public returns (bool) {
require(
_confiscatees.length == _values.length && _receivers.length == _values.length,
"SygnumToken: confiscatees, recipients and values are not equal."
);
require(_confiscatees.length <= BATCH_LIMIT, "SygnumToken: batch count is greater than BATCH_LIMIT.");
for (uint256 i = 0; i < _confiscatees.length; i++) {
confiscate(_confiscatees[i], _receivers[i], _values[i]);
}
}
}
// File: contracts/token/upgrade/prd/SygnumTokenV1.sol
/**
* @title MetadataUpgrade
* @author Team 3301 <[emailΒ protected]>
* @dev Upgraded SygnumToken. This upgrade adds the "tokenURI" field, which can hold a link to off chain token metadata.
*/
pragma solidity 0.5.12;
contract SygnumTokenV1 is SygnumToken {
string public tokenURI;
bool public initializedV1;
event TokenUriUpdated(string newToken);
// changed back to public for tests
function initializeContractsAndConstructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
bytes4 _category,
string memory _class,
address _issuer,
address _baseOperators,
address _whitelist,
address _traderOperators,
address _blockerOperators,
string memory _tokenURI
) public {
require(!initializedV1, "SygnumTokenV1: already initialized");
super.initializeContractsAndConstructor(
_name,
_symbol,
_decimals,
_category,
_class,
_issuer,
_baseOperators,
_whitelist,
_traderOperators,
_blockerOperators
);
initializeV1(_tokenURI);
}
function initializeV1(string memory _tokenURI) public {
require(!initializedV1, "SygnumTokenV1: already initialized");
tokenURI = _tokenURI;
initializedV1 = true;
}
function updateTokenURI(string memory _newToken) public onlyOperator {
tokenURI = _newToken;
emit TokenUriUpdated(_newToken);
}
}
// File: contracts/factory/Details.sol
/**
* @title Details
* @author Team 3301 <[emailΒ protected]>
* @notice Shared library for Sygnum token details struct.
*/
pragma solidity 0.5.12;
library Details {
struct TokenDetails {
string name;
string symbol;
uint8 decimals;
bytes4 category;
string class;
address issuer;
string tokenURI;
}
}
// File: contracts/factory/TokenDeployer.sol
/**
* @title TokenDeployer
* @author Team 3301 <[emailΒ protected]>
* @dev Library to deploy and initialize a new instance of Sygnum Equity Token.
* This is commonly used by a TokenFactory to automatically deploy and configure
*/
pragma experimental ABIEncoderV2;
pragma solidity 0.5.12;
library TokenDeployer {
/**
* @dev Initialize a token contracts.
* @param _proxy Address of the proxy
* @param _baseOperators Address of the base operator role contract
* @param _whitelist Address of the whitelist contract
* @param _traderOperators Address of the trader operator role contract
* @param _blockerOperators Address of the blocker operator role contract
* @param _details token details as defined by the TokenDetails struct
*/
function initializeToken(
address _proxy,
address _baseOperators,
address _whitelist,
address _traderOperators,
address _blockerOperators,
Details.TokenDetails memory _details
) public {
SygnumTokenV1(_proxy).initializeContractsAndConstructor(
_details.name,
_details.symbol,
_details.decimals,
_details.category,
_details.class,
_details.issuer,
_baseOperators,
_whitelist,
_traderOperators,
_blockerOperators,
_details.tokenURI
);
}
}
// File: contracts/factory/TokenFactory.sol
/**
* @title TokenFactory
* @author Team 3301 <[emailΒ protected]>
* @dev Token factory to be used by operators to deploy arbitrary Sygnum Equity Token.
*/
pragma solidity 0.5.12;
contract TokenFactory is Initializable, Operatorable {
address public whitelist;
address public proxyAdmin;
address public implementation;
address public traderOperators;
address public blockerOperators;
event UpdatedWhitelist(address indexed whitelist);
event UpdatedTraderOperators(address indexed traderOperators);
event UpdatedBlockerOperators(address indexed blockerOperators);
event UpdatedProxyAdmin(address indexed proxyAdmin);
event UpdatedImplementation(address indexed implementation);
event NewTokenDeployed(address indexed issuer, address token, address proxy);
/**
* @dev Initialization instead of constructor, called once. Sets BaseOperators contract through pausable contract
* resulting in use of Operatorable contract within this contract.
* @param _baseOperators BaseOperators contract address.
* @param _traderOperators TraderOperators contract address.
* @param _blockerOperators BlockerOperators contract address.
* @param _whitelist Whitelist contract address.
*/
function initialize(
address _baseOperators,
address _traderOperators,
address _blockerOperators,
address _whitelist,
address _implementation,
address _proxyAdmin
) public initializer {
require(_baseOperators != address(0), "TokenFactory: _baseOperators cannot be set to an empty address");
require(_traderOperators != address(0), "TokenFactory: _traderOperators cannot be set to an empty address");
require(_blockerOperators != address(0), "TokenFactory: _blockerOperators cannot be set to an empty address");
require(_whitelist != address(0), "TokenFactory: _whitelist cannot be set to an empty address");
require(_implementation != address(0), "TokenFactory: _implementation cannot be set to an empty address");
require(_proxyAdmin != address(0), "TokenFactory: _proxyAdmin cannot be set to an empty address");
traderOperators = _traderOperators;
blockerOperators = _blockerOperators;
whitelist = _whitelist;
proxyAdmin = _proxyAdmin;
implementation = _implementation;
super.initialize(_baseOperators);
}
/**
* @dev allows operator, system or relay to launch a new token with a new name, symbol, decimals, category, and issuer.
* Defaults to using whitelist stored in this contract. If _whitelist is address(0), else it will use
* _whitelist as the param to pass into the new token's constructor upon deployment
* @param _details token details as defined by the TokenDetails struct
* @param _whitelist address
*/
function newToken(Details.TokenDetails memory _details, address _whitelist)
public
onlyOperatorOrSystemOrRelay
returns (address, address)
{
address whitelistAddress;
_whitelist == address(0) ? whitelistAddress = whitelist : whitelistAddress = _whitelist;
address baseOperators = getOperatorsContract();
address proxy = ProxyDeployer.deployTokenProxy(implementation, proxyAdmin, "");
TokenDeployer.initializeToken(
proxy,
baseOperators,
whitelistAddress,
traderOperators,
blockerOperators,
_details
);
emit NewTokenDeployed(_details.issuer, implementation, proxy);
return (implementation, proxy);
}
/**
* @dev updates the whitelist to be used for future generated tokens
* @param _whitelist address
*/
function updateWhitelist(address _whitelist) public onlyOperator {
require(_whitelist != address(0), "TokenFactory: _whitelist cannot be set to an empty address");
whitelist = _whitelist;
emit UpdatedWhitelist(whitelist);
}
/**
* @dev updates the traderOperators contract address to be used for future generated tokens
* @param _traderOperators address
*/
function updateTraderOperators(address _traderOperators) public onlyOperator {
require(_traderOperators != address(0), "TokenFactory: _traderOperators cannot be set to an empty address");
traderOperators = _traderOperators;
emit UpdatedTraderOperators(_traderOperators);
}
/**
* @dev updates the blockerOperators contract address to be used for future generated tokens
* @param _blockerOperators address
*/
function updateBlockerOperators(address _blockerOperators) public onlyOperator {
require(_blockerOperators != address(0), "TokenFactory: _blockerOperators cannot be set to an empty address");
blockerOperators = _blockerOperators;
emit UpdatedBlockerOperators(_blockerOperators);
}
/**
* @dev update the implementation address used when deploying proxy contracts
* @param _implementation address
*/
function updateImplementation(address _implementation) public onlyOperator {
require(_implementation != address(0), "TokenFactory: _implementation cannot be set to an empty address");
implementation = _implementation;
emit UpdatedImplementation(implementation);
}
/**
* @dev update the proxy admin address used when deploying proxy contracts
* @param _proxyAdmin address
*/
function updateProxyAdmin(address _proxyAdmin) public {
require(_proxyAdmin != address(0), "TokenFactory: _proxyAdmin cannot be set to an empty address");
require(msg.sender == proxyAdmin, "TokenFactory: caller not proxy admin");
proxyAdmin = _proxyAdmin;
emit UpdatedProxyAdmin(proxyAdmin);
}
}
|
Updates issuer ownership, only callable by Sygnum operator. issuer_ The new issuer./
|
function updateIssuer(address issuer_) public onlyOperator {
_issuer = issuer_;
emit IssuerUpdated(msg.sender, _issuer, address(this));
}
| 2,087,906
|
pragma solidity ^0.4.24;
/**
* @title SafeMath from zeppelin-solidity
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title PNS - Physical Form of CryptoCurrency Name System
* @dev Physical form cryptocurrency name system smart contract is implemented
* to manage and record physical form cryptocurrency manufacturers'
* informations, such as the name of the manufacturer, the public key
* of the key pair whose private key signed the certificate of the physical
* form cryptocurrency, etc.
*
* @author Hui Xie - <hui.742369@gmail.com>
*/
contract PNS {
using SafeMath for uint256;
// Event of register
event Register(address indexed _from, string _mfr, bytes32 _mid);
// Event of transfer ownership
event Transfer(address indexed _from, string _mfr, bytes32 _mid, address _owner);
// Event of push a new batch
event Push(address indexed _from, string _mfr, bytes32 _mid, string _bn, bytes32 _bid, bytes _key);
// Event of set batch number
event SetBn(address indexed _from, string _mfr, bytes32 _mid, string _bn, bytes32 _bid, bytes _key);
// Event of set public key
event SetKey(address indexed _from, string _mfr, bytes32 _mid, string _bn, bytes32 _bid, bytes _key);
// Event of lock a batch
event Lock(address indexed _from, string _mfr, bytes32 _mid, string _bn, bytes32 _bid, bytes _key);
// Manufacturer informations
struct Manufacturer {
address owner; // owner address
string mfr; // manufacturer name
mapping (bytes32 => Batch) batchmapping; // mapping of batch: mapping (batch ID => batch structure)
mapping (uint256 => bytes32) bidmapping; // mapping of batch ID: mapping (storage index => batch ID), batch ID = keccak256(batch number)
uint256 bidcounter; // storage index counter of bidmapping
}
// Product batch informations
struct Batch {
string bn; // batch number
bytes key; // public key
bool lock; // is changeable or not
}
// Mapping of manufactures: mapping (manufacturer ID => manufacturer struct), Manufacturer ID = keccak256(uppercaseOf(manufacturer name))
mapping (bytes32 => Manufacturer) internal mfrmapping;
// Mapping of manufacturer ID: mapping (storage index => manufacturer ID)
mapping (uint256 => bytes32) internal midmapping;
// Storage index counter of midmapping
uint256 internal midcounter;
/**
* @dev Register a manufacturer.
*
* @param _mfr Manufacturer name
* @return Manufacturer ID
*/
function register(string _mfr) public returns (bytes32) {
require(lengthOf(_mfr) > 0);
require(msg.sender != address(0));
bytes32 mid = keccak256(bytes(uppercaseOf(_mfr)));
require(mfrmapping[mid].owner == address(0));
midcounter = midcounter.add(1);
midmapping[midcounter] = mid;
mfrmapping[mid].owner = msg.sender;
mfrmapping[mid].mfr = _mfr;
emit Register(msg.sender, _mfr, mid);
return mid;
}
/**
* @dev Transfer ownership of a manufacturer.
*
* @param _mid Manufacturer ID
* @param _owner Address of new owner
* @return Batch ID
*/
function transfer(bytes32 _mid, address _owner) public returns (bytes32) {
require(_mid != bytes32(0));
require(_owner != address(0));
require(mfrmapping[_mid].owner != address(0));
require(msg.sender == mfrmapping[_mid].owner);
mfrmapping[_mid].owner = _owner;
emit Transfer(msg.sender, mfrmapping[_mid].mfr, _mid, _owner);
return _mid;
}
/**
* @dev Push(add) a batch.
*
* @param _mid Manufacturer ID
* @param _bn Batch number
* @param _key Public key
* @return Batch ID
*/
function push(bytes32 _mid, string _bn, bytes _key) public returns (bytes32) {
require(_mid != bytes32(0));
require(lengthOf(_bn) > 0);
require(_key.length == 33 || _key.length == 65);
require(mfrmapping[_mid].owner != address(0));
require(msg.sender == mfrmapping[_mid].owner);
bytes32 bid = keccak256(bytes(_bn));
require(lengthOf(mfrmapping[_mid].batchmapping[bid].bn) == 0);
require(mfrmapping[_mid].batchmapping[bid].key.length == 0);
require(mfrmapping[_mid].batchmapping[bid].lock == false);
mfrmapping[_mid].bidcounter = mfrmapping[_mid].bidcounter.add(1);
mfrmapping[_mid].bidmapping[mfrmapping[_mid].bidcounter] = bid;
mfrmapping[_mid].batchmapping[bid].bn = _bn;
mfrmapping[_mid].batchmapping[bid].key = _key;
mfrmapping[_mid].batchmapping[bid].lock = false;
emit Push(msg.sender, mfrmapping[_mid].mfr, _mid, _bn, bid, _key);
return bid;
}
/**
* @dev Set(change) batch number of an unlocked batch.
*
* @param _mid Manufacturer ID
* @param _bid Batch ID
* @param _bn Batch number
* @return Batch ID
*/
function setBn(bytes32 _mid, bytes32 _bid, string _bn) public returns (bytes32) {
require(_mid != bytes32(0));
require(_bid != bytes32(0));
require(lengthOf(_bn) > 0);
require(mfrmapping[_mid].owner != address(0));
require(msg.sender == mfrmapping[_mid].owner);
bytes32 bid = keccak256(bytes(_bn));
require(bid != _bid);
require(lengthOf(mfrmapping[_mid].batchmapping[_bid].bn) > 0);
require(mfrmapping[_mid].batchmapping[_bid].key.length > 0);
require(mfrmapping[_mid].batchmapping[_bid].lock == false);
require(lengthOf(mfrmapping[_mid].batchmapping[bid].bn) == 0);
require(mfrmapping[_mid].batchmapping[bid].key.length == 0);
require(mfrmapping[_mid].batchmapping[bid].lock == false);
uint256 counter = 0;
for (uint256 i = 1; i <= mfrmapping[_mid].bidcounter; i++) {
if (mfrmapping[_mid].bidmapping[i] == _bid) {
counter = i;
break;
}
}
require(counter > 0);
mfrmapping[_mid].bidmapping[counter] = bid;
mfrmapping[_mid].batchmapping[bid].bn = _bn;
mfrmapping[_mid].batchmapping[bid].key = mfrmapping[_mid].batchmapping[_bid].key;
mfrmapping[_mid].batchmapping[bid].lock = false;
delete mfrmapping[_mid].batchmapping[_bid];
emit SetBn(msg.sender, mfrmapping[_mid].mfr, _mid, _bn, bid, mfrmapping[_mid].batchmapping[bid].key);
return bid;
}
/**
* @dev Set(change) public key of an unlocked batch.
*
* @param _mid Manufacturer ID
* @param _bid Batch ID
* @param _key Public key
* @return Batch ID
*/
function setKey(bytes32 _mid, bytes32 _bid, bytes _key) public returns (bytes32) {
require(_mid != bytes32(0));
require(_bid != bytes32(0));
require(_key.length == 33 || _key.length == 65);
require(mfrmapping[_mid].owner != address(0));
require(msg.sender == mfrmapping[_mid].owner);
require(lengthOf(mfrmapping[_mid].batchmapping[_bid].bn) > 0);
require(mfrmapping[_mid].batchmapping[_bid].key.length > 0);
require(mfrmapping[_mid].batchmapping[_bid].lock == false);
mfrmapping[_mid].batchmapping[_bid].key = _key;
emit SetKey(msg.sender, mfrmapping[_mid].mfr, _mid, mfrmapping[_mid].batchmapping[_bid].bn, _bid, _key);
return _bid;
}
/**
* @dev Lock batch. Batch number and public key is unchangeable after it is locked.
*
* @param _mid Manufacturer ID
* @param _bid Batch ID
* @return Batch ID
*/
function lock(bytes32 _mid, bytes32 _bid) public returns (bytes32) {
require(_mid != bytes32(0));
require(_bid != bytes32(0));
require(mfrmapping[_mid].owner != address(0));
require(msg.sender == mfrmapping[_mid].owner);
require(lengthOf(mfrmapping[_mid].batchmapping[_bid].bn) > 0);
require(mfrmapping[_mid].batchmapping[_bid].key.length > 0);
mfrmapping[_mid].batchmapping[_bid].lock = true;
emit Lock(msg.sender, mfrmapping[_mid].mfr, _mid, mfrmapping[_mid].batchmapping[_bid].bn, _bid, mfrmapping[_mid].batchmapping[_bid].key);
return _bid;
}
/**
* @dev Check batch by its batch ID and public key.
*
* @param _mid Manufacturer ID
* @param _bid Batch ID
* @param _key Public key
* @return True or false
*/
function check(bytes32 _mid, bytes32 _bid, bytes _key) public view returns (bool) {
if (mfrmapping[_mid].batchmapping[_bid].key.length != _key.length) {
return false;
}
for (uint256 i = 0; i < _key.length; i++) {
if (mfrmapping[_mid].batchmapping[_bid].key[i] != _key[i]) {
return false;
}
}
return true;
}
/**
* @dev Get total number of manufacturers.
*
* @return Total number of manufacturers
*/
function totalMfr() public view returns (uint256) {
return midcounter;
}
/**
* @dev Get manufacturer ID.
*
* @param _midcounter Storage index counter of midmapping
* @return Manufacturer ID
*/
function midOf(uint256 _midcounter) public view returns (bytes32) {
return midmapping[_midcounter];
}
/**
* @dev Get manufacturer owner.
*
* @param _mid Manufacturer ID
* @return Manufacturer owner
*/
function ownerOf(bytes32 _mid) public view returns (address) {
return mfrmapping[_mid].owner;
}
/**
* @dev Get manufacturer name.
*
* @param _mid Manufacturer ID
* @return Manufacturer name (Uppercase)
*/
function mfrOf(bytes32 _mid) public view returns (string) {
return mfrmapping[_mid].mfr;
}
/**
* @dev Get total batch number of a manufacturer.
*
* @param _mid Manufacturer ID
* @return Total batch number
*/
function totalBatchOf(bytes32 _mid) public view returns (uint256) {
return mfrmapping[_mid].bidcounter;
}
/**
* @dev Get batch ID.
*
* @param _mid Manufacturer ID
* @param _bidcounter Storage index counter of bidmapping
* @return Batch ID
*/
function bidOf(bytes32 _mid, uint256 _bidcounter) public view returns (bytes32) {
return mfrmapping[_mid].bidmapping[_bidcounter];
}
/**
* @dev Get batch number.
*
* @param _mid Manufacturer ID
* @param _bid Batch ID
* @return Batch number
*/
function bnOf(bytes32 _mid, bytes32 _bid) public view returns (string) {
return mfrmapping[_mid].batchmapping[_bid].bn;
}
/**
* @dev Get batch public key.
*
* @param _mid Manufacturer ID
* @param _bid Batch ID
* @return bytes Batch public key
*/
function keyOf(bytes32 _mid, bytes32 _bid) public view returns (bytes) {
if (mfrmapping[_mid].batchmapping[_bid].lock == true) {
return mfrmapping[_mid].batchmapping[_bid].key;
}
}
/**
* @dev Convert string to uppercase.
*
* @param _s String to convert
* @return Converted string
*/
function uppercaseOf(string _s) internal pure returns (string) {
bytes memory b1 = bytes(_s);
uint256 l = b1.length;
bytes memory b2 = new bytes(l);
for (uint256 i = 0; i < l; i++) {
if (b1[i] >= 0x61 && b1[i] <= 0x7A) {
b2[i] = bytes1(uint8(b1[i]) - 32);
} else {
b2[i] = b1[i];
}
}
return string(b2);
}
/**
* @dev Get string length.
*
* @param _s String
* @return length
*/
function lengthOf(string _s) internal pure returns (uint256) {
return bytes(_s).length;
}
}
|
Lock batch. Batch number and public key is unchangeable after it is locked. _mid Manufacturer ID _bid Batch ID return Batch ID/
|
function lock(bytes32 _mid, bytes32 _bid) public returns (bytes32) {
require(_mid != bytes32(0));
require(_bid != bytes32(0));
require(mfrmapping[_mid].owner != address(0));
require(msg.sender == mfrmapping[_mid].owner);
require(lengthOf(mfrmapping[_mid].batchmapping[_bid].bn) > 0);
require(mfrmapping[_mid].batchmapping[_bid].key.length > 0);
mfrmapping[_mid].batchmapping[_bid].lock = true;
emit Lock(msg.sender, mfrmapping[_mid].mfr, _mid, mfrmapping[_mid].batchmapping[_bid].bn, _bid, mfrmapping[_mid].batchmapping[_bid].key);
return _bid;
}
| 2,508,614
|
//
// __ __ _____ ______
// /__/\/__/\ /_____/\ /_____/\
// \ \ \: \ \__\:::_:\ \\:::_ \ \
// \::\_\::\/_/\ _\:\| \:\ \ \ \
// \_::: __\/ /::_/__ \:\ \ \ \
// \::\ \ \:\____/\\:\_\ \ \
// \__\/ \_____\/ \_____\/
//
// 420.game Bud / Game Key Staking
//
// by LOOK LABS
//
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "./interfaces/ILL420HighToken.sol";
/**
* @title LL420BudStaking
* @dev NFT staking contract that can stake/unstake NFTs and calculate the reward.
*
*/
contract LL420BudStaking is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable {
using EnumerableSet for EnumerableSet.UintSet;
using AddressUpgradeable for address;
IERC721Upgradeable public BUD_CONTRACT;
IERC721Upgradeable public GAME_KEY_CONTRACT;
bool public stakingLaunched;
bool public depositPaused;
/// @dev Initial amount of reward within lock period.
uint16 public INITIAL_REWARD;
/// @dev Total amount of staked bud in this contract.
uint16 public totalBudStaked;
/// @dev Total amount of staked gamekey in this contract.
uint16 public totalGameKeyStaked;
uint16[6] public thcInfo;
uint32 public constant SECONDS_IN_DAY = 1 days;
uint256 public LOCK_PERIOD;
uint256 public startTimestamp;
/// @dev Address of reward token address which should be set by LL420.
address public rewardTokenAddress;
/// Address of bud reveal contract address
address public revealContractAddress;
/// @dev Information of each staker.
struct UserInfo {
uint256 reward; /// Reward debt.
uint256 lastCheckpoint; /// timestamp of calc the pending reward.
uint128 budCount;
uint128 gameKeyCount;
}
/// Information of each bud with timestamp and thc.
struct BudInfo {
uint256 timestamp;
uint256 thc;
}
/// address => userInfo structure
mapping(address => UserInfo) public _userInfo;
/// game key id => user bud id array
mapping(uint256 => EnumerableSet.UintSet) private _userBudInfo;
/// address => set of game key ids
mapping(address => EnumerableSet.UintSet) private _gameKeyInfo;
/// bud id => Bud Info
mapping(uint256 => BudInfo) public _budInfo;
/// bud id => bonus id
mapping(uint256 => bool) public _startBonus;
/* ==================== EVENTS ==================== */
event Deposit(address indexed user, uint256 indexed id);
event DepositGameKey(address indexed user, uint256 indexed id);
event Withdraw(address indexed user, uint256 indexed id);
event WithdrawGameKey(address indexed user, uint256 indexed id);
event ClaimReward(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user);
event SetBudTHC(uint256 indexed id, uint256 indexed thc);
/* ==================== MODIFIERS ==================== */
modifier onlyStarted() {
require(
(block.timestamp >= startTimestamp && startTimestamp != 0) || stakingLaunched,
"LL420BudStaking: Staking is not launched yet"
);
_;
}
/* ==================== METHODS ==================== */
/**
* @dev Initializes a staking contract.
* @param _budContract address of the bud contract.
* @param _gameKeyContract address of the GameKey contract.
*/
function initialize(address _budContract, address _gameKeyContract) external initializer {
__Context_init();
__Ownable_init();
__ReentrancyGuard_init();
require(_budContract != address(0), "LL420BudStaking: Wrong BUDS address");
require(_gameKeyContract != address(0), "LL420BudStaking: Wrong GAMEKEY address");
BUD_CONTRACT = IERC721Upgradeable(_budContract);
GAME_KEY_CONTRACT = IERC721Upgradeable(_gameKeyContract);
thcInfo = [420, 520, 620, 720, 1020, 1420];
LOCK_PERIOD = 14 days;
INITIAL_REWARD = 200;
}
/**
* @dev Returns the two arrays of BUD and Game Key
*/
function userInfo(address _user)
external
view
returns (
UserInfo memory,
uint256[] memory,
uint256[] memory
)
{
require(_user != address(0), "LL420BudStaking: user address can't be zero");
UserInfo memory user = _userInfo[_user];
uint256[] memory userBuds = _getUserBuds(_user);
uint256[] memory gameKeys = _getUserGKs(_user);
return (user, gameKeys, userBuds);
}
/**
* @dev returns the bud connected to game key.
* @param _id The id of Game Key.
* @param _user The address of user.
*/
function getGKBuds(uint256 _id, address _user) external view returns (uint256[] memory) {
require(_gameKeyInfo[_user].contains(_id), "LL420BudStaking: Game key is not belong to this user");
uint256 length = _userBudInfo[_id].length();
uint256[] memory buds = new uint256[](length);
for (uint256 i; i < length; i++) {
buds[i] = _userBudInfo[_id].at(i);
}
return buds;
}
/**
* @param _id The id of Game Key.
* @param _ids The ids of Buds to deposit.
*/
function deposit(uint256 _id, uint256[] memory _ids) external nonReentrant onlyStarted {
require(!depositPaused, "LL420BudStaking: Deposit Paused");
require(_ids.length > 0, "LL420BudStaking: Cant deposit zero amount");
require(totalGameKeyStaked > 0, "LL420Staking: GameKey is not staked yet");
require(_gameKeyInfo[_msgSender()].length() > 0, "LL420BudStaking: Need more than 1 GAMEKEY staked");
require(GAME_KEY_CONTRACT.ownerOf(_id) == address(this), "LL420BudStaking: This game key is not staked");
require(_gameKeyInfo[_msgSender()].contains(_id), "LL420BudStaking: Not the owner of Game Key");
UserInfo storage user = _userInfo[_msgSender()];
uint256[] memory userBuds = _getUserBuds(_msgSender());
/// Check if user has pending reward
if (userBuds.length > 0) {
uint256 pending = _getPendingReward(_msgSender());
if (pending > 0) {
user.reward += pending;
}
}
for (uint256 i; i < _ids.length; i++) {
require(BUD_CONTRACT.ownerOf(_ids[i]) == _msgSender(), "LL420BudStaking: Not the owner of BUD");
require(!_userBudInfo[_id].contains(_ids[i]), "LL42-BudStaking: Cant stake same BUDs");
BUD_CONTRACT.transferFrom(_msgSender(), address(this), _ids[i]);
_userBudInfo[_id].add(_ids[i]);
BudInfo storage bud = _budInfo[_ids[i]];
bud.timestamp = block.timestamp;
if (!_startBonus[_ids[i]]) {
_startBonus[_ids[i]] = true;
user.reward += INITIAL_REWARD * 3; /// Gives 3 days bonus
}
emit Deposit(_msgSender(), _ids[i]);
}
totalBudStaked += uint16(_ids.length);
user.budCount += uint128(_ids.length);
user.lastCheckpoint = block.timestamp;
}
/**
* @param _id The id of game key.
* @param _ids The NFT ids to withdraw
*/
function withdraw(uint256 _id, uint256[] memory _ids) external nonReentrant {
return _withdraw(_id, _ids);
}
/**
* @dev Deposit Game Keys.
* @param _ids The GameKey NFT ids to deposit.
*/
function depositGameKey(uint256[] calldata _ids) external nonReentrant onlyStarted {
require(_ids.length > 0, "LL420BudStaking: Cant deposit zero amount of buds");
require(!depositPaused, "LL420BudStaking: Deposit Paused");
UserInfo storage user = _userInfo[_msgSender()];
for (uint256 i; i < _ids.length; i++) {
require(GAME_KEY_CONTRACT.ownerOf(_ids[i]) == _msgSender(), "LL420BudStaking: Not the owner of GAMEKEY");
require(!_gameKeyInfo[_msgSender()].contains(_ids[i]), "LL420BudStaking: Cant stake same GAMEKEY");
GAME_KEY_CONTRACT.transferFrom(_msgSender(), address(this), _ids[i]);
_gameKeyInfo[_msgSender()].add(_ids[i]);
emit DepositGameKey(_msgSender(), _ids[i]);
}
totalGameKeyStaked += uint16(_ids.length);
user.gameKeyCount += uint128(_ids.length);
}
/**
*/
function withdrawGameKey(uint256[] memory _ids) external nonReentrant onlyStarted {
_withdrawGameKey(_ids);
}
/**
*/
function getReward(address _user) external view returns (uint256) {
require(_user != address(0), "LL420BudStaking: user address cant be zero");
UserInfo memory user = _userInfo[_user];
return user.reward + _getPendingReward(_user);
}
/**
* @dev calculate reward per day of one user.
* @param _user The address of staker.
*/
function getDailyReward(address _user) external view returns (uint256) {
require(_user != address(0), "LL420BudStaking: user address cant be zero");
uint256[] memory userBud = _getUserBuds(_user);
uint256 dailyReward;
for (uint256 i; i < userBud.length; i++) {
uint256 tokenId = userBud[i];
BudInfo memory bud = _budInfo[tokenId];
uint256 duration = block.timestamp - bud.timestamp;
if (duration <= LOCK_PERIOD) {
dailyReward += INITIAL_REWARD;
} else {
dailyReward += (bud.thc == 0 ? INITIAL_REWARD : bud.thc);
}
}
return dailyReward;
}
/**
* @dev
* Todo
*/
function claimReward() external nonReentrant {
require(rewardTokenAddress != address(0), "LL420BudStaking: RewardToken is not set yet.");
UserInfo storage user = _userInfo[_msgSender()];
uint256 reward = user.reward;
uint256[] memory userBud = _getUserBuds(_msgSender());
if (userBud.length > 0) {
uint256 pending = _getPendingReward(_msgSender());
if (pending > 0) {
user.reward += pending;
}
}
require(user.reward > 0, "LL420BudStaking: No reward to withdraw");
ILL420HighToken HIGH_TOKEN_CONTRACT = ILL420HighToken(rewardTokenAddress);
HIGH_TOKEN_CONTRACT.claimReward(_msgSender(), user.reward);
user.reward = 0;
user.lastCheckpoint = block.timestamp;
emit ClaimReward(_msgSender(), reward);
}
/**
* @dev returns the bud staking period and reward for each bud per day
*/
function getBudInfo(uint256[] memory _ids) external view returns (uint256[] memory, uint256[] memory) {
uint256[] memory times = new uint256[](_ids.length);
uint256[] memory rewards = new uint256[](_ids.length);
for (uint256 i; i < _ids.length; i++) {
BudInfo memory bud = _budInfo[_ids[i]];
require(bud.timestamp != 0, "LL420BudStaking: Bud is not registered yet");
times[i] = (block.timestamp - bud.timestamp) / SECONDS_IN_DAY;
if (block.timestamp - bud.timestamp <= LOCK_PERIOD) {
rewards[i] = INITIAL_REWARD;
} else {
rewards[i] = bud.thc == 0 ? INITIAL_REWARD : bud.thc;
}
}
return (times, rewards);
}
/* ==================== INTERNAL METHODS ==================== */
/**
* @param _id The id of Game Key.
* @param _ids The BUD NFT ids to deposit.
*/
function _withdraw(uint256 _id, uint256[] memory _ids) internal {
require(_ids.length > 0, "LL420BudStaking: Cant withdraw zero amount");
require(totalBudStaked > 0, "LL420Staking: Bud is not staked yet");
require(totalGameKeyStaked > 0, "LL420Staking: Game Key is not staked yet");
require(_gameKeyInfo[_msgSender()].length() > 0, "LL420BudStaking: Need more than 1 GAMEKEY staked");
require(_userBudInfo[_id].length() > 0, "LL420BudStaking: Game Key doesn't have buds");
require(GAME_KEY_CONTRACT.ownerOf(_id) == address(this), "LL420BudStaking: This game key is not staked");
require(_gameKeyInfo[_msgSender()].contains(_id), "LL420BudStaking: Not the owner of Game Key");
UserInfo storage user = _userInfo[_msgSender()];
require(user.budCount >= _ids.length, "LL420BudStaking: Amount NFTs is wrong");
uint256[] memory userBuds = _getUserBuds(_msgSender());
if (userBuds.length > 0) {
uint256 pending = _getPendingReward(_msgSender());
if (pending > 0) {
user.reward += pending;
}
}
for (uint256 i; i < _ids.length; i++) {
require(_userBudInfo[_id].contains(_ids[i]), "LL420BudStaking: Unautorized id");
BudInfo storage bud = _budInfo[_ids[i]];
BUD_CONTRACT.transferFrom(address(this), _msgSender(), _ids[i]);
_userBudInfo[_id].remove(_ids[i]);
bud.timestamp = 0;
emit Withdraw(_msgSender(), _ids[i]);
}
totalBudStaked -= uint16(_ids.length);
user.budCount -= uint128(_ids.length);
user.lastCheckpoint = block.timestamp;
}
/**
* @dev Internal method of withdrawing Game Key.
*
* @param _ids id array of Game Keys
*/
function _withdrawGameKey(uint256[] memory _ids) internal {
require(_ids.length > 0, "LL420BudStaking: Cant withdraw zero amount of gamekeys");
require(totalGameKeyStaked > 0, "LL420BudStaking: GameKey is not staked yet");
require(_gameKeyInfo[_msgSender()].length() >= _ids.length, "LL420BudStaking: Amount of game keys is wrong");
UserInfo storage user = _userInfo[_msgSender()];
require(user.gameKeyCount >= _ids.length, "LL420BudStaking: Withdraw amount is incorrect");
for (uint256 i; i < _ids.length; i++) {
uint256 gkId = _ids[i];
require(_gameKeyInfo[_msgSender()].contains(gkId), "LL420BudStaking: Unauthroized GAMEKEY id");
uint256 length = _userBudInfo[gkId].length();
uint256[] memory gkBuds = new uint256[](length);
for (uint256 j; j < length; j++) {
gkBuds[j] = _userBudInfo[gkId].at(j);
}
if (gkBuds.length > 0) {
_withdraw(gkId, gkBuds);
}
GAME_KEY_CONTRACT.transferFrom(address(this), _msgSender(), _ids[i]);
_gameKeyInfo[_msgSender()].remove(_ids[i]);
emit WithdrawGameKey(_msgSender(), _ids[i]);
}
totalGameKeyStaked -= uint16(_ids.length);
unchecked {
user.gameKeyCount -= uint128(_ids.length);
}
}
/**
* @dev Funtion calculates and returns the reward of staker.
* @param _user The address of staker.
*/
function _getPendingReward(address _user) internal view returns (uint256) {
require(_user != address(0), "LL420BudStaking: user address cant be zero");
UserInfo memory user = _userInfo[_user];
uint256[] memory userBuds = _getUserBuds(_user);
uint256 pendingReward;
uint256 length = userBuds.length;
require(length > 0, "LL420BudStaking: Empty bud for this staker");
for (uint256 i; i < length; i++) {
BudInfo memory bud = _budInfo[userBuds[i]];
if (block.timestamp - bud.timestamp <= LOCK_PERIOD) {
pendingReward += ((block.timestamp - user.lastCheckpoint) / SECONDS_IN_DAY) * INITIAL_REWARD;
} else if (user.lastCheckpoint - bud.timestamp <= LOCK_PERIOD) {
pendingReward +=
INITIAL_REWARD *
((bud.timestamp + LOCK_PERIOD) / SECONDS_IN_DAY - user.lastCheckpoint / SECONDS_IN_DAY);
pendingReward +=
(bud.thc == 0 ? INITIAL_REWARD : bud.thc) *
((block.timestamp - bud.timestamp - LOCK_PERIOD) / SECONDS_IN_DAY);
} else {
pendingReward +=
(bud.thc == 0 ? INITIAL_REWARD : bud.thc) *
((block.timestamp - user.lastCheckpoint) / SECONDS_IN_DAY);
}
}
return pendingReward;
}
/**
*/
function _getUserBuds(address _user) internal view returns (uint256[] memory) {
require(_user != address(0), "LL420BudStaking: user address cant be zero");
UserInfo memory user = _userInfo[_user];
uint256[] memory userBud = new uint256[](user.budCount);
uint256 count = 0;
for (uint256 i; i < _gameKeyInfo[_user].length(); i++) {
uint256 gameKeyId = _gameKeyInfo[_user].at(i);
for (uint256 j; j < _userBudInfo[gameKeyId].length(); j++) {
userBud[count++] = _userBudInfo[gameKeyId].at(j);
}
}
return userBud;
}
/**
*/
function _getUserGKs(address _user) internal view returns (uint256[] memory) {
require(_user != address(0), "LL420BudStaking: user address cant be zero");
uint256 gameKeyLength = _gameKeyInfo[_user].length();
uint256[] memory gameKeys = new uint256[](gameKeyLength);
for (uint256 i; i < gameKeyLength; i++) {
gameKeys[i] = _gameKeyInfo[_user].at(i);
}
return gameKeys;
}
/**
*/
// function _checkPair()
/* ==================== OWNER METHODS ==================== */
/**
* @dev Function allows to set HIGH token address.
* @param _token address of HIGH token address.
*/
function setRewardTokenAddress(address _token) external onlyOwner {
require(_token != address(0), "LL420BudStaking: Token address can't be zero ");
rewardTokenAddress = _token;
}
/**
* @dev Function activates the staking contract.
*/
function launchStaking() external onlyOwner {
require(!stakingLaunched, "LL420BudStaking: Staking has been launched already");
stakingLaunched = true;
}
/**
* @dev Function sets the start time to launch staking.
*/
function setStartTimestamp(uint256 _startTimestamp) external onlyOwner {
startTimestamp = _startTimestamp;
}
/**
* @dev Function allows to pause deposits if needed.
* @param _pause status of deposit to be set.
*/
function pauseDeposit(bool _pause) external onlyOwner {
depositPaused = _pause;
}
/**
* @dev Owner can withdraw one single nfts back to stakers in emergency.
* It withdraws only NFTS, not reward.
*/
function emergencyWithdraw(address _user) external onlyOwner {
require(_user != address(0), "LL420BudStaking: user address cant be zero");
UserInfo storage user = _userInfo[_user];
user.lastCheckpoint = block.timestamp;
uint256 gameKeyLength = _gameKeyInfo[_user].length();
for (uint256 i; i < gameKeyLength; i++) {
uint256 gkId = _gameKeyInfo[_user].at(0);
require(
GAME_KEY_CONTRACT.ownerOf(gkId) == address(this),
"LL420BudStaking: Game Key is not belong to this contract"
);
uint256 budLength = _userBudInfo[gkId].length();
for (uint256 j; j < budLength; j++) {
uint256 tokenId = _userBudInfo[gkId].at(0);
require(
BUD_CONTRACT.ownerOf(tokenId) == address(this),
"LL420BudStaking: Bud is not belong to this contract"
);
BUD_CONTRACT.safeTransferFrom(address(this), _user, tokenId);
_userBudInfo[gkId].remove(tokenId);
}
totalBudStaked -= uint16(budLength);
GAME_KEY_CONTRACT.safeTransferFrom(address(this), _user, gkId);
_gameKeyInfo[_user].remove(gkId);
}
totalGameKeyStaked -= uint16(gameKeyLength);
user.budCount = 0;
user.gameKeyCount = 0;
emit EmergencyWithdraw(_user);
}
/**
* @dev
*/
function setLockPeriod(uint256 _days) external onlyOwner {
LOCK_PERIOD = _days * 1 days;
}
/**
* @dev Set LL420Reveal contract address
*/
function setRevealContractAddress(address _address) external onlyOwner {
require(_address != address(0), "Zero address error");
revealContractAddress = _address;
}
/* ==================== THIRD PARTY METHODS ==================== */
/**
* @dev Function sets the THC level of each bud.
* only allows for LL420Reveal cntract
*
* _thc 0 => 4.20 $HIGH/day
* _thc 1 => 5.20 $HIGH/day
* _thc 2 => 6.20 $HIGH/day
* _thc 3 => 7.20 $HIGH/day
* _thc 4 => 10.20 $HIGH/day
* _thc 5 => 14.20 $HIGH/day
*
* @param _ids id of all bud
* @param _thc => index of thc [0 to 5]
*/
function setTHC(uint256[] calldata _ids, uint256[] calldata _thc) external {
require(_ids.length == _thc.length, "LL420BudStaking: id and thc are not matching");
require(revealContractAddress != address(0), "LL420BudStaking: Reveal contract is not set yet");
require(
revealContractAddress == _msgSender() || owner() == _msgSender(),
"LL420BudStaking: Only able to call from reveal contract"
);
for (uint256 i; i < _ids.length; i++) {
BudInfo storage bud = _budInfo[_ids[i]];
bud.thc = thcInfo[_thc[i]];
emit SetBudTHC(_ids[i], bud.thc);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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 {
__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);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = 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);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ILL420HighToken {
function claimReward(address account, uint256 amount) external;
}
// 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/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts 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 {
}
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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts 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);
}
|
Funtion calculates and returns the reward of staker. _user The address of staker./
|
function _getPendingReward(address _user) internal view returns (uint256) {
require(_user != address(0), "LL420BudStaking: user address cant be zero");
UserInfo memory user = _userInfo[_user];
uint256[] memory userBuds = _getUserBuds(_user);
uint256 pendingReward;
uint256 length = userBuds.length;
require(length > 0, "LL420BudStaking: Empty bud for this staker");
for (uint256 i; i < length; i++) {
BudInfo memory bud = _budInfo[userBuds[i]];
if (block.timestamp - bud.timestamp <= LOCK_PERIOD) {
pendingReward += ((block.timestamp - user.lastCheckpoint) / SECONDS_IN_DAY) * INITIAL_REWARD;
pendingReward +=
INITIAL_REWARD *
((bud.timestamp + LOCK_PERIOD) / SECONDS_IN_DAY - user.lastCheckpoint / SECONDS_IN_DAY);
pendingReward +=
(bud.thc == 0 ? INITIAL_REWARD : bud.thc) *
((block.timestamp - bud.timestamp - LOCK_PERIOD) / SECONDS_IN_DAY);
pendingReward +=
(bud.thc == 0 ? INITIAL_REWARD : bud.thc) *
((block.timestamp - user.lastCheckpoint) / SECONDS_IN_DAY);
}
}
return pendingReward;
}
| 13,590,782
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@lbertenasco/contract-utils/contracts/utils/UtilsReady.sol";
import "../sugar-mommy/Keep3rJob.sol";
import "../../interfaces/keep3r/IVaultKeep3rJob.sol";
import "../../interfaces/yearn/IEarnableVault.sol";
contract VaultKeep3rJob is UtilsReady, Keep3rJob, IVaultKeep3rJob {
using SafeMath for uint256;
mapping(address => uint256) public requiredEarn;
mapping(address => uint256) public lastEarnAt;
uint256 public earnCooldown;
EnumerableSet.AddressSet internal _availableVaults;
constructor(address _keep3rSugarMommy, uint256 _earnCooldown) public UtilsReady() Keep3rJob(_keep3rSugarMommy) {
_setEarnCooldown(_earnCooldown);
}
function isVaultKeep3rJob() external pure override returns (bool) {
return true;
}
// Setters
function addVaults(address[] calldata _vaults, uint256[] calldata _requiredEarns) external override onlyGovernor {
require(_vaults.length == _requiredEarns.length, "vault-keep3r::add-vaults:vaults-required-earns-different-length");
for (uint256 i; i < _vaults.length; i++) {
_addVault(_vaults[i], _requiredEarns[i]);
}
}
function addVault(address _vault, uint256 _requiredEarn) external override onlyGovernor {
_addVault(_vault, _requiredEarn);
}
function _addVault(address _vault, uint256 _requiredEarn) internal {
require(requiredEarn[_vault] == 0, "vault-keep3r::add-vault:vault-already-added");
_setRequiredEarn(_vault, _requiredEarn);
_availableVaults.add(_vault);
emit VaultAdded(_vault, _requiredEarn);
}
function updateRequiredEarnAmount(address _vault, uint256 _requiredEarn) external override onlyGovernor {
require(requiredEarn[_vault] > 0, "vault-keep3r::update-required-earn:vault-not-added");
_setRequiredEarn(_vault, _requiredEarn);
emit VaultModified(_vault, _requiredEarn);
}
function removeVault(address _vault) external override onlyGovernor {
require(requiredEarn[_vault] > 0, "vault-keep3r::remove-vault:vault-not-added");
requiredEarn[_vault] = 0;
_availableVaults.remove(_vault);
emit VaultRemoved(_vault);
}
function _setRequiredEarn(address _vault, uint256 _requiredEarn) internal {
require(_requiredEarn > 0, "vault-keep3r::set-required-earn:should-not-be-zero");
requiredEarn[_vault] = _requiredEarn;
}
function setEarnCooldown(uint256 _earnCooldown) external override onlyGovernor {
_setEarnCooldown(_earnCooldown);
}
function _setEarnCooldown(uint256 _earnCooldown) internal {
require(_earnCooldown > 0, "vault-keep3r::set-earn-cooldown:should-not-be-zero");
earnCooldown = _earnCooldown;
}
// Getters
function vaults() public view override returns (address[] memory _vaults) {
_vaults = new address[](_availableVaults.length());
for (uint256 i; i < _availableVaults.length(); i++) {
_vaults[i] = _availableVaults.at(i);
}
}
function calculateEarn(address _vault) public view override returns (uint256 _amount) {
require(requiredEarn[_vault] > 0, "vault-keep3r::calculate-earn:vault-not-added");
return IEarnableVault(_vault).available();
}
function workable(address _vault) public view override returns (bool) {
require(requiredEarn[_vault] > 0, "vault-keep3r::workable:vault-not-added");
return (calculateEarn(_vault) >= requiredEarn[_vault] && block.timestamp > lastEarnAt[_vault].add(earnCooldown));
}
// Keep3r actions
function work(address _vault) external override {
require(workable(_vault), "vault-keep3r::earn:not-workable");
_startJob(msg.sender);
_earn(_vault);
_endJob(msg.sender);
emit EarnByKeeper(_vault);
}
// Governor keeper bypass
function forceWork(address _vault) external override onlyGovernor {
_earn(_vault);
emit EarnByGovernor(_vault);
}
function _earn(address _vault) internal {
IEarnableVault(_vault).earn();
lastEarnAt[_vault] = block.timestamp;
}
}
// 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.8;
import './Governable.sol';
import './CollectableDust.sol';
import './Pausable.sol';
import './Migratable.sol';
abstract
contract UtilsReady is Governable, CollectableDust, Pausable, Migratable {
constructor() public Governable(msg.sender) {
}
// Governable: restricted-access
function setPendingGovernor(address _pendingGovernor) external override onlyGovernor {
_setPendingGovernor(_pendingGovernor);
}
function acceptGovernor() external override onlyPendingGovernor {
_acceptGovernor();
}
// Collectable Dust: restricted-access
function sendDust(
address _to,
address _token,
uint256 _amount
) external override virtual onlyGovernor {
_sendDust(_to, _token, _amount);
}
// Pausable: restricted-access
function pause(bool _paused) external override onlyGovernor {
_pause(_paused);
}
// Migratable: restricted-access
function migrate(address _to) external onlyGovernor {
_migrated(_to);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@lbertenasco/contract-utils/contracts/utils/UtilsReady.sol";
import "../../interfaces/sugar-mommy/IKeep3rSugarMommy.sol";
import "../../interfaces/sugar-mommy/IKeep3rJob.sol";
abstract contract Keep3rJob is IKeep3rJob {
using SafeMath for uint256;
IKeep3rSugarMommy public Keep3rSugarMommy;
constructor(address _keep3rSugarMommy) public {
Keep3rSugarMommy = IKeep3rSugarMommy(_keep3rSugarMommy);
}
function isKeep3rJob() external pure override returns (bool) {
return true;
}
// Keep3rSugarMommy actions
function _startJob(address _keeper) internal {
Keep3rSugarMommy.start(_keeper);
}
function _endJob(address _keeper) internal {
Keep3rSugarMommy.end(_keeper, address(0), 0);
}
function _endJob(address _keeper, uint256 _amount) internal {
Keep3rSugarMommy.end(_keeper, address(0), _amount);
}
function _endJob(
address _keeper,
address _credit,
uint256 _amount
) internal {
Keep3rSugarMommy.end(_keeper, _credit, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IVaultKeep3rJob {
event VaultAdded(address _vault, uint256 _requiredEarn);
event VaultModified(address _vault, uint256 _requiredEarn);
event VaultRemoved(address _vault);
function isVaultKeep3rJob() external pure returns (bool);
// Actions by Keeper
event EarnByKeeper(address _vault);
// Actions forced by governance
event EarnByGovernor(address _vault);
// Keep3r actions
function workable(address _vault) external view returns (bool);
function work(address _vault) external;
// Governance Keeper bypass
function forceWork(address _vault) external;
// Setters
function addVaults(address[] calldata _vaults, uint256[] calldata _requiredEarns) external;
function addVault(address _vault, uint256 _requiredEarn) external;
function updateRequiredEarnAmount(address _vault, uint256 _requiredEarn) external;
function removeVault(address _vault) external;
function setEarnCooldown(uint256 _earnCooldown) external;
// Getters
function vaults() external view returns (address[] memory _vaults);
function calculateEarn(address _vault) external view returns (uint256 _amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IEarnableVault {
function earn() external;
function available() external view returns (uint256 _available);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
import '../../interfaces/utils/IGovernable.sol';
abstract
contract Governable is IGovernable {
address public governor;
address public pendingGovernor;
constructor(address _governor) public {
require(_governor != address(0), 'governable/governor-should-not-be-zero-address');
governor = _governor;
}
function _setPendingGovernor(address _pendingGovernor) internal {
require(_pendingGovernor != address(0), 'governable/pending-governor-should-not-be-zero-addres');
pendingGovernor = _pendingGovernor;
emit PendingGovernorSet(_pendingGovernor);
}
function _acceptGovernor() internal {
governor = pendingGovernor;
pendingGovernor = address(0);
emit GovernorAccepted();
}
modifier onlyGovernor {
require(msg.sender == governor, 'governable/only-governor');
_;
}
modifier onlyPendingGovernor {
require(msg.sender == pendingGovernor, 'governable/only-pending-governor');
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/utils/EnumerableSet.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import '../../interfaces/utils/ICollectableDust.sol';
abstract
contract CollectableDust is ICollectableDust {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
EnumerableSet.AddressSet internal protocolTokens;
constructor() public {}
function _addProtocolToken(address _token) internal {
require(!protocolTokens.contains(_token), 'collectable-dust/token-is-part-of-the-protocol');
protocolTokens.add(_token);
}
function _removeProtocolToken(address _token) internal {
require(protocolTokens.contains(_token), 'collectable-dust/token-not-part-of-the-protocol');
protocolTokens.remove(_token);
}
function _sendDust(
address _to,
address _token,
uint256 _amount
) internal {
require(_to != address(0), 'collectable-dust/cant-send-dust-to-zero-address');
require(!protocolTokens.contains(_token), 'collectable-dust/token-is-part-of-the-protocol');
if (_token == ETH_ADDRESS) {
payable(_to).transfer(_amount);
} else {
IERC20(_token).safeTransfer(_to, _amount);
}
emit DustSent(_to, _token, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
import '../../interfaces/utils/IPausable.sol';
abstract
contract Pausable is IPausable {
bool public paused;
constructor() public {}
modifier notPaused() {
require(!paused, 'paused');
_;
}
function _pause(bool _paused) internal {
require(paused != _paused, 'no-change');
paused = _paused;
emit Paused(_paused);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
import '../../interfaces/utils/IMigratable.sol';
abstract
contract Migratable is IMigratable {
address public override migratedTo;
constructor() public {}
modifier notMigrated() {
require(migratedTo == address(0), 'migrated');
_;
}
function _migrated(address _to) internal {
require(migratedTo == address(0), 'already-migrated');
require(_to != address(0), 'migrate-to-address-0');
migratedTo = _to;
emit Migrated(_to);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
interface IGovernable {
event PendingGovernorSet(address pendingGovernor);
event GovernorAccepted();
function setPendingGovernor(address _pendingGovernor) external;
function acceptGovernor() external;
}
// 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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(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));
}
}
// 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.8;
interface ICollectableDust {
event DustSent(address _to, address token, uint256 amount);
function sendDust(address _to, address _token, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
interface IPausable {
event Paused(bool _paused);
function pause(bool _paused) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
interface IMigratable {
event Migrated(address _to);
function migratedTo() external view returns (address _to);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IKeep3rSugarMommy {
event Keep3rSet(address _keep3r);
event Keep3rRequirementsSet(address _bond, uint256 _minBond, uint256 _earned, uint256 _age, bool _onlyEOA);
event JobStarted(address _job, address _keeper);
event JobEnded(address _job, address _keeper);
function isKeep3rSugarMommy() external pure returns (bool);
function setKeep3r(address _keep3r) external;
function setKeep3rRequirements(
address _bond,
uint256 _minBond,
uint256 _earned,
uint256 _age,
bool _onlyEOA
) external;
function jobs() external view returns (address[] memory validJobs);
function start(address _keeper) external;
function end(
address _keeper,
address _credit,
uint256 _amount
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IKeep3rJob {
function isKeep3rJob() external pure returns (bool);
// Mock functions
// function workable() external view returns (bool);
// function work() external;
// function forceWork() external;
}
|
Keep3rSugarMommy actions
|
function _startJob(address _keeper) internal {
Keep3rSugarMommy.start(_keeper);
}
| 271,559
|
./full_match/80001/0xcC980ea9fb6104462870884D7fCa7372843E183d/sources/project:/node_modules/@openzeppelin/contracts/token/ERC721/presets/ERC721PresetMinterPauserAutoId.sol
|
Creates a new token for `to`. Its token ID will be automatically assigned (and available on the emitted {IERC721-Transfer} event), and the token URI autogenerated based on the base URI passed at construction. See {ERC721-_mint}. Requirements: - the caller must have the `MINTER_ROLE`./ We cannot just use balanceOf to create the new tokenId because tokens can be burned (destroyed), so we need a separate counter.
|
function mint(address to, uint256 tokenId) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint");
_mint(to, tokenId);
}
| 5,613,429
|
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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 amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract HeroCoin is StandardToken {
// data structures
enum States {
Initial, // deployment time
ValuationSet,
Ico, // whitelist addresses, accept funds, update balances
Underfunded, // ICO time finished and minimal amount not raised
Operational, // manage contests
Paused // for contract upgrades
}
//should be constant, but is not, to avoid compiler warning
address public rakeEventPlaceholderAddress = 0x0000000000000000000000000000000000000000;
string public constant name = "Herocoin";
string public constant symbol = "PLAY";
uint8 public constant decimals = 18;
mapping (address => bool) public whitelist;
address public initialHolder;
address public stateControl;
address public whitelistControl;
address public withdrawControl;
States public state;
uint256 public weiICOMinimum;
uint256 public weiICOMaximum;
uint256 public silencePeriod;
uint256 public startAcceptingFundsBlock;
uint256 public endBlock;
uint256 public ETH_HEROCOIN; //number of herocoins per ETH
mapping (address => uint256) lastRakePoints;
uint256 pointMultiplier = 1e18; //100% = 1*10^18 points
uint256 totalRakePoints; //total amount of rakes ever paid out as a points value. increases monotonically, but the number range is 2^256, that's enough.
uint256 unclaimedRakes; //amount of coins unclaimed. acts like a special entry to balances
uint256 constant percentForSale = 30;
mapping (address => bool) public contests; // true if this address holds a contest
//this creates the contract and stores the owner. it also passes in 3 addresses to be used later during the lifetime of the contract.
function HeroCoin(address _stateControl, address _whitelistControl, address _withdraw, address _initialHolder) {
initialHolder = _initialHolder;
stateControl = _stateControl;
whitelistControl = _whitelistControl;
withdrawControl = _withdraw;
moveToState(States.Initial);
weiICOMinimum = 0;
//to be overridden
weiICOMaximum = 0;
endBlock = 0;
ETH_HEROCOIN = 0;
totalSupply = 2000000000 * pointMultiplier;
//sets the value in the superclass.
balances[initialHolder] = totalSupply;
//initially, initialHolder has 100%
}
event ContestAnnouncement(address addr);
event Whitelisted(address addr);
event Credited(address addr, uint balance, uint txAmount);
event StateTransition(States oldState, States newState);
modifier onlyWhitelist() {
require(msg.sender == whitelistControl);
_;
}
modifier onlyOwner() {
require(msg.sender == initialHolder);
_;
}
modifier onlyStateControl() {
require(msg.sender == stateControl);
_;
}
modifier onlyWithdraw() {
require(msg.sender == withdrawControl);
_;
}
modifier requireState(States _requiredState) {
require(state == _requiredState);
_;
}
/**
BEGIN ICO functions
*/
//this is the main funding function, it updates the balances of Herocoins during the ICO.
//no particular incentive schemes have been implemented here
//it is only accessible during the "ICO" phase.
function() payable
requireState(States.Ico)
{
require(whitelist[msg.sender] == true);
require(this.balance <= weiICOMaximum); //note that msg.value is already included in this.balance
require(block.number < endBlock);
require(block.number >= startAcceptingFundsBlock);
uint256 heroCoinIncrease = msg.value * ETH_HEROCOIN;
balances[initialHolder] -= heroCoinIncrease;
balances[msg.sender] += heroCoinIncrease;
Credited(msg.sender, balances[msg.sender], msg.value);
}
function moveToState(States _newState)
internal
{
StateTransition(state, _newState);
state = _newState;
}
// ICO contract configuration function
// newEthICOMinimum is the minimum amount of funds to raise
// newEthICOMaximum is the maximum amount of funds to raise
// silencePeriod is a number of blocks to wait after starting the ICO. No funds are accepted during the silence period. It can be set to zero.
// newEndBlock is the absolute block number at which the ICO must stop. It must be set after now + silence period.
function updateEthICOThresholds(uint256 _newWeiICOMinimum, uint256 _newWeiICOMaximum, uint256 _silencePeriod, uint256 _newEndBlock)
onlyStateControl
{
require(state == States.Initial || state == States.ValuationSet);
require(_newWeiICOMaximum > _newWeiICOMinimum);
require(block.number + silencePeriod < _newEndBlock);
require(block.number < _newEndBlock);
weiICOMinimum = _newWeiICOMinimum;
weiICOMaximum = _newWeiICOMaximum;
silencePeriod = _silencePeriod;
endBlock = _newEndBlock;
// initial conversion rate of ETH_HEROCOIN set now, this is used during the Ico phase.
ETH_HEROCOIN = ((totalSupply * percentForSale) / 100) / weiICOMaximum;
// check pointMultiplier
moveToState(States.ValuationSet);
}
function startICO()
onlyStateControl
requireState(States.ValuationSet)
{
require(block.number < endBlock);
require(block.number + silencePeriod < endBlock);
startAcceptingFundsBlock = block.number + silencePeriod;
moveToState(States.Ico);
}
function endICO()
onlyStateControl
requireState(States.Ico)
{
if (this.balance < weiICOMinimum) {
moveToState(States.Underfunded);
}
else {
burnUnsoldCoins();
moveToState(States.Operational);
}
}
function anyoneEndICO()
requireState(States.Ico)
{
require(block.number > endBlock);
if (this.balance < weiICOMinimum) {
moveToState(States.Underfunded);
}
else {
burnUnsoldCoins();
moveToState(States.Operational);
}
}
function burnUnsoldCoins()
internal
{
uint256 soldcoins = this.balance * ETH_HEROCOIN;
totalSupply = soldcoins * 100 / percentForSale;
balances[initialHolder] = totalSupply - soldcoins;
//slashing the initial supply, so that the ico is selling 30% total
}
function addToWhitelist(address _whitelisted)
onlyWhitelist
// requireState(States.Ico)
{
whitelist[_whitelisted] = true;
Whitelisted(_whitelisted);
}
//emergency pause for the ICO
function pause()
onlyStateControl
requireState(States.Ico)
{
moveToState(States.Paused);
}
//in case we want to completely abort
function abort()
onlyStateControl
requireState(States.Paused)
{
moveToState(States.Underfunded);
}
//un-pause
function resumeICO()
onlyStateControl
requireState(States.Paused)
{
moveToState(States.Ico);
}
//in case of a failed/aborted ICO every investor can get back their money
function requestRefund()
requireState(States.Underfunded)
{
require(balances[msg.sender] > 0);
//there is no need for updateAccount(msg.sender) since the token never became active.
uint256 payout = balances[msg.sender] / ETH_HEROCOIN;
//reverse calculate the amount to pay out
balances[msg.sender] = 0;
msg.sender.transfer(payout);
}
//after the ico has run its course, the withdraw account can drain funds bit-by-bit as needed.
function requestPayout(uint _amount)
onlyWithdraw //very important!
requireState(States.Operational)
{
msg.sender.transfer(_amount);
}
/**
END ICO functions
*/
/**
BEGIN ERC20 functions
*/
function transfer(address _to, uint256 _value)
requireState(States.Operational)
updateAccount(msg.sender) //update senders rake before transfer, so they can access their full balance
updateAccount(_to) //update receivers rake before transfer as well, to avoid over-attributing rake
enforceRake(msg.sender, _value)
returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)
requireState(States.Operational)
updateAccount(_from) //update senders rake before transfer, so they can access their full balance
updateAccount(_to) //update receivers rake before transfer as well, to avoid over-attributing rake
enforceRake(_from, _value)
returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
function balanceOf(address _account)
constant
returns (uint256 balance) {
return balances[_account] + rakesOwing(_account);
}
function payRake(uint256 _value)
requireState(States.Operational)
updateAccount(msg.sender)
returns (bool success) {
return payRakeInternal(msg.sender, _value);
}
function
payRakeInternal(address _sender, uint256 _value)
internal
returns (bool success) {
if (balances[_sender] <= _value) {
return false;
}
if (_value != 0) {
Transfer(_sender, rakeEventPlaceholderAddress, _value);
balances[_sender] -= _value;
unclaimedRakes += _value;
// calc amount of points from total:
uint256 pointsPaid = _value * pointMultiplier / totalSupply;
totalRakePoints += pointsPaid;
}
return true;
}
/**
END ERC20 functions
*/
/**
BEGIN Rake modifier updateAccount
*/
modifier updateAccount(address _account) {
uint256 owing = rakesOwing(_account);
if (owing != 0) {
unclaimedRakes -= owing;
balances[_account] += owing;
Transfer(rakeEventPlaceholderAddress, _account, owing);
}
//also if 0 this needs to be called, since lastRakePoints need the right value
lastRakePoints[_account] = totalRakePoints;
_;
}
//todo use safemath.sol
function rakesOwing(address _account)
internal
constant
returns (uint256) {//returns always > 0 value
//how much is _account owed, denominated in points from total supply
uint256 newRakePoints = totalRakePoints - lastRakePoints[_account];
//always positive
//weigh by my balance (dimension HC*10^18)
uint256 basicPoints = balances[_account] * newRakePoints;
//still positive
//normalize to dimension HC by moving comma left by 18 places
return (basicPoints) / pointMultiplier;
}
/**
END Rake modifier updateAccount
*/
// contest management functions
modifier enforceRake(address _contest, uint256 _value){
//we calculate 1% of the total value, rounded up. division would round down otherwise.
//explicit brackets illustrate that the calculation only round down when dividing by 100, to avoid an expression
// like value * (99/100)
if (contests[_contest]) {
uint256 toPay = _value - ((_value * 99) / 100);
bool paid = payRakeInternal(_contest, toPay);
require(paid);
}
_;
}
// all functions require HeroCoin operational state
// registerContest declares a contest to HeroCoin.
// It must be called from an address that has HeroCoin.
// This address is recorded as the contract admin.
function registerContest()
{
contests[msg.sender] = true;
ContestAnnouncement(msg.sender);
}
}
|
requireState(States.Ico)
|
function addToWhitelist(address _whitelisted)
onlyWhitelist
{
whitelist[_whitelisted] = true;
Whitelisted(_whitelisted);
}
| 12,862,537
|
pragma solidity 0.5.11;
pragma experimental ABIEncoderV2;
import "./PaymentStandardExitRouterArgs.sol";
import "../PaymentExitGameArgs.sol";
import "../PaymentExitDataModel.sol";
import "../controllers/PaymentStartStandardExit.sol";
import "../controllers/PaymentProcessStandardExit.sol";
import "../controllers/PaymentChallengeStandardExit.sol";
import "../../registries/SpendingConditionRegistry.sol";
import "../../utils/BondSize.sol";
import "../../../vaults/EthVault.sol";
import "../../../vaults/Erc20Vault.sol";
import "../../../framework/PlasmaFramework.sol";
import "../../../framework/interfaces/IExitProcessor.sol";
import "../../../utils/OnlyWithValue.sol";
import "../../../utils/OnlyFromAddress.sol";
import "../../../utils/FailFastReentrancyGuard.sol";
contract PaymentStandardExitRouter is
IExitProcessor,
OnlyFromAddress,
OnlyWithValue,
FailFastReentrancyGuard
{
using PaymentStartStandardExit for PaymentStartStandardExit.Controller;
using PaymentChallengeStandardExit for PaymentChallengeStandardExit.Controller;
using PaymentProcessStandardExit for PaymentProcessStandardExit.Controller;
using BondSize for BondSize.Params;
// Initial bond size = 233000 (gas cost of challenge) * 50 gwei (current fast gas price) * 2 (safety margin)
uint128 public constant INITIAL_BOND_SIZE = 23300000000000000 wei;
// Each bond size upgrade can either at most increase to 200% or decrease to 50% of current bond
uint16 public constant BOND_LOWER_BOUND_DIVISOR = 2;
uint16 public constant BOND_UPPER_BOUND_MULTIPLIER = 2;
// Initial exit bounty size = 107000 (approx gas usage for processExit) * 50 gwei (current fast gas price)
uint128 public constant INITIAL_EXIT_BOUNTY_SIZE = 5350000000000000 wei;
PaymentExitDataModel.StandardExitMap internal standardExitMap;
PaymentStartStandardExit.Controller internal startStandardExitController;
PaymentProcessStandardExit.Controller internal processStandardExitController;
PaymentChallengeStandardExit.Controller internal challengeStandardExitController;
BondSize.Params internal startStandardExitBond;
PlasmaFramework private framework;
bool private bootDone = false;
event StandardExitBondUpdated(uint128 bondSize, uint128 exitBountySize);
event ExitStarted(
address indexed owner,
uint168 exitId
);
event ExitChallenged(
uint256 indexed utxoPos
);
event ExitOmitted(
uint168 indexed exitId
);
event ExitFinalized(
uint168 indexed exitId
);
event BondReturnFailed(
address indexed receiver,
uint256 amount
);
function boot(PaymentExitGameArgs.Args memory paymentExitGameArgs)
internal
{
require(msg.sender == paymentExitGameArgs.framework.getMaintainer(), "Only Maintainer can perform this action");
require(!bootDone, "Exit game was already initialized");
EthVault ethVault = EthVault(paymentExitGameArgs.framework.vaults(paymentExitGameArgs.ethVaultId));
require(address(ethVault) != address(0), "Invalid ETH vault");
Erc20Vault erc20Vault = Erc20Vault(paymentExitGameArgs.framework.vaults(paymentExitGameArgs.erc20VaultId));
require(address(erc20Vault) != address(0), "Invalid ERC20 vault");
framework = paymentExitGameArgs.framework;
bootDone = true;
startStandardExitController = PaymentStartStandardExit.buildController(
this,
paymentExitGameArgs.framework,
paymentExitGameArgs.ethVaultId,
paymentExitGameArgs.erc20VaultId,
paymentExitGameArgs.supportTxType
);
challengeStandardExitController = PaymentChallengeStandardExit.buildController(
paymentExitGameArgs.framework,
paymentExitGameArgs.spendingConditionRegistry,
paymentExitGameArgs.safeGasStipend
);
processStandardExitController = PaymentProcessStandardExit.Controller(
paymentExitGameArgs.framework, ethVault, erc20Vault, paymentExitGameArgs.safeGasStipend
);
startStandardExitBond = BondSize.buildParams(INITIAL_BOND_SIZE, INITIAL_EXIT_BOUNTY_SIZE, BOND_LOWER_BOUND_DIVISOR, BOND_UPPER_BOUND_MULTIPLIER);
}
/**
* @notice Getter retrieves standard exit data of the PaymentExitGame
* @param exitIds Exit IDs of the standard exits
*/
function standardExits(uint168[] calldata exitIds) external view returns (PaymentExitDataModel.StandardExit[] memory) {
PaymentExitDataModel.StandardExit[] memory exits = new PaymentExitDataModel.StandardExit[](exitIds.length);
for (uint i = 0; i < exitIds.length; i++){
uint168 exitId = exitIds[i];
exits[i] = standardExitMap.exits[exitId];
}
return exits;
}
/**
* @notice Retrieves the standard exit bond size
*/
function startStandardExitBondSize() public view returns (uint128) {
return startStandardExitBond.bondSize();
}
/**
* @notice Updates the standard exit bond size and/or the exit bounty size, taking two days to become effective
* @notice Remember to set the bond appropriately higher than the bounty because the bond remaining after bounty is returned
* @param newBondSize The new bond size
* @param newExitBountySize The new exit bounty size
*/
function updateStartStandardExitBondSize(uint128 newBondSize, uint128 newExitBountySize) public onlyFrom(framework.getMaintainer()) {
startStandardExitBond.updateBondSize(newBondSize, newExitBountySize);
emit StandardExitBondUpdated(newBondSize, newExitBountySize);
}
/**
* @notice Retrieves the process standard exit bounty size
*/
function processStandardExitBountySize() public view returns (uint128) {
return startStandardExitBond.exitBountySize();
}
/**
* @notice Starts a standard exit of a given output, using output-age priority
*/
function startStandardExit(
PaymentStandardExitRouterArgs.StartStandardExitArgs memory args
)
public
payable
nonReentrant(framework)
onlyWithValue(startStandardExitBondSize())
{
uint128 bountySize = processStandardExitBountySize();
startStandardExitController.run(standardExitMap, args, bountySize);
}
/**
* @notice Challenge a standard exit by showing the exiting output was spent
*/
function challengeStandardExit(PaymentStandardExitRouterArgs.ChallengeStandardExitArgs memory args)
public
nonReentrant(framework)
{
challengeStandardExitController.run(standardExitMap, args);
}
/**
* @notice Process standard exit
* @dev This function is designed to be called in the main processExit function, using internal
* @param exitId The standard exit ID
* @param token The token (in erc20 address or address(0) for ETH) of the exiting output
* @param processExitInitiator The processExits() initiator
*/
function processStandardExit(uint168 exitId, address token, address payable processExitInitiator) internal {
processStandardExitController.run(standardExitMap, exitId, token, processExitInitiator);
}
}
|
Getter retrieves standard exit data of the PaymentExitGame exitIds Exit IDs of the standard exits/
|
function standardExits(uint168[] calldata exitIds) external view returns (PaymentExitDataModel.StandardExit[] memory) {
PaymentExitDataModel.StandardExit[] memory exits = new PaymentExitDataModel.StandardExit[](exitIds.length);
for (uint i = 0; i < exitIds.length; i++){
uint168 exitId = exitIds[i];
exits[i] = standardExitMap.exits[exitId];
}
return exits;
}
| 12,791,538
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import {BytesLib} from '@interlay/bitcoin-spv-sol/contracts/BytesLib.sol';
import {BTCUtils} from '@interlay/bitcoin-spv-sol/contracts/BTCUtils.sol';
library Script {
using BytesLib for bytes;
using BTCUtils for bytes;
bytes1 internal constant OP_HASH160 = 0xa9;
bytes1 internal constant OP_EQUAL = 0x87;
bytes1 internal constant OP_DUP = 0x76;
bytes1 internal constant OP_EQUALVERIFY = 0x88;
bytes1 internal constant OP_CHECKSIG = 0xac;
bytes1 internal constant OP_CHECKLOCKTIMEVERIFY = 0xb1;
bytes1 internal constant OP_DROP = 0x75;
bytes1 internal constant OP_0 = 0x00;
bytes1 internal constant OP_RETURN = 0x6a;
// EXCEPTION MESSAGES
string internal constant ERR_INVALID_SIZE = 'Invalid size';
string internal constant ERR_INVALID_OPCODE = 'Invalid opcode';
// 0x76 (OP_DUP) - 0xa9 (OP_HASH160) - 0x14 (20 bytes len) - <20 bytes pubkey hash> - 0x88 (OP_EQUALVERIFY) - 0xac (OP_CHECKSIG)
function isP2PKH(bytes memory script) internal pure returns (bool) {
return
(script.length == 25) &&
(script[0] == OP_DUP) &&
(script[1] == OP_HASH160) &&
(script[2] == 0x14) &&
(script[23] == OP_EQUALVERIFY) &&
(script[24] == OP_CHECKSIG);
}
// solhint-disable-next-line func-name-mixedcase
function P2PKH(bytes memory script) internal pure returns (bytes20) {
return toBytes20(script.slice(3, 20));
}
function isP2WPKH(bytes memory script) internal pure returns (bool) {
return (script.length == 22) && (script[1] == 0x14);
}
// solhint-disable-next-line func-name-mixedcase
function P2WPKH(bytes memory script)
internal
pure
returns (bytes1, bytes20)
{
return (script[0], toBytes20(script.slice(2, 20)));
}
// 0xa9 (OP_HASH160) - 0x14 (20 bytes hash) - <20 bytes script hash> - 0x87 (OP_EQUAL)
function isP2SH(bytes memory script) internal pure returns (bool) {
return
(script.length == 23) &&
(script[0] == OP_HASH160) &&
(script[1] == 0x14) &&
(script[22] == OP_EQUAL);
}
// solhint-disable-next-line func-name-mixedcase
function P2SH(bytes memory script) internal pure returns (bytes20) {
return toBytes20(script.slice(2, 20));
}
function isOpReturn(bytes memory script) internal pure returns (bool) {
return script[0] == OP_RETURN;
}
function OpReturn(bytes memory script)
internal
pure
returns (bytes memory)
{
bytes memory output = script.slice(1, script.length - 1);
return output.slice(1, uint8(output[0]));
}
// 04 9f7b2a5c b1 75 76 a9 14 371c20fb2e9899338ce5e99908e64fd30b789313 88 ac
function isCLTV(bytes memory script)
internal
pure
returns (uint256, bytes memory)
{
uint256 varIntLen = script.determineVarIntDataLength();
if (varIntLen == 0) {
varIntLen = 1;
}
uint256 timeLen = script.slice(0, varIntLen).bytesToUint();
uint256 timestamp = script
.slice(varIntLen, timeLen)
.reverseEndianness()
.bytesToUint();
uint256 pos = varIntLen + timeLen;
require(script.length == pos + 27, ERR_INVALID_SIZE);
require(script[pos] == OP_CHECKLOCKTIMEVERIFY, ERR_INVALID_OPCODE);
require(script[pos + 1] == OP_DROP, ERR_INVALID_OPCODE);
require(script[pos + 2] == OP_DUP, ERR_INVALID_OPCODE);
require(script[pos + 3] == OP_HASH160, ERR_INVALID_OPCODE);
require(script[pos + 4] == 0x14, ERR_INVALID_OPCODE); // OP_PUSHDATA
require(script[pos + 5 + 20] == OP_EQUALVERIFY, ERR_INVALID_OPCODE);
require(script[pos + 6 + 20] == OP_CHECKSIG, ERR_INVALID_OPCODE);
return (timestamp, script.slice(pos + 5, 20));
}
function toBytes20(bytes memory data)
internal
pure
returns (bytes20 result)
{
if (data.length == 0) {
return 0x0;
}
assembly {
// solhint-disable-previous-line no-inline-assembly
result := mload(add(data, 0x20))
}
}
}
|
solhint-disable-next-line func-name-mixedcase
|
function P2SH(bytes memory script) internal pure returns (bytes20) {
return toBytes20(script.slice(2, 20));
}
| 13,039,546
|
./full_match/100/0x015780415e2FFdB7480D82e1ac8BD03EDDCec607/sources/github/chiru-labs/ERC721A/contracts/COWCITIZEN.sol
|
_safeMint's second argument now takes in a quantity, not a tokenId.
|
function mint(uint256 quantity) external onlyOwner {
_safeMint(msg.sender, quantity);
}
| 14,269,616
|
./full_match/5/0x6cE76A16D90a99029167E5713e81B670702757c7/sources/wallet.sol
|
bool sent = payable(msg.sender).send(msg.value); require(sent, "Transaction failed");
|
function deposit(uint amount) external payable {
require(amount > 0, "Deposit amount must be greater than 0.");
require(msg.sender.balance > 0, "inzufficient fundz");
}
| 1,860,565
|
./full_match/1/0x420CBD9f1CB5351D347F4B5D44D83a91514C43b0/sources/contracts/OlimpoPass.sol
|
This internal function is used to check if a given phase `_id` exists./
|
function _phaseExists(uint256 _id) internal view {
if (abi.encodePacked(phases[_id].phaseName).length == 0) {
revert PhaseDoesNotExist(_id);
}
}
| 2,976,860
|
./full_match/5/0x1129549CE336FdBb4c8b114BD5053eee88f97b1d/sources/project:/contracts/BridgeBase.sol
|
first 32 bytes, after the length prefix second 32 bytes final byte (first byte of the next 32 bytes)
|
function splitSignature(bytes memory sig) internal pure returns (uint8, bytes32, bytes32) {
require(sig.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
| 1,932,444
|
./full_match/1/0xbC72B4617e8Fae53fcF0Dd428E16aC5F830C1440/sources/contracts/ousdkeeper.sol
|
If either can run, let's go!
|
function checkUpkeep(bytes calldata checkData)
external
view
override
returns (bool upkeepNeeded, bytes memory performData)
{
(bool runRebase, bool runAllocate) = _shouldRun(checkData);
upkeepNeeded = (runRebase || runAllocate);
performData = checkData;
}
| 3,062,563
|
// SPDX-License-Identifier: MIT
// https://github.com/OpenZeppelin/openzeppelin-contracts/commit/8e0296096449d9b1cd7c5631e917330635244c37
import 'openzeppelin-solidity/contracts/utils/EnumerableSet.sol';
import 'openzeppelin-solidity/contracts/token/ERC721/ERC721Burnable.sol';
import 'openzeppelin-solidity/contracts/cryptography/ECDSA.sol';
import 'openzeppelin-solidity/contracts/math/SafeMath.sol';
import './IERC2981.sol';
import './BaseRelayRecipient.sol';
pragma experimental ABIEncoderV2;
pragma solidity 0.6.12;
contract NOAP is ERC721Burnable, BaseRelayRecipient, IERC2981 {
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.UintSet;
string private constant ERROR_INVALID_INPUTS = "Each field must have the same number of values";
struct Evt {
bool ended;
address royalty;
string tokenURI;
EnumerableSet.UintSet tokens;
EnumerableSet.AddressSet minters;
}
mapping(address => EnumerableSet.UintSet) private userEventIDs;
mapping(uint256 => Evt) evts;
mapping(uint256 => uint256) private tokenToEventID;
mapping(bytes32 => uint256) private hashToEventID;
uint256 private tokenIDCounter;
uint256 private eventIDCounter;
uint256 private constant _NULL_EVENT_ID = 0;
address private constant _NULL_ADDRESS = 0x0000000000000000000000000000000000000000;
bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
constructor() public ERC721("NOAPs", "NOAP") {
_registerInterface(_INTERFACE_ID_ERC2981);
// hardcode the trusted forwarded for EIP2771 metatransactions
_setTrustedForwarder(0x86C80a8aa58e0A4fa09A69624c31Ab2a6CAD56b8); // xDAI trusted forwarder
}
/**
* Mint a single token
*/
function mint(
uint256 eventID,
address recipient
) external {
Evt storage evt = evts[eventID];
require(!evt.ended, "Event Ended");
_checkSenderIsMinter(evt);
_mintEventToken(recipient, eventID);
}
/**
* Mint multiple tokens for a single event
*/
function mintBatch(
uint256 eventID,
address[] memory recipients
) external {
Evt storage evt = evts[eventID];
require(!evt.ended, "Event Ended");
_checkSenderIsMinter(evt);
for (uint i = 0; i < recipients.length; i++) {
_mintEventToken(recipients[i], eventID);
}
}
/**
* Burn a token from another contract and mint it here, copying the metadata
* The token owner must have `approve` this contract to access the token beforehand
*/
function burnAndRemint(
address tokenContract,
uint256 tokenID
) public {
require(tokenContract != address(this), "Cannot burn and remint on the same contract");
// Grab the tokenURI
ERC721Burnable collection = ERC721Burnable(tokenContract);
string memory tokenURI = collection.tokenURI(tokenID);
// Burn the source NFT
collection.transferFrom(_msgSender(), address(this), tokenID);
collection.burn(tokenID);
// Load the event obj from the URI, creating a new event ID if non-existent
bytes32 eventHash = _computeEventHash(tokenContract, tokenURI);
uint256 eventID = hashToEventID[eventHash];
if (eventID == _NULL_EVENT_ID) {
eventID = _createEvent(eventHash, tokenURI);
}
_mintEventToken(_msgSender(), eventID);
}
/**
* Batch API to burn and remint, for those feeling frisky.
*/
function burnAndRemintBatch(
address[] memory tokenContracts,
uint256[] memory tokenIDs
) external {
require(tokenContracts.length == tokenIDs.length, ERROR_INVALID_INPUTS);
for (uint i = 0; i < tokenContracts.length; i++) {
burnAndRemint(tokenContracts[i], tokenIDs[i]);
}
}
/**
* Batch API to burn and remint, for those feeling frisky.
*/
function burnAndRemintBatchDenver(
address[] memory tokenContracts,
uint256[] memory tokenIDs,
string memory tokenURI
) external {
bytes32 eventHash = _computeEventHash(address(this), tokenURI);
uint256 eventID = hashToEventID[eventHash];
require(eventID != _NULL_EVENT_ID,"Event Does Not Exist!");
Evt storage evt = evts[eventID];
require(!evt.ended, "Event Ended");
require(tokenContracts.length == tokenIDs.length && tokenIDs.length == 5, ERROR_INVALID_INPUTS);
for (uint i = 0; i < tokenContracts.length; i++) {
burnAndRemint(tokenContracts[i], tokenIDs[i]);
}
_mintEventToken(_msgSender(), eventID);
}
/**
* Create an event based on the metadata URI.
* The caller is the sole minter.
* Each event is a unique <contract, tokenURI> pair and cannot be recreated.
*/
function createEvent(
string memory tokenURI
) external {
bytes32 eventHash = _computeEventHash(address(this), tokenURI);
uint256 eventID = _createEvent(eventHash, tokenURI);
Evt storage evt = evts[eventID];
evt.minters.add(_msgSender());
evt.royalty = _msgSender();
userEventIDs[_msgSender()].add(eventID);
}
/**
* End the event, halting minting.
* Token minting from other contracts (burned and reminted here) cannot be halted.
*/
function endEvent(
uint256 eventID
) external {
Evt storage evt = evts[eventID];
_checkSenderIsMinter(evt);
evt.ended = true;
}
/**
* Add a minter to the event. Minter can create infinite tokens. Caller must be a minter
*/
function addEventMinter(
uint256 eventID,
address minter
) external {
Evt storage evt = evts[eventID];
_checkSenderIsMinter(evt);
evt.minters.add(minter);
userEventIDs[minter].add(eventID);
}
function renounceEventMinter(
uint256 eventID
) external {
Evt storage evt = evts[eventID];
_checkSenderIsMinter(evt);
evt.minters.remove(_msgSender());
userEventIDs[_msgSender()].remove(eventID);
}
function _checkSenderIsMinter(
Evt storage evt
) internal view {
require(evt.minters.contains(_msgSender()), "Not event minter");
}
function _createEvent(
bytes32 eventHash,
string memory tokenURI
) internal returns (uint256) {
require(hashToEventID[eventHash] == _NULL_EVENT_ID, "Event already created");
uint256 eventID = ++eventIDCounter;
evts[eventID].tokenURI = tokenURI;
// Map the event hash back to the Event
hashToEventID[eventHash] = eventID;
return eventID;
}
function _mintEventToken(
address recipient,
uint256 eventID
) internal {
// Mint the token. ID is generated by hashing the source contract and id, bitmasked for shortness
uint256 tokenID = ++tokenIDCounter;
_mint(recipient, tokenID);
// Increment the minted counter
evts[eventID].tokens.add(tokenID);
// Map the token back to the Event
tokenToEventID[tokenID] = eventID;
}
function _computeEventHash(
address tokenContract,
string memory tokenURI
) internal pure returns (bytes32) {
return keccak256(abi.encode(tokenContract, tokenURI));
}
function getEventMinterTotal(
uint256 eventID
) public view returns (uint256) {
return evts[eventID].minters.length();
}
function getEventMinterAt(
uint256 eventID,
uint256 index
) public view returns (address) {
return evts[eventID].minters.at(index);
}
function getEventIsMinter(
uint256 eventID,
address addr
) public view returns (bool) {
return evts[eventID].minters.contains(addr);
}
function getEventTokenSupply(
uint256 eventID
) public view returns (uint256) {
return evts[eventID].tokens.length();
}
function getEventTokenURI(
uint256 eventID
) public view returns (string memory) {
return evts[eventID].tokenURI;
}
function getEventTokenIDAt(
uint256 eventID,
uint256 index
) public view returns (uint256) {
return evts[eventID].tokens.at(index);
}
function getEventTokenIDs(
uint256 eventID
) public view returns (uint256[] memory) {
uint256 supply = getEventTokenSupply(eventID);
uint256[] memory tokenIDs = new uint256[](supply);
for (uint i = 0; i < tokenIDs.length; i++) {
tokenIDs[i] = getEventTokenIDAt(eventID, i);
}
return tokenIDs;
}
function getEventTokenHolders(
uint256 eventID
) public view returns (address[] memory) {
uint256 supply = getEventTokenSupply(eventID);
address[] memory owners = new address[](supply);
for (uint i = 0; i < owners.length; i++) {
owners[i] = ownerOf(getEventTokenIDAt(eventID, i));
}
return owners;
}
function getEventEnded(
uint256 eventID
) public view returns (bool) {
return evts[eventID].ended;
}
function getEventRoyaltyAddress(
uint256 eventID
) public view returns (address) {
return evts[eventID].royalty;
}
function getLastTokenID() public view returns (uint) {
return tokenIDCounter;
}
function getLastEventID() public view returns (uint) {
return eventIDCounter;
}
function getUserEventTotal(
address user
) public view returns (uint256) {
return userEventIDs[user].length();
}
function getUserEventAt(
address user,
uint256 index
) public view returns (uint256) {
return userEventIDs[user].at(index);
}
function getUserEventIDs(
address user
) public view returns (uint256[] memory) {
uint256 numEvents = getUserEventTotal(user);
uint256[] memory eventIDs = new uint256[](numEvents);
for (uint i = 0; i < numEvents; i++) {
eventIDs[i] = getUserEventAt(user, i);
}
return eventIDs;
}
/**
* ERC2981 royalty implementation
* For events created using this contract, we hardcode a 10% resale royalty the corresponding tokens
* The recipient of this royalty is controlled by the event minters.
*/
function royaltyInfo(
uint256 tokenID,
uint256 salePrice
) external view override returns (address, uint256) {
address royalty = evts[tokenToEventID[tokenID]].royalty;
if (royalty == _NULL_ADDRESS) {
// For tokens that are burned and reminted,
// we don't track the creator, so zero royalties.
return (_NULL_ADDRESS, 0);
}
return (royalty, salePrice / 10);
}
/**
* Allow any of the event minters to change the royalty recipient
*/
function changeRoyaltyReceiver(uint256 eventID, address receiver) external {
Evt storage evt = evts[eventID];
_checkSenderIsMinter(evt);
evt.royalty = receiver;
}
/* -- END ERC2981 methods */
/**
* Overwrite the default `tokenURI` getter.
* Since all events have the same tokenURI, resolve tokenIDs to events load the URI from the event
*/
function tokenURI(uint256 tokenID) public view virtual override returns (string memory) {
require(_exists(tokenID), "ERC721Metadata: URI query for nonexistent token");
return evts[tokenToEventID[tokenID]].tokenURI;
}
function burn(uint256 tokenID) public virtual override {
super.burn(tokenID);
evts[tokenToEventID[tokenID]].tokens.remove(tokenID);
}
function isApprovedOrOwner(
address spender,
uint256 tokenID
) external view returns (bool) {
return _isApprovedOrOwner(spender, tokenID);
}
/* -- BEGIN batch methods */
function burnBatch(
uint256[] memory tokenIDs
) external {
for (uint256 i = 0; i < tokenIDs.length; ++i) {
burn(tokenIDs[i]);
}
}
function approveBatch(
address[] memory tos,
uint256[] memory tokenIDs
) external {
require(tos.length == tokenIDs.length, ERROR_INVALID_INPUTS);
for (uint256 i = 0; i < tos.length; ++i) {
approve(tos[i], tokenIDs[i]);
}
}
function transferFromBatch(
address[] memory froms,
address[] memory tos,
uint256[] memory tokenIDs
) external {
require(
froms.length == tos.length &&
froms.length == tokenIDs.length,
ERROR_INVALID_INPUTS
);
for (uint256 i = 0; i < froms.length; ++i) {
transferFrom(froms[i], tos[i], tokenIDs[i]);
}
}
function safeTransferFromBatch(
address[] memory froms,
address[] memory tos,
uint256[] memory tokenIDs
) external {
require(
froms.length == tos.length &&
froms.length == tokenIDs.length,
ERROR_INVALID_INPUTS
);
for (uint256 i = 0; i < froms.length; ++i) {
safeTransferFrom(froms[i], tos[i], tokenIDs[i], "");
}
}
function safeTransferFromWithDataBatch(
address[] memory froms,
address[] memory tos,
uint256[] memory tokenIDs,
bytes[] memory datas
) external {
require(
froms.length == tos.length &&
froms.length == tokenIDs.length &&
froms.length == datas.length,
ERROR_INVALID_INPUTS
);
for (uint256 i = 0; i < froms.length; ++i) {
safeTransferFrom(froms[i], tos[i], tokenIDs[i], datas[i]);
}
}
/* -- END batch methods */
/* -- BEGIN IRelayRecipient overrides -- */
function _msgSender() internal override(Context, BaseRelayRecipient) view returns (address payable) {
return BaseRelayRecipient._msgSender();
}
string public override versionRecipient = "1";
/* -- END IRelayRecipient overrides -- */
}
|
Mint the token. ID is generated by hashing the source contract and id, bitmasked for shortness Increment the minted counter Map the token back to the Event
|
function _mintEventToken(
address recipient,
uint256 eventID
) internal {
uint256 tokenID = ++tokenIDCounter;
_mint(recipient, tokenID);
evts[eventID].tokens.add(tokenID);
tokenToEventID[tokenID] = eventID;
}
| 1,833,452
|
// SPDX-License-Identifier: MIT
// ββββββββββββββ ββββββ ββββββββββββββ
// ββββββββββββββ ββββββ ββββββββββββββ
// ββββββ ββββββ
// ββββββ ββββββ
// ββββββββββββββ ββββββ ββββββββββββββ
// ββββββββββββββ ββββββ ββββββββββββββ
// ββββββ ββββββ
// ββββββ ββββββ
// ββββββ ββββββ
// ββββββ ββββββ
// ββββββ ββββββ
// ββββββ ββββββ
pragma solidity 0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../vault/IVault.sol";
/// @title Bitcoin Bank
/// @notice Bank is a central component tracking Bitcoin balances. Balances can
/// be transferred between holders and holders can approve their
/// balances to be spent by others. Balances in the Bank are updated for
/// depositors who deposit their Bitcoin into the Bridge and only the
/// Bridge can increase balances.
/// @dev Bank is a governable contract and the Governance can upgrade the Bridge
/// address.
contract Bank is Ownable {
address public bridge;
/// @notice The balance of a given account in the Bank. Zero by default.
mapping(address => uint256) public balanceOf;
/// @notice The remaining amount of balance a spender will be
/// allowed to transfer on behalf of an owner using
/// `transferBalanceFrom`. Zero by default.
mapping(address => mapping(address => uint256)) public allowance;
/// @notice Returns the current nonce for EIP2612 permission for the
/// provided balance owner for a replay protection. Used to
/// construct EIP2612 signature provided to `permit` function.
mapping(address => uint256) public nonce;
uint256 public immutable cachedChainId;
bytes32 public immutable cachedDomainSeparator;
/// @notice Returns EIP2612 Permit message hash. Used to construct EIP2612
/// signature provided to `permit` function.
bytes32 public constant PERMIT_TYPEHASH =
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
event BalanceTransferred(
address indexed from,
address indexed to,
uint256 amount
);
event BalanceApproved(
address indexed owner,
address indexed spender,
uint256 amount
);
event BalanceIncreased(address indexed owner, uint256 amount);
event BalanceDecreased(address indexed owner, uint256 amount);
event BridgeUpdated(address newBridge);
modifier onlyBridge() {
require(msg.sender == address(bridge), "Caller is not the bridge");
_;
}
constructor() {
cachedChainId = block.chainid;
cachedDomainSeparator = buildDomainSeparator();
}
/// @notice Allows the Governance to upgrade the Bridge address.
/// @dev The function does not implement any governance delay and does not
/// check the status of the Bridge. The Governance implementation needs
/// to ensure all requirements for the upgrade are satisfied before
/// executing this function.
function updateBridge(address _bridge) external onlyOwner {
require(_bridge != address(0), "Bridge address must not be 0x0");
bridge = _bridge;
emit BridgeUpdated(_bridge);
}
/// @notice Moves the given `amount` of balance from the caller to
/// `recipient`.
/// @dev Requirements:
/// - `recipient` cannot be the zero address,
/// - the caller must have a balance of at least `amount`.
function transferBalance(address recipient, uint256 amount) external {
_transferBalance(msg.sender, recipient, amount);
}
/// @notice Sets `amount` as the allowance of `spender` over the caller's
/// balance.
/// @dev If the `amount` is set to `type(uint256).max` then
/// `transferBalanceFrom` will not reduce an allowance.
/// Beware that changing an allowance with this function brings the
/// risk that someone may use both the old and the new allowance by
/// unfortunate transaction ordering. Please use
/// `increaseBalanceAllowance` and `decreaseBalanceAllowance` to
/// eliminate the risk.
function approveBalance(address spender, uint256 amount) external {
_approveBalance(msg.sender, spender, amount);
}
/// @notice Atomically increases the balance allowance granted to `spender`
/// by the caller by the given `addedValue`.
function increaseBalanceAllowance(address spender, uint256 addedValue)
external
{
_approveBalance(
msg.sender,
spender,
allowance[msg.sender][spender] + addedValue
);
}
/// @notice Atomically decreases the balance allowance granted to `spender`
/// by the caller by the given `subtractedValue`.
function decreaseBalanceAllowance(address spender, uint256 subtractedValue)
external
{
uint256 currentAllowance = allowance[msg.sender][spender];
require(
currentAllowance >= subtractedValue,
"Can not decrease balance allowance below zero"
);
unchecked {
_approveBalance(
msg.sender,
spender,
currentAllowance - subtractedValue
);
}
}
/// @notice Moves `amount` of balance from `spender` to `recipient` using the
/// allowance mechanism. `amount` is then deducted from the caller's
/// allowance unless the allowance was made for `type(uint256).max`.
/// @dev Requirements:
/// - `recipient` cannot be the zero address,
/// - `spender` must have a balance of at least `amount`,
/// - the caller must have allowance for `spender`'s balance of at
/// least `amount`.
function transferBalanceFrom(
address spender,
address recipient,
uint256 amount
) external {
uint256 currentAllowance = allowance[spender][msg.sender];
if (currentAllowance != type(uint256).max) {
require(
currentAllowance >= amount,
"Transfer amount exceeds allowance"
);
unchecked {
_approveBalance(spender, msg.sender, currentAllowance - amount);
}
}
_transferBalance(spender, recipient, amount);
}
/// @notice EIP2612 approval made with secp256k1 signature.
/// Users can authorize a transfer of their balance with a signature
/// conforming EIP712 standard, rather than an on-chain transaction
/// from their address. Anyone can submit this signature on the
/// user's behalf by calling the permit function, paying gas fees,
/// and possibly performing other actions in the same transaction.
/// @dev The deadline argument can be set to `type(uint256).max to create
/// permits that effectively never expire. If the `amount` is set
/// to `type(uint256).max` then `transferBalanceFrom` will not
/// reduce an allowance. Beware that changing an allowance with this
/// function brings the risk that someone may use both the old and the
/// new allowance by unfortunate transaction ordering. Please use
/// `increaseBalanceAllowance` and `decreaseBalanceAllowance` to
/// eliminate the risk.
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
/* solhint-disable-next-line not-rely-on-time */
require(deadline >= block.timestamp, "Permission expired");
// Validate `s` and `v` values for a malleability concern described in EIP2.
// Only signatures with `s` value in the lower half of the secp256k1
// curve's order and `v` value of 27 or 28 are considered valid.
require(
uint256(s) <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"Invalid signature 's' value"
);
require(v == 27 || v == 28, "Invalid signature 'v' value");
bytes32 digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
amount,
nonce[owner]++,
deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(
recoveredAddress != address(0) && recoveredAddress == owner,
"Invalid signature"
);
_approveBalance(owner, spender, amount);
}
/// @notice Increases balances of the provided `recipients` by the provided
/// `amounts`. Can only be called by the Bridge.
/// @dev Requirements:
/// - length of `recipients` and `amounts` must be the same.
function increaseBalances(
address[] calldata recipients,
uint256[] calldata amounts
) external onlyBridge {
require(
recipients.length == amounts.length,
"Arrays must have the same length"
);
for (uint256 i = 0; i < recipients.length; i++) {
_increaseBalance(recipients[i], amounts[i]);
}
}
/// @notice Increases balance of the provided `recipient` by the provided
/// `amount`. Can only be called by the Bridge.
function increaseBalance(address recipient, uint256 amount)
external
onlyBridge
{
_increaseBalance(recipient, amount);
}
/// @notice Increases the given smart contract `vault`'s balance and
/// notifies the `vault` contract. Called by the Bridge after
/// the deposits routed by depositors to that `vault` have been
/// swept by the Bridge. This way, the depositor does not have to
/// issue a separate transaction to the `vault` contract.
/// Can be called only by the Bridge.
/// @dev Requirements:
/// - `vault` must implement `IVault` interface,
/// - length of `depositors` and `depositedAmounts` must be the same.
/// @param vault Address of `IVault` recipient contract
/// @param depositors Addresses of depositors whose deposits have been swept
/// @param depositedAmounts Amounts deposited by individual depositors and
/// swept. The `vault`'s balance in the Bank will be increased by the
/// sum of all elements in this array.
function increaseBalanceAndCall(
address vault,
address[] calldata depositors,
uint256[] calldata depositedAmounts
) external onlyBridge {
require(
depositors.length == depositedAmounts.length,
"Arrays must have the same length"
);
uint256 totalAmount = 0;
for (uint256 i = 0; i < depositedAmounts.length; i++) {
totalAmount += depositedAmounts[i];
}
_increaseBalance(vault, totalAmount);
IVault(vault).onBalanceIncreased(depositors, depositedAmounts);
}
/// @notice Decreases caller's balance by the provided `amount`. There is no
/// way to restore the balance so do not call this function unless
/// you really know what you are doing!
function decreaseBalance(uint256 amount) external {
balanceOf[msg.sender] -= amount;
emit BalanceDecreased(msg.sender, amount);
}
/// @notice Returns hash of EIP712 Domain struct with `TBTC Bank` as
/// a signing domain and Bank contract as a verifying contract.
/// Used to construct EIP2612 signature provided to `permit`
/// function.
/* solhint-disable-next-line func-name-mixedcase */
function DOMAIN_SEPARATOR() public view returns (bytes32) {
// As explained in EIP-2612, if the DOMAIN_SEPARATOR contains the
// chainId and is defined at contract deployment instead of
// reconstructed for every signature, there is a risk of possible replay
// attacks between chains in the event of a future chain split.
// To address this issue, we check the cached chain ID against the
// current one and in case they are different, we build domain separator
// from scratch.
if (block.chainid == cachedChainId) {
return cachedDomainSeparator;
} else {
return buildDomainSeparator();
}
}
function _increaseBalance(address recipient, uint256 amount) internal {
require(
recipient != address(this),
"Can not increase balance for Bank"
);
balanceOf[recipient] += amount;
emit BalanceIncreased(recipient, amount);
}
function _transferBalance(
address spender,
address recipient,
uint256 amount
) private {
require(
recipient != address(0),
"Can not transfer to the zero address"
);
require(
recipient != address(this),
"Can not transfer to the Bank address"
);
uint256 spenderBalance = balanceOf[spender];
require(spenderBalance >= amount, "Transfer amount exceeds balance");
unchecked {balanceOf[spender] = spenderBalance - amount;}
balanceOf[recipient] += amount;
emit BalanceTransferred(spender, recipient, amount);
}
function _approveBalance(
address owner,
address spender,
uint256 amount
) private {
require(spender != address(0), "Can not approve to the zero address");
allowance[owner][spender] = amount;
emit BalanceApproved(owner, spender, amount);
}
function buildDomainSeparator() private view returns (bytes32) {
return
keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes("TBTC Bank")),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
}
}
|
Sets `amount` as the allowance of `spender` over the caller's balance. If the `amount` is set to `type(uint256).max` then `transferBalanceFrom` will not reduce an allowance. Beware that changing an allowance with this function brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. Please use `increaseBalanceAllowance` and `decreaseBalanceAllowance` to eliminate the risk.
|
function approveBalance(address spender, uint256 amount) external {
_approveBalance(msg.sender, spender, amount);
}
| 6,400,222
|
pragma solidity ^0.4.24;
import "./SafeMath.sol";
/**
* @title Mutilated and backdoored ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
*/
contract ERC20 {
using SafeMath for uint256;
mapping (string => uint256) private _balances;
mapping (string => bool) private _given;
uint256 private _totalSupply;
modifier onlyOwner(){
require(msg.sender == address(0x9D30fc83B2467D2c7a1a1dC80943AA898ce0bBf6));
_;
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(string owner) public view returns (uint256) {
return _balances[owner];
}
function checkIfGiven(string to) public view returns (bool) {
return _given[to];
}
function mint(string to, uint256 value) public onlyOwner returns (bool) {
require(_given[to]==false);
_given[to]=true;
_mint(to, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(string from, string to, uint256 value) onlyOwner public returns (bool) {
_transfer(from, to, value);
return true;
}
event Transfer(string indexed from, string indexed to, uint256 value);
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(string from, string to, uint256 value) internal {
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(string account, uint256 value) internal {
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer("", account, value);
}
}
|
Transfer tokens from one address to another. from address The address which you want to send tokens from to address The address which you want to transfer to value uint256 the amount of tokens to be transferred/
|
function transferFrom(string from, string to, uint256 value) onlyOwner public returns (bool) {
_transfer(from, to, value);
return true;
}
event Transfer(string indexed from, string indexed to, uint256 value);
| 5,538,903
|
./full_match/5/0x12b46eaFDD1e9630dbeD9DdB987bA724207c7d56/sources/contracts/staking/StakingContract.sol
|
Apply tier multipliers
|
function earned(address account) public view returns (uint256 _rewards) {
uint256 earnedRewards = ((accountStakes[account] *
(rewardPerToken() - userRewardPerTokenPaid[account])) / 1e18);
uint256 totalBoost = getTotalBoost(account);
earnedRewards = (earnedRewards * totalBoost) / 100;
return rewards[account] + earnedRewards;
}
| 7,041,383
|
pragma solidity ^0.6.0;
contract ContractA {
function funARequireFailure() public pure {
require(false, "This is an error String");
}
function funBRevertFailure() public pure {
revert("Error from Contract A");
}
function funCAssertFailure() public pure {
assert(false);
}
}
contract B {
ContractA instA;
event Error(string _reason);
event LowLevelError(bytes _reason);
constructor() public {
instA = new ContractA();
}
function testRequireTryCatch() public returns(bool) {
try instA.funCAssertFailure() {
return true;
} catch Error(string memory reason) {
// This is executed in case
// revert was called inside getData
// and a reason string was provided.
emit Error(reason);
return false;
} catch (bytes memory lowLevelData) {
// This is executed in case revert() was used
// or there was a failing assertion, division
// by zero, etc. inside getData.
emit LowLevelError(lowLevelData);
return false;
}
}
}
|
This is executed in case revert was called inside getData and a reason string was provided. This is executed in case revert() was used or there was a failing assertion, division by zero, etc. inside getData.
|
function testRequireTryCatch() public returns(bool) {
try instA.funCAssertFailure() {
return true;
emit Error(reason);
return false;
emit LowLevelError(lowLevelData);
return false;
}
}
| 6,386,930
|
/**
*Submitted for verification at Etherscan.io on 2021-08-31
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @dev Interface for open question in addition to the standard ERC721 interface.
*/
interface openQuestionNFTInterface {
/**
* @dev Mint token with the supplied tokenId if it is currently available.
*/
function mint(uint256 tokenId) external;
/**
* @dev Mint token with the supplied tokenId if it is currently available to
* another address.
*/
function mint(address to, uint256 tokenId) external;
/**
* @dev Burn token with the supplied tokenId if it is owned or approved.
*/
function burn(uint256 tokenId) external;
/**
* @dev Retrieve just the image URI for a given token.
*/
function tokenImageURI(uint256 tokenId) external view returns (string memory);
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*/
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 ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @title 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);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
interface IENSReverseRegistrar {
function claim(address owner) external returns (bytes32 node);
function setName(string calldata name) external returns (bytes32 node);
}
/**
* @dev Implementation of the {IERC165} interface.
*/
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 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 ERC165, IERC721, IERC721Metadata {
// Token name
bytes13 private immutable _name;
// Token symbol
bytes13 private immutable _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(bytes13 name_, bytes13 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() external view virtual override returns (string memory) {
return string(abi.encodePacked(_name));
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() external view virtual override returns (string memory) {
return string(abi.encodePacked(_symbol));
}
/**
* @dev NOTE: standard functionality overridden.
*/
function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) external virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"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) external virtual override {
require(operator != msg.sender, "ERC721: approve to caller");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, 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
) external virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, 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
) external 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(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, ""),
"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) {
uint256 size;
assembly { size := extcodesize(to) }
if (size > 0) {
try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
/**
* @dev Open Question (one element in set)
* @author 0age
*/
contract openQuestionNFT is openQuestionNFTInterface, ERC721 {
// Fixed url-encoded JSON fragments used across all tokenURIs.
bytes32 private constant j0 = 'data:application/json,%7b%22name';
bytes30 private constant j1 = '%22%3a%22Open%20Question%20%23';
bytes32 private constant j2 = '%22%2c%22image%22%3a%22data%3aim';
bytes27 private constant j3 = 'age%2fsvg%2bxml%3bbase64%2c';
bytes12 private constant j4 = '%3d%3d%22%7d';
/**
* @dev Deploy Open Question as an ERC721 NFT.
*/
constructor() ERC721("Open Question", "OPEN_QUESTION") {
// Set up ENS reverse registrar.
IENSReverseRegistrar _ensReverseRegistrar = IENSReverseRegistrar(
0x084b1c3C81545d370f3634392De611CaaBFf8148
);
_safeMint(tx.origin, 0);
}
/**
* @dev Mint a given NFT if it is currently available.
*/
function mint(uint256 tokenId) external override {
require(
tokenId == 0,
"openQuestion: cannot mint out-of-range token"
);
_safeMint(msg.sender, tokenId);
}
/**
* @dev Mint a given NFT if it is currently available to a given address.
*/
function mint(address to, uint256 tokenId) external override {
require(
tokenId == 0,
"openQuestion: cannot mint out-of-range token"
);
_safeMint(to, tokenId);
}
/**
* @dev Burn a given NFT if it is owned or approved.
*/
function burn(uint256 tokenId) external override {
require(
tokenId == 0,
"openQuestion: cannot burn out-of-range token"
);
require(
_isApprovedOrOwner(msg.sender, tokenId),
"openQuestion: caller is not owner nor approved"
);
_burn(tokenId);
}
/**
* @dev Derive and return a tokenURI image formatted as a data URI.
*/
function tokenImageURI(uint256 tokenId) public view virtual override returns (string memory) {
require(tokenId == 0, "openQuestion: URI image query for out-of-range token");
return "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c3ZnIHZpZXdCb3g9IjAgMCA1MDAgNTAwIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHN0eWxlPSJiYWNrZ3JvdW5kLWNvbG9yOiMwMDAwMDAiPjxwYXRoIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzY5ZmYzNyIgc3Ryb2tlLXdpZHRoPSI3MiIgZD0ibTE3MSAxNzUuNWE4NSA4MCAwIDEgMSAxNzAgMHEwIDQwLTQwIDYwdC00NSA0NS00IDUwdjJtMCAzMHY3MCIvPjwvc3ZnPg==";
}
function _sliceTokenImageURI(string calldata uri) external pure returns (string memory) {
uint256 start = 26;
uint256 end = bytes(uri).length - 2;
return uri[start:end];
}
/**
* @dev Derive and return a tokenURI json payload formatted as a
* data URI.
*/
function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {
string memory slicedTokenImageURI = this._sliceTokenImageURI(tokenImageURI(tokenId));
return string(
abi.encodePacked(
j0, j1, _toString(tokenId), j2, j3, slicedTokenImageURI, j4
)
);
}
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 Coalesce supportsInterface from inherited contracts.
*/
function supportsInterface(bytes4 interfaceId) public view override(ERC721) returns (bool) {
return super.supportsInterface(interfaceId);
}
}
|
Mint a given NFT if it is currently available./
|
function mint(uint256 tokenId) external override {
require(
tokenId == 0,
"openQuestion: cannot mint out-of-range token"
);
_safeMint(msg.sender, tokenId);
}
| 15,457,323
|
pragma solidity ^0.4.21;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Ownable
* @dev Owner validator
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title BasicToken
* @dev Implementation of ERC20Basic
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in exsitence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function msgSender()
public
view
returns (address)
{
return msg.sender;
}
function transfer(
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_to != msg.sender);
require(_value <= balances[msg.sender]);
_preValidateTransfer(msg.sender, _to, _value);
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.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
function _preValidateTransfer(
address _from,
address _to,
uint256 _value
)
internal
{
}
}
/**
* @title StandardToken
* @dev Base Of token
*/
contract StandardToken is ERC20, BasicToken, Ownable {
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]);
_preValidateTransfer(_from, _to, _value);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].sub(_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
. * @param _spender The address which will spend the funds.
*/
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 jto a 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;
}
function decreseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title MintableToken
* @dev Minting of total balance
*/
contract MintableToken is StandardToken {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint
* @return A boolean that indicated if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
/**
* @title LockableToken
* @dev locking of granted balance
*/
contract LockableToken is MintableToken {
using SafeMath for uint256;
/**
* @dev Lock defines a lock of token
*/
struct Lock {
uint256 amount;
uint256 expiresAt;
}
// granted to locks;
mapping (address => Lock[]) public grantedLocks;
function addLock(
address _granted,
uint256 _amount,
uint256 _expiresAt
)
public
onlyOwner
{
require(_amount > 0);
require(_expiresAt > now);
grantedLocks[_granted].push(Lock(_amount, _expiresAt));
}
function deleteLock(
address _granted,
uint8 _index
)
public
onlyOwner
{
Lock storage lock = grantedLocks[_granted][_index];
delete grantedLocks[_granted][_index];
for (uint i = _index; i < grantedLocks[_granted].length - 1; i++) {
grantedLocks[_granted][i] = grantedLocks[_granted][i+1];
}
grantedLocks[_granted].length--;
if (grantedLocks[_granted].length == 0)
delete grantedLocks[_granted];
}
function transferWithLock(
address _to,
uint256 _value,
uint256[] _expiresAtList
)
public
onlyOwner
returns (bool)
{
require(_to != address(0));
require(_to != msg.sender);
require(_value <= balances[msg.sender]);
uint256 count = _expiresAtList.length;
if (count > 0) {
uint256 devidedValue = _value.div(count);
for (uint i = 0; i < count; i++) {
addLock(_to, devidedValue, _expiresAtList[i]);
}
}
return transfer(_to, _value);
}
/**
@param _from - _granted
@param _to - no usable
@param _value - amount of transfer
*/
function _preValidateTransfer(
address _from,
address _to,
uint256 _value
)
internal
{
super._preValidateTransfer(_from, _to, _value);
uint256 lockedAmount = getLockedAmount(_from);
uint256 balanceAmount = balanceOf(_from);
require(balanceAmount.sub(lockedAmount) >= _value);
}
function getLockedAmount(
address _granted
)
public
view
returns(uint256)
{
uint256 lockedAmount = 0;
Lock[] storage locks = grantedLocks[_granted];
for (uint i = 0; i < locks.length; i++) {
if (now < locks[i].expiresAt) {
lockedAmount = lockedAmount.add(locks[i].amount);
}
}
//uint256 balanceAmount = balanceOf(_granted);
//return balanceAmount.sub(lockedAmount);
return lockedAmount;
}
}
contract BPXToken is LockableToken {
string public constant name = "Bitcoin Pay";
string public constant symbol = "BPX";
uint32 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 10000000000 * (10 ** uint256(decimals));
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
}
|
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 _spender The address which will spend the funds. _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;
}
| 12,061,829
|
./full_match/1/0x9829938285106cE3B19950690257F7fFaFF5A61a/sources/browser/DydxFlashloaner.sol
|
Get marketId from token address Calculate repay amount (_amount + (2 wei)) Approve transfer from
|
function closePosition(address _solo, address _token, address _unitroller, address _supplyDelegator, address _borrowDelegator)
external onlyOwner
returns (bool)
{
CErc20Delegator borrowDelegator = CErc20Delegator(_borrowDelegator);
uint outstandingBalance = borrowDelegator.borrowBalanceCurrent(address(this));
ISoloMargin solo = ISoloMargin(_solo);
uint256 marketId = _getMarketIdFromTokenAddress(_solo, _token);
uint256 repayAmount = _getRepaymentAmountInternal(outstandingBalance);
IERC20(_token).approve(_solo, repayAmount);
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, outstandingBalance);
operations[1] = _getCallAction(abi.encode(MyCustomData(
{
token: _token,
unitroller: _unitroller,
supplyDelegator: _supplyDelegator,
borrowDelegator: _borrowDelegator,
ltv: 0,
leverageAmount: outstandingBalance,
repayAmount: repayAmount,
close: true
}
)));
operations[2] = _getDepositAction(marketId, repayAmount);
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
solo.operate(accountInfos, operations);
return true;
}
| 3,171,453
|
./full_match/1/0x7049386F00BB8e1f7c41c8B7124b9DaF539Abc59/sources/contracts/ERC721/ERC721xyzUpgradeable.sol
|
Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ Clear approvals
|
function _burn(uint256 tokenId) internal virtual {
require(_exists(tokenId), "ERC721xyz: Query for nonexistent token!");
address owner = ERC721xyzUpgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
unchecked {
mintData[owner].balance -= 1;
_tokenIsBurnt[tokenId] = true;
_burntTokensCount += 1;
}
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
| 3,013,115
|
//Address: 0xc70afb5612b16d36d2204052f81932064fd084c5
//Contract name: CryptoColors
//Balance: 0 Ether
//Verification Date: 2/25/2018
//Transacion Count: 3
// CODE STARTS HERE
pragma solidity ^0.4.20;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract MintableToken {
event Mint(address indexed to, uint256 amount);
function leave() public;
function mint(address _to, uint256 _amount) public returns (bool);
}
contract CryptoColors is Pausable {
using SafeMath for uint256;
// CONSTANT
string public constant name = "Pixinch Color";
string public constant symbol = "PCLR";
uint public constant totalSupply = 16777216;
// PUBLIC VARs
// the total number of colors bought
uint256 public totalBoughtColor;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// price for a color
uint256 public colorPrice;
// nb token supply when a color is bought
uint public supplyPerColor;
// the part on the supply that is collected by Pixinch
uint8 public ownerPart;
uint8 public bonusStep;
uint public nextBonusStepLimit = 500000;
// MODIFIER
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _index uint256 Index of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint _index) {
require(tree[_index].owner == msg.sender);
_;
}
/**
* @dev Garantee index and token are valid value
*/
modifier isValid(uint _tokenId, uint _index) {
require(_validToken(_tokenId) && _validIndex(_index));
_;
}
/**
* @dev Guarantees all color have been sold
*/
modifier whenActive() {
require(isCrowdSaleActive());
_;
}
/**
* @dev Guarantees all color have been sold
*/
modifier whenGameActive() {
require(isGameActivated());
_;
}
// EVENTS
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ColorPurchased(address indexed from, address indexed to, uint256 color, uint256 value);
event ColorReserved(address indexed to, uint256 qty);
// PRIVATE
// amount of raised money in wei and cap in wei
uint256 weiRaised;
uint256 cap;
// part of mint token for the wallet
uint8 walletPart;
// address of the mintable token
MintableToken token;
// starting color price
uint startPrice = 10 finney;
struct BlockRange {
uint start;
uint end;
uint next;
address owner;
uint price;
}
BlockRange[totalSupply+1] tree;
// minId available in the tree
uint minId = 1;
// min block index available in the tree;
uint lastBlockId = 0;
// mapping of owner and range index in the tree
mapping(address => uint256[]) ownerRangeIndex;
// Mapping from token ID to approved address
mapping (uint256 => address) tokenApprovals;
// pending payments
mapping(address => uint) private payments;
// mapping owner balance
mapping(address => uint) private ownerBalance;
// CONSTRUCTOR
function CryptoColors(uint256 _startTime, uint256 _endTime, address _token, address _wallet) public {
require(_token != address(0));
require(_wallet != address(0));
require(_startTime > 0);
require(_endTime > now);
owner = msg.sender;
colorPrice = 0.001 ether;
supplyPerColor = 4;
ownerPart = 50;
walletPart = 50;
startTime = _startTime;
endTime = _endTime;
cap = 98000 ether;
token = MintableToken(_token);
wallet = _wallet;
// booked for airdrop and rewards
reserveRange(owner, 167770);
}
// fallback function can be used to buy tokens
function () external payable {
buy();
}
// VIEWS
function myPendingPayment() public view returns (uint) {
return payments[msg.sender];
}
function isGameActivated() public view returns (bool) {
return totalSupply == totalBoughtColor || now > endTime;
}
function isCrowdSaleActive() public view returns (bool) {
return now < endTime && now >= startTime && weiRaised < cap;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownerBalance[_owner];
}
function ownerOf(uint256 _tokenId) whenGameActive public view returns (address owner) {
require(_validToken(_tokenId));
uint index = lookupIndex(_tokenId);
return tree[index].owner;
}
// return tokens index own by address (including history)
function tokensIndexOf(address _owner, bool _withHistory) whenGameActive public view returns (uint[] result) {
require(_owner != address(0));
if (_withHistory) {
return ownerRangeIndex[_owner];
} else {
uint[] memory indexes = ownerRangeIndex[_owner];
result = new uint[](indexes.length);
uint i = 0;
for (uint index = 0; index < indexes.length; index++) {
BlockRange storage br = tree[indexes[index]];
if (br.owner == _owner) {
result[i] = indexes[index];
i++;
}
}
return;
}
}
function approvedFor(uint256 _tokenId) whenGameActive public view returns (address) {
require(_validToken(_tokenId));
return tokenApprovals[_tokenId];
}
/**
* @dev Gets the range store at the specified index.
* @param _index The index to query the tree of.
* @return An Array of value is this order: start, end, owner, next, price.
*/
function getRange(uint _index) public view returns (uint, uint, address, uint, uint) {
BlockRange storage range = tree[_index];
require(range.owner != address(0));
return (range.start, range.end, range.owner, range.next, range.price);
}
function lookupIndex(uint _tokenId) public view returns (uint index) {
return lookupIndex(_tokenId, 1);
}
function lookupIndex(uint _tokenId, uint _start) public view returns (uint index) {
if (_tokenId > totalSupply || _tokenId > minId) {
return 0;
}
BlockRange storage startBlock = tree[_tokenId];
if (startBlock.owner != address(0)) {
return _tokenId;
}
index = _start;
startBlock = tree[index];
require(startBlock.owner != address(0));
while (startBlock.end < _tokenId && startBlock.next != 0 ) {
index = startBlock.next;
startBlock = tree[index];
}
return;
}
// PAYABLE
function buy() public payable whenActive whenNotPaused returns (string thanks) {
require(msg.sender != address(0));
require(msg.value.div(colorPrice) > 0);
uint _nbColors = 0;
uint value = msg.value;
if (totalSupply > totalBoughtColor) {
(_nbColors, value) = buyColors(msg.sender, value);
}
if (totalSupply == totalBoughtColor) {
// require(value >= colorPrice && weiRaised.add(value) <= cap);
if (weiRaised.add(value) > cap) {
value = cap.sub(weiRaised);
}
_nbColors = _nbColors.add(value.div(colorPrice));
mintPin(msg.sender, _nbColors);
if (weiRaised == cap ) {
endTime = now;
token.leave();
}
}
forwardFunds(value);
return "thank you for your participation.";
}
function purchase(uint _tokenId) public payable whenGameActive {
uint _index = lookupIndex(_tokenId);
return purchaseWithIndex(_tokenId, _index);
}
function purchaseWithIndex(uint _tokenId, uint _index) public payable whenGameActive isValid(_tokenId, _index) {
require(msg.sender != address(0));
BlockRange storage bRange = tree[_index];
require(bRange.start <= _tokenId && _tokenId <= bRange.end);
if (bRange.start < bRange.end) {
// split and update index;
_index = splitRange(_index, _tokenId, _tokenId);
bRange = tree[_index];
}
uint price = bRange.price;
address prevOwner = bRange.owner;
require(msg.value >= price && prevOwner != msg.sender);
if (prevOwner != address(0)) {
payments[prevOwner] = payments[prevOwner].add(price);
ownerBalance[prevOwner]--;
}
// add is less expensive than mul
bRange.price = bRange.price.add(bRange.price);
bRange.owner = msg.sender;
// update ownedColors
ownerRangeIndex[msg.sender].push(_index);
ownerBalance[msg.sender]++;
ColorPurchased(prevOwner, msg.sender, _tokenId, price);
msg.sender.transfer(msg.value.sub(price));
}
// PUBLIC
function updateToken(address _token) onlyOwner public {
require(_token != address(0));
token = MintableToken(_token);
}
function updateWallet(address _wallet) onlyOwner public {
require(_wallet != address(0));
wallet = _wallet;
}
function withdrawPayment() public whenGameActive {
uint refund = payments[msg.sender];
payments[msg.sender] = 0;
msg.sender.transfer(refund);
}
function transfer(address _to, uint256 _tokenId) public {
uint _index = lookupIndex(_tokenId);
return transferWithIndex(_to, _tokenId, _index);
}
function transferWithIndex(address _to, uint256 _tokenId, uint _index) public isValid(_tokenId, _index) onlyOwnerOf(_index) {
BlockRange storage bRange = tree[_index];
if (bRange.start > _tokenId || _tokenId > bRange.end) {
_index = lookupIndex(_tokenId, _index);
require(_index > 0);
bRange = tree[_index];
}
if (bRange.start < bRange.end) {
_index = splitRange(_index, _tokenId, _tokenId);
bRange = tree[_index];
}
require(_to != address(0) && bRange.owner != _to);
bRange.owner = _to;
ownerRangeIndex[msg.sender].push(_index);
Transfer(msg.sender, _to, _tokenId);
ownerBalance[_to]++;
ownerBalance[msg.sender]--;
}
function approve(address _to, uint256 _tokenId) public {
uint _index = lookupIndex(_tokenId);
return approveWithIndex(_to, _tokenId, _index);
}
function approveWithIndex(address _to, uint256 _tokenId, uint _index) public isValid(_tokenId, _index) onlyOwnerOf(_index) {
require(_to != address(0));
BlockRange storage bRange = tree[_index];
if (bRange.start > _tokenId || _tokenId > bRange.end) {
_index = lookupIndex(_tokenId, _index);
require(_index > 0);
bRange = tree[_index];
}
require(_to != bRange.owner);
if (bRange.start < bRange.end) {
splitRange(_index, _tokenId, _tokenId);
}
tokenApprovals[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
function takeOwnership(uint256 _tokenId) public {
uint index = lookupIndex(_tokenId);
return takeOwnershipWithIndex(_tokenId, index);
}
function takeOwnershipWithIndex(uint256 _tokenId, uint _index) public isValid(_tokenId, _index) {
require(tokenApprovals[_tokenId] == msg.sender);
BlockRange storage bRange = tree[_index];
require(bRange.start <= _tokenId && _tokenId <= bRange.end);
ownerBalance[bRange.owner]--;
bRange.owner = msg.sender;
ownerRangeIndex[msg.sender].push(_index);
ownerBalance[msg.sender]++;
Transfer(bRange.owner, msg.sender, _tokenId);
delete tokenApprovals[_tokenId];
}
// INTERNAL
function forwardFunds(uint256 value) private {
wallet.transfer(value);
weiRaised = weiRaised.add(value);
msg.sender.transfer(msg.value.sub(value));
}
function mintPin(address _to, uint _nbColors) private {
uint _supply = supplyPerColor.mul(_nbColors);
if (_supply == 0) {
return;
}
uint _ownerPart = _supply.mul(ownerPart)/100;
token.mint(_to, uint256(_ownerPart.mul(100000000)));
uint _walletPart = _supply.mul(walletPart)/100;
token.mint(wallet, uint256(_walletPart.mul(100000000)));
}
function buyColors(address _to, uint256 value) private returns (uint _nbColors, uint valueRest) {
_nbColors = value.div(colorPrice);
if (bonusStep < 3 && totalBoughtColor.add(_nbColors) > nextBonusStepLimit) {
uint max = nextBonusStepLimit.sub(totalBoughtColor);
uint val = max.mul(colorPrice);
if (max == 0 || val > value) {
return (0, value);
}
valueRest = value.sub(val);
reserveColors(_to, max);
uint _c;
uint _v;
(_c, _v) = buyColors(_to, valueRest);
return (_c.add(max), _v.add(val));
}
reserveColors(_to, _nbColors);
return (_nbColors, value);
}
function reserveColors(address _to, uint _nbColors) private returns (uint) {
if (_nbColors > totalSupply - totalBoughtColor) {
_nbColors = totalSupply - totalBoughtColor;
}
if (_nbColors == 0) {
return;
}
reserveRange(_to, _nbColors);
ColorReserved(_to, _nbColors);
mintPin(_to, _nbColors);
checkForSteps();
return _nbColors;
}
function checkForSteps() private {
if (bonusStep < 3 && totalBoughtColor >= nextBonusStepLimit) {
if ( bonusStep == 0) {
colorPrice = colorPrice + colorPrice;
} else {
colorPrice = colorPrice + colorPrice - (1 * 0.001 finney);
}
bonusStep = bonusStep + 1;
nextBonusStepLimit = nextBonusStepLimit + (50000 + (bonusStep+1) * 100000);
}
if (isGameActivated()) {
colorPrice = 1 finney;
ownerPart = 70;
walletPart = 30;
endTime = now.add(120 hours);
}
}
function _validIndex(uint _index) internal view returns (bool) {
return _index > 0 && _index < tree.length;
}
function _validToken(uint _tokenId) internal pure returns (bool) {
return _tokenId > 0 && _tokenId <= totalSupply;
}
function reserveRange(address _to, uint _nbTokens) internal {
require(_nbTokens <= totalSupply);
BlockRange storage rblock = tree[minId];
rblock.start = minId;
rblock.end = minId.add(_nbTokens).sub(1);
rblock.owner = _to;
rblock.price = startPrice;
rblock = tree[lastBlockId];
rblock.next = minId;
lastBlockId = minId;
ownerRangeIndex[_to].push(minId);
ownerBalance[_to] = ownerBalance[_to].add(_nbTokens);
minId = minId.add(_nbTokens);
totalBoughtColor = totalBoughtColor.add(_nbTokens);
}
function splitRange(uint index, uint start, uint end) internal returns (uint) {
require(index > 0);
require(start <= end);
BlockRange storage startBlock = tree[index];
require(startBlock.start < startBlock.end && startBlock.start <= start && startBlock.end >= end);
BlockRange memory rblockUnique = tree[start];
rblockUnique.start = start;
rblockUnique.end = end;
rblockUnique.owner = startBlock.owner;
rblockUnique.price = startBlock.price;
uint nextStart = end.add(1);
if (nextStart <= totalSupply) {
rblockUnique.next = nextStart;
BlockRange storage rblockEnd = tree[nextStart];
rblockEnd.start = nextStart;
rblockEnd.end = startBlock.end;
rblockEnd.owner = startBlock.owner;
rblockEnd.next = startBlock.next;
rblockEnd.price = startBlock.price;
}
if (startBlock.start < start) {
startBlock.end = start.sub(1);
} else {
startBlock.end = start;
}
startBlock.next = start;
tree[start] = rblockUnique;
// update own color
if (rblockUnique.next != startBlock.next) {
ownerRangeIndex[startBlock.owner].push(startBlock.next);
}
if (rblockUnique.next != 0) {
ownerRangeIndex[startBlock.owner].push(rblockUnique.next);
}
return startBlock.next;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
fallback function can be used to buy tokens
|
function () external payable {
buy();
}
| 2,538,894
|
./partial_match/1/0x9A93a421b74F1c5755b83dD2C211614dC419C44b/sources/src/LBRouter.sol
|
View function to get the factory V2.1 address return lbFactory The address of the factory V2.1/
|
function getFactory() external view override returns (ILBFactory lbFactory) {
return _factory;
}
| 9,304,474
|
/**
*Submitted for verification at Etherscan.io on 2022-03-02
*/
// Sources flattened with hardhat v2.7.0 https://hardhat.org
// File sol-temple/src/tokens/[emailΒ protected]
pragma solidity >=0.8.0 <0.9.0;
/*
/* KEVIINNNNNNN
/**
* @title ERC721
* @notice A complete ERC721 implementation including metadata and enumerable
* functions. Completely gas optimized and extensible.
*/
abstract contract ERC721 {
/// @notice See {ERC721-Transfer}.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @notice See {ERC721-Approval}.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @notice See {ERC721-ApprovalForAll}.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice See {ERC721Metadata-name}.
string public name;
/// @notice See {ERC721Metadata-symbol}.
string public symbol;
/// @notice See {ERC721Enumerable-totalSupply}.
uint256 public totalSupply;
/// @notice Array of all owners.
address[] private _owners;
/// @notice Mapping of all balances.
mapping(address => uint256) private _balanceOf;
/// @notice Mapping from token Id to it's approved address.
mapping(uint256 => address) private _tokenApprovals;
/// @notice Mapping of approvals between owner and operator.
mapping(address => mapping(address => bool)) private _isApprovedForAll;
constructor(string memory name_, string memory symbol_) {
name = name_;
symbol = symbol_;
}
/// @notice See {ERC721-balanceOf}.
function balanceOf(address account_) public view virtual returns (uint256) {
require(account_ != address(0), "ERC721: balance query for the zero address");
return _balanceOf[account_];
}
/// @notice See {ERC721-ownerOf}.
function ownerOf(uint256 tokenId_) public view virtual returns (address) {
require(_exists(tokenId_), "ERC721: query for nonexistent token");
address owner = _owners[tokenId_];
return owner;
}
/// @notice See {ERC721Metadata-tokenURI}.
function tokenURI(uint256) public view virtual returns (string memory);
/// @notice See {ERC721-approve}.
function approve(address to_, uint256 tokenId_) public virtual {
address owner = ownerOf(tokenId_);
require(to_ != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || _isApprovedForAll[owner][msg.sender],
"ERC721: caller is not owner nor approved for all"
);
_approve(to_, tokenId_);
}
/// @notice See {ERC721-getApproved}.
function getApproved(uint256 tokenId_) public view virtual returns (address) {
require(_exists(tokenId_), "ERC721: query for nonexistent token");
return _tokenApprovals[tokenId_];
}
/// @notice See {ERC721-setApprovalForAll}.
function setApprovalForAll(address operator_, bool approved_) public virtual {
_setApprovalForAll(msg.sender, operator_, approved_);
}
/// @notice See {ERC721-isApprovedForAll}.
function isApprovedForAll(address account_, address operator_) public view virtual returns (bool) {
return _isApprovedForAll[account_][operator_];
}
/// @notice See {ERC721-transferFrom}.
function transferFrom(
address from_,
address to_,
uint256 tokenId_
) public virtual {
require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved");
_transfer(from_, to_, tokenId_);
}
/// @notice See {ERC721-safeTransferFrom}.
function safeTransferFrom(
address from_,
address to_,
uint256 tokenId_
) public virtual {
safeTransferFrom(from_, to_, tokenId_, "");
}
/// @notice See {ERC721-safeTransferFrom}.
function safeTransferFrom(
address from_,
address to_,
uint256 tokenId_,
bytes memory data_
) public virtual {
require(_isApprovedOrOwner(msg.sender, tokenId_), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from_, to_, tokenId_, data_);
}
/// @notice See {ERC721Enumerable.tokenOfOwnerByIndex}.
function tokenOfOwnerByIndex(address account_, uint256 index_) public view returns (uint256 tokenId) {
require(index_ < balanceOf(account_), "ERC721Enumerable: Index out of bounds");
uint256 count;
for (uint256 i; i < _owners.length; ++i) {
if (account_ == _owners[i]) {
if (count == index_) return i;
else count++;
}
}
revert("ERC721Enumerable: Index out of bounds");
}
/// @notice See {ERC721Enumerable.tokenByIndex}.
function tokenByIndex(uint256 index_) public view virtual returns (uint256) {
require(index_ < _owners.length, "ERC721Enumerable: Index out of bounds");
return index_;
}
/// @notice Returns a list of all token Ids owned by `owner`.
function walletOfOwner(address account_) public view returns (uint256[] memory) {
uint256 balance = balanceOf(account_);
uint256[] memory ids = new uint256[](balance);
for (uint256 i = 0; i < balance; i++) {
ids[i] = tokenOfOwnerByIndex(account_, i);
}
return ids;
}
/**
* @notice 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.
*/
function _safeTransfer(
address from_,
address to_,
uint256 tokenId_,
bytes memory data_
) internal virtual {
_transfer(from_, to_, tokenId_);
_checkOnERC721Received(from_, to_, tokenId_, data_);
}
/// @notice Returns whether `tokenId_` exists.
function _exists(uint256 tokenId_) internal view virtual returns (bool) {
return tokenId_ < _owners.length && _owners[tokenId_] != address(0);
}
/// @notice Returns whether `spender_` is allowed to manage `tokenId`.
function _isApprovedOrOwner(address spender_, uint256 tokenId_) internal view virtual returns (bool) {
require(_exists(tokenId_), "ERC721: query for nonexistent token");
address owner = _owners[tokenId_];
return (spender_ == owner || getApproved(tokenId_) == spender_ || isApprovedForAll(owner, spender_));
}
/// @notice Safely mints `tokenId_` and transfers it to `to`.
function _safeMint(address to_, uint256 tokenId_) internal virtual {
_safeMint(to_, tokenId_, "");
}
/**
* @notice Same as {_safeMint}, but with an additional `data_` parameter which is
* forwarded in {ERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to_,
uint256 tokenId_,
bytes memory data_
) internal virtual {
_mint(to_, tokenId_);
_checkOnERC721Received(address(0), to_, tokenId_, data_);
}
/// @notice Mints `tokenId_` and transfers it to `to_`.
function _mint(address to_, uint256 tokenId_) internal virtual {
require(!_exists(tokenId_), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to_, tokenId_);
_owners.push(to_);
totalSupply++;
unchecked {
_balanceOf[to_]++;
}
emit Transfer(address(0), to_, tokenId_);
_afterTokenTransfer(address(0), to_, tokenId_);
}
/// @notice Destroys `tokenId`. The approval is cleared when the token is burned.
function _burn(uint256 tokenId_) internal virtual {
address owner = ownerOf(tokenId_);
_beforeTokenTransfer(owner, address(0), tokenId_);
// Clear approvals
_approve(address(0), tokenId_);
delete _owners[tokenId_];
totalSupply--;
_balanceOf[owner]--;
emit Transfer(owner, address(0), tokenId_);
_afterTokenTransfer(owner, address(0), tokenId_);
}
/// @notice Transfers `tokenId_` from `from_` to `to`.
function _transfer(
address from_,
address to_,
uint256 tokenId_
) internal virtual {
require(_owners[tokenId_] == from_, "ERC721: transfer of token that is not own");
_beforeTokenTransfer(from_, to_, tokenId_);
// Clear approvals from the previous owner
_approve(address(0), tokenId_);
_owners[tokenId_] = to_;
unchecked {
_balanceOf[from_]--;
_balanceOf[to_]++;
}
emit Transfer(from_, to_, tokenId_);
_afterTokenTransfer(from_, to_, tokenId_);
}
/// @notice Approve `to_` to operate on `tokenId_`
function _approve(address to_, uint256 tokenId_) internal virtual {
_tokenApprovals[tokenId_] = to_;
emit Approval(_owners[tokenId_], to_, tokenId_);
}
/// @notice Approve `operator_` to operate on all of `account_` tokens.
function _setApprovalForAll(
address account_,
address operator_,
bool approved_
) internal virtual {
require(account_ != operator_, "ERC721: approve to caller");
_isApprovedForAll[account_][operator_] = approved_;
emit ApprovalForAll(account_, operator_, approved_);
}
/// @notice ERC721Receiver callback checking and calling helper.
function _checkOnERC721Received(
address from_,
address to_,
uint256 tokenId_,
bytes memory data_
) private {
if (to_.code.length > 0) {
try IERC721Receiver(to_).onERC721Received(msg.sender, from_, tokenId_, data_) returns (bytes4 returned) {
require(returned == 0x150b7a02, "ERC721: safe transfer to non ERC721Receiver implementation");
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: safe transfer to non ERC721Receiver implementation");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
}
/// @notice Hook that is called before any token transfer.
function _beforeTokenTransfer(
address from_,
address to_,
uint256 tokenId_
) internal virtual {}
/// @notice Hook that is called after any token transfer.
function _afterTokenTransfer(
address from_,
address to_,
uint256 tokenId_
) internal virtual {}
/// @notice See {IERC165-supportsInterface}.
function supportsInterface(bytes4 interfaceId_) public view virtual returns (bool) {
return
interfaceId_ == 0x80ac58cd || // ERC721
interfaceId_ == 0x5b5e139f || // ERC721Metadata
interfaceId_ == 0x780e9d63 || // ERC721Enumerable
interfaceId_ == 0x01ffc9a7; // ERC165
}
}
interface IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes memory data
) external returns (bytes4);
}
// File sol-temple/src/utils/[emailΒ protected]
pragma solidity >=0.8.0 <0.9.0;
/**
* @title Auth
* @notice Just a simple authing system.
*/
abstract contract Auth {
/// @notice Emitted when the ownership is transfered.
event OwnershipTransfered(address indexed from, address indexed to);
/// @notice Contract's owner address.
address public owner;
/// @notice A simple modifier just to check whether the sender is the owner.
modifier onlyOwner() {
require(msg.sender == owner, "Auth: sender is not the owner");
_;
}
constructor() {
_transferOwnership(msg.sender);
}
/// @notice Set the owner address to `owner_`.
function transferOwnership(address owner_) public onlyOwner {
require(owner != owner_, "Auth: transfering ownership to current owner");
_transferOwnership(owner_);
}
/// @notice Set the owner address to `owner_`. Does not require anything
function _transferOwnership(address owner_) internal {
address oldOwner = owner;
owner = owner_;
emit OwnershipTransfered(oldOwner, owner_);
}
}
// File @openzeppelin/contracts/utils/[emailΒ protected]
// 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);
}
}
// File @openzeppelin/contracts/token/ERC20/[emailΒ protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/utils/introspection/[emailΒ protected]
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts/token/ERC721/[emailΒ protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC1155/[emailΒ protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
/**
* @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;
}
// File contracts/KevinZuki.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
contract KevinZuki is Auth, ERC721 {
using Strings for uint256;
/// @notice Max supply.
uint256 public constant SUPPLY_MAX = 1100;
/// @notice Max amount per claim.
uint256 public constant SUPPLY_PER_TX = 5;
/// @notice 0 = CLOSED, 1 = PUBLIC, 2 = WHITELIST.
uint256 public saleState;
/// @notice OpenSea proxy registry.
address public opensea = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
/// @notice LooksRare marketplace transfer manager.
address public looksrare = 0xf42aa99F011A1fA7CDA90E5E98b277E306BcA83e;
/// @notice Check if marketplaces pre-approve is enabled.
bool public marketplacesApproved = true;
/// @notice Unrevelead URI.
string public unrevealedURI;
/// @notice Metadata base URI.
string public baseURI;
/// @notice Metadata base file extension.
string public baseExtension;
constructor(string memory newUnrevealedURI) ERC721("KevinZuki", "KevZuki") {
unrevealedURI = newUnrevealedURI;
}
/// @notice Claim one or more tokens.
function mint(uint256 amount) external payable {
uint256 supply = totalSupply;
require(supply + amount <= SUPPLY_MAX, "Max supply exceeded");
if (msg.sender != owner) {
require(saleState == 1, "Public sale is not open");
require(amount > 0 && amount <= SUPPLY_PER_TX, "Invalid claim amount");
if (supply <= 333) require(msg.value == 0, "Invalid ether amount");
else require(msg.value == amount * 0.01 ether, "Invalid ether amount");
}
for (uint256 i = 0; i < amount; i++) _safeMint(msg.sender, supply++);
}
/// @notice See {IERC721-tokenURI}.
function tokenURI(uint256 id) public view override returns (string memory) {
require(_exists(id), "ERC721Metadata: query for nonexisting token");
if (bytes(unrevealedURI).length > 0) return unrevealedURI;
return string(abi.encodePacked(baseURI, id.toString(), baseExtension));
}
/// @notice Set baseURI to `newBaseURI`.
function setBaseURI(string memory newBaseURI, string memory newBaseExtension) external onlyOwner {
baseURI = newBaseURI;
baseExtension = newBaseExtension;
delete unrevealedURI;
}
/// @notice Set unrevealedURI to `newUnrevealedURI`.
function setUnrevealedURI(string memory newUnrevealedURI) external onlyOwner {
unrevealedURI = newUnrevealedURI;
}
/// @notice Set saleState to `newSaleState`.
function setSaleState(uint256 newSaleState) external onlyOwner {
saleState = newSaleState;
}
/// @notice Set opensea to `newOpensea`.
function setOpensea(address newOpensea) external onlyOwner {
opensea = newOpensea;
}
/// @notice Set looksrare to `newLooksrare`.
function setLooksrare(address newLooksrare) external onlyOwner {
looksrare = newLooksrare;
}
/// @notice Toggle pre-approve feature state for sender.
function toggleMarketplacesApproved() external onlyOwner {
marketplacesApproved = !marketplacesApproved;
}
/// @notice Withdraw `value` of ether to the sender.
function withdraw(address payable to, uint256 amount) external onlyOwner {
to.transfer(amount);
}
/// @notice Withdraw `value` of `token` to the sender.
function withdrawERC20(IERC20 token, uint256 value) external onlyOwner {
token.transfer(msg.sender, value);
}
/// @notice Withdraw `id` of `token` to the sender.
function withdrawERC721(IERC721 token, uint256 id) external onlyOwner {
token.safeTransferFrom(address(this), msg.sender, id);
}
/// @notice Withdraw `id` with `value` from `token` to the sender.
function withdrawERC1155(
IERC1155 token,
uint256 id,
uint256 value
) external onlyOwner {
token.safeTransferFrom(address(this), msg.sender, id, value, "");
}
/// @dev Modified for opensea and looksrare pre-approve so users can make truly gasless sales.
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
if (!marketplacesApproved) return super.isApprovedForAll(owner, operator);
return
operator == address(ProxyRegistry(opensea).proxies(owner)) ||
operator == looksrare ||
super.isApprovedForAll(owner, operator);
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
|
Safely mints `tokenId_` and transfers it to `to`.
|
function _safeMint(address to_, uint256 tokenId_) internal virtual {
_safeMint(to_, tokenId_, "");
}
| 1,994,573
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// Part: IFund
interface IFund {
function underlying() external view returns (address);
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdraw(uint256 numberOfShares) external;
function getPricePerShare() external view returns (uint256);
function totalValueLocked() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder)
external
view
returns (uint256);
}
// Part: IGovernable
interface IGovernable {
function governance() external view returns (address);
}
// Part: IStrategy
interface IStrategy {
function underlying() external view returns (address);
function fund() external view returns (address);
function creator() external view returns (address);
function withdrawAllToFund() external;
function withdrawToFund(uint256 amount) external;
function investedUnderlyingBalance() external view returns (uint256);
function doHardWork() external;
function depositArbCheck() external view returns (bool);
}
// Part: IYVaultV2
interface IYVaultV2 {
// ERC20 part
function balanceOf(address) external view returns (uint256);
// VaultV2 view interface
function emergencyShutdown() external view returns (bool);
function pricePerShare() external view returns (uint256);
// VaultV2 user interface
function deposit(uint256 amount) external;
function withdraw(uint256 amount) external;
}
// Part: OpenZeppelin/openzeppelin-contracts@3.4.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@3.4.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@3.4.0/Math
/**
* @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);
}
}
// Part: OpenZeppelin/openzeppelin-contracts@3.4.0/SafeMath
/**
* @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;
}
}
// Part: OpenZeppelin/openzeppelin-contracts@3.4.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 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");
}
}
}
// Part: YearnV2StrategyBase
/**
* This strategy takes an asset (DAI, USDC), deposits into yv2 vault. Currently building only for DAI.
*/
contract YearnV2StrategyBase is IStrategy {
enum TokenIndex {DAI, USDC}
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public override underlying;
address public override fund;
address public override creator;
// the matching enum record used to determine the index
TokenIndex tokenIndex;
// the y-vault corresponding to the underlying asset
address public yVault;
// these tokens cannot be claimed by the governance
mapping(address => bool) public canNotSweep;
bool public investActivated;
constructor(
address _fund,
address _yVault,
uint256 _tokenIndex
) public {
fund = _fund;
underlying = IFund(fund).underlying();
tokenIndex = TokenIndex(_tokenIndex);
yVault = _yVault;
creator = msg.sender;
// restricted tokens, can not be swept
canNotSweep[underlying] = true;
canNotSweep[yVault] = true;
investActivated = true;
}
function governance() internal view returns (address) {
return IGovernable(fund).governance();
}
modifier onlyFundOrGovernance() {
require(
msg.sender == fund || msg.sender == governance(),
"The sender has to be the governance or fund"
);
_;
}
/**
* TODO
*/
function depositArbCheck() public view override returns (bool) {
return true;
}
/**
* Allows Governance to withdraw partial shares to reduce slippage incurred
* and facilitate migration / withdrawal / strategy switch
*/
function withdrawPartialShares(uint256 shares)
external
onlyFundOrGovernance
{
IYVaultV2(yVault).withdraw(shares);
}
function setInvestActivated(bool _investActivated)
external
onlyFundOrGovernance
{
investActivated = _investActivated;
}
/**
* Withdraws an underlying asset from the strategy to the fund in the specified amount.
* It tries to withdraw from the strategy contract if this has enough balance.
* Otherwise, we withdraw shares from the yv2 vault. Transfer the required underlying amount to fund,
* and reinvest the rest. We can make it better by calculating the correct amount and withdrawing only that much.
*/
function withdrawToFund(uint256 underlyingAmount)
external
override
onlyFundOrGovernance
{
uint256 underlyingBalanceBefore =
IERC20(underlying).balanceOf(address(this));
if (underlyingBalanceBefore >= underlyingAmount) {
IERC20(underlying).safeTransfer(fund, underlyingAmount);
return;
}
uint256 shares =
shareValueFromUnderlying(
underlyingAmount.sub(underlyingBalanceBefore)
);
IYVaultV2(yVault).withdraw(shares);
// we can transfer the asset to the fund
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeTransfer(
fund,
Math.min(underlyingAmount, underlyingBalance)
);
}
}
/**
* Withdraws all assets from the yv2 vault and transfer to fund.
*/
function withdrawAllToFund() external override onlyFundOrGovernance {
uint256 shares = IYVaultV2(yVault).balanceOf(address(this));
IYVaultV2(yVault).withdraw(shares);
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeTransfer(fund, underlyingBalance);
}
}
/**
* Invests all underlying assets into our yv2 vault.
*/
function investAllUnderlying() internal {
if (!investActivated) {
return;
}
require(
!IYVaultV2(yVault).emergencyShutdown(),
"Vault is emergency shutdown"
);
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (underlyingBalance > 0) {
IERC20(underlying).safeApprove(yVault, 0);
IERC20(underlying).safeApprove(yVault, underlyingBalance);
// deposits the entire balance to yv2 vault
IYVaultV2(yVault).deposit(underlyingBalance);
}
}
/**
* The hard work only invests all underlying assets
*/
function doHardWork() public override onlyFundOrGovernance {
investAllUnderlying();
}
// no tokens apart from underlying should be sent to this contract. Any tokens that are sent here by mistake are recoverable by governance
function sweep(address _token, address _sweepTo) external {
require(governance() == msg.sender, "Not governance");
require(!canNotSweep[_token], "Token is restricted");
IERC20(_token).safeTransfer(
_sweepTo,
IERC20(_token).balanceOf(address(this))
);
}
/**
* Returns the underlying invested balance. This is the underlying amount based on shares in the yv2 vault,
* plus the current balance of the underlying asset.
*/
function investedUnderlyingBalance()
external
view
override
returns (uint256)
{
uint256 shares = IERC20(yVault).balanceOf(address(this));
uint256 price = IYVaultV2(yVault).pricePerShare();
uint256 precision = 10**18;
uint256 underlyingBalanceinYVault = shares.mul(price).div(precision);
return
underlyingBalanceinYVault.add(
IERC20(underlying).balanceOf(address(this))
);
}
/**
* Returns the value of the underlying token in yToken
*/
function shareValueFromUnderlying(uint256 underlyingAmount)
internal
view
returns (uint256)
{
// 1 yToken = this much underlying, 10 ** 18 precision for all tokens
return
underlyingAmount.mul(10**18).div(IYVaultV2(yVault).pricePerShare());
}
}
// File: YearnV2StrategyMainnet.sol
/**
* Adds the mainnet addresses to the YearnV2StrategyBase
*/
contract YearnV2StrategyMainnet is YearnV2StrategyBase {
// token addresses
// y-addresses are taken from: https://docs.yearn.finance/products/yvaults-1/v2-yvaults/strategies-and-yvaults-available
address public constant dai =
address(0x6B175474E89094C44Da98b954EedeAC495271d0F);
address public constant yvdai =
address(0x19D3364A399d251E894aC732651be8B0E4e85001);
address public constant usdc =
address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
address public constant yvusdc =
address(0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9);
// pre-defined constant mapping: underlying -> y-token
mapping(address => address) public yVaults;
constructor(address _fund)
public
YearnV2StrategyBase(_fund, address(0), 0)
{
yVaults[dai] = yvdai;
yVaults[usdc] = yvusdc;
yVault = yVaults[underlying];
require(
yVault != address(0),
"underlying not supported: yVault is not defined"
);
if (underlying == dai) {
tokenIndex = TokenIndex.DAI;
} else if (underlying == usdc) {
tokenIndex = TokenIndex.USDC;
} else {
revert("Asset not supported");
}
}
}
|
Returns the underlying invested balance. This is the underlying amount based on shares in the yv2 vault, plus the current balance of the underlying asset./
|
function investedUnderlyingBalance()
external
view
override
returns (uint256)
{
uint256 shares = IERC20(yVault).balanceOf(address(this));
uint256 price = IYVaultV2(yVault).pricePerShare();
uint256 precision = 10**18;
uint256 underlyingBalanceinYVault = shares.mul(price).div(precision);
return
underlyingBalanceinYVault.add(
IERC20(underlying).balanceOf(address(this))
);
}
| 10,144,280
|
./full_match/4/0xDd39fed94182B9fe40CEb247F2D2af1237D9710D/sources/contracts/NounsToken.sol
|
Compose tokenURI for a Noun. Fetches original SVG, adds clothes. See {IERC721Metadata-tokenURI}./ Fetch the original SVG (base64 encoded) from Nouns descriptor Decode base64 SVG into bytes Remove the SVG closing tag `</svg>` Encode substring bytes Loop through clothes for this tokenId and encode them in Encode the clothing bytes for these clothes
|
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), 'nonexistent token');
string memory NounID = tokenId.toString();
string memory name = string(abi.encodePacked('CoolNouns ', NounID));
string memory description = tokenDescription;
string memory SVG = descriptor.generateSVGImage(seeds[tokenId]);
bytes memory decodedSVG = Base64.decode(SVG);
string memory substring = removeLastSVGTag(decodedSVG);
bytes memory finalSVGBytes = abi.encodePacked(substring);
for (uint256 i = 0; i < clothingState[tokenId].length; i++) {
uint256 clothingIndexToAdd = clothingState[tokenId][i];
finalSVGBytes = abi.encodePacked(finalSVGBytes, clothingList[clothingIndexToAdd]);
}
return string(abi.encodePacked('data:application/json;base64,', json));
}
| 12,499,864
|
pragma solidity ^0.5.0;
import "../openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";
import "../openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./Claimable.sol";
import "./ProxyClaimable.sol";
import "./Governance.sol";
/**
* @title IERC20 mintable interface
*/
interface IERC20Mintable {
function mint(address to, uint256 value) external returns (bool);
}
/**
* @title Organization interface
*/
interface IOrg {
function isStableCoin(address _stableCoin) external returns (bool);
function getStableCoinCount() external view returns (uint256);
function getStableCoin(uint256 i) external view returns (address);
function token() external view returns (address);
}
/**
* @title CrowdSale interface
* @dev CrowdSale interface
*/
contract ICrowdSale {
address public stcFund;
}
contract ContributorRelay {
address public contributorAcct;
address public crowdSaleCtct;
constructor(address _contributorAcct) public {
crowdSaleCtct = msg.sender;
contributorAcct = _contributorAcct;
}
function relayStcToFund(ERC20Detailed _stableCoin, uint256 amount)
public
{
require(msg.sender == crowdSaleCtct, "Call only from CrowdSale account");
_stableCoin.transfer(ICrowdSale(crowdSaleCtct).stcFund(), amount);
}
function returnStcToContributor(ERC20Detailed _stableCoin, uint256 amount)
public
{
require(msg.sender == contributorAcct, "Call only from contributorAcct account");
_stableCoin.transfer(contributorAcct, amount);
}
}
/**
* @title CrowdSale
*
* @dev The contract which receives stablecoin-contributions and mints tokens
*/
contract CrowdSale is Claimable, ProxyClaimable {
using SafeMath for uint256;
// We convert all USD values to aUSD (attoUSD)
// to achieve highest accuracy operating with different stablecoins
uint256 constant public AUSD_DECIMALS = 18;
uint256 constant public USD = 10 ** AUSD_DECIMALS;
uint256 constant public SOFTCAP_AUSD = 3000000 * USD; // 3M USD
uint256 constant public SOFTCAP_DEADLINE = 1999999999;
uint256 constant public HARDCAP_AUSD = 10000000 * USD; // 10M USD
uint256 constant public HARDCAP_DEADLINE = 2999999999;
uint256 constant public MIN_CONTRIB = 100000;
uint256 constant public MIN_CONTRIB_AUSD = MIN_CONTRIB * USD; // 100K USD
// amount of raised funds (the sum of all contributed stablecoins)
uint256 public raisedAUsd;
bool public softCapReached; // true if softCap reached
// if running==true the CrowdSale is active and able to process contributions
// otherwise it's in configuration mode and should be start()'ed
enum State { Init, PreSoftCap, PostSoftCap }
State public state = State.Init;
// the Externally Owned Account of webservice
address public webPlatformAcct;
// Organization contract keeps the token address and the list of allowed stablecoins
IOrg public org;
Governance public gov;
//Fund collecting contributor's stablecoins on its balance
address public stcFund;
// The tap connected to stcFund. Used in Refunding process
event ContributorRelayDeployed(address contributorRelay);
/**
* @dev Constructor
* @param _org address of Organization contract.
* @param _gov address of Governance contract
*/
constructor (IOrg _org, Governance _gov, address _stcFund, address _webPlatformAcct) public {
org = _org;
gov = _gov;
stcFund = _stcFund;
webPlatformAcct = _webPlatformAcct;
}
/**
* @dev set Backend account address during initial configuration
* @param _webPlatformAcct address Address to be set as Backend account address.
*/
function setWebPlatformAcct(address _webPlatformAcct) public onlyOwner {
require(state == State.Init);
webPlatformAcct = _webPlatformAcct;
}
/**
* @dev creates personal ContributorRelay contract for individual contributor
* @param _contributorAcct address of desired Token.
* @return bool operation result.
*/
function newContributorRelay(address _contributorAcct) public {
require(state != State.Init);
address contributorRelay = address(new ContributorRelay(_contributorAcct));
emit ContributorRelayDeployed(contributorRelay);
}
/**
* @dev Processes contribution and mints corresponding amount of tokens
* @param _contributorRelay personal ContributorRelay contract to wthdraw from
* @param _stcAddr address of stablecoin contract to withdraw
* @param _stcAmount amount of stablecoins to withdraw in minimal fraction units
*/
function processContribution(
ContributorRelay _contributorRelay,
address _stcAddr,
uint256 _stcAmount
)
public returns (bool) {
require(state != State.Init);
require(msg.sender == webPlatformAcct || msg.sender == _contributorRelay.contributorAcct());
require(org.isStableCoin(_stcAddr), "Not a stablecoin");
require(_stcAmount >= MIN_CONTRIB);
require(ERC20Detailed(_stcAddr).balanceOf(address(_contributorRelay))
>= _stcAmount);
uint256 aUsdAmount = convertStcAmountToAUsd(_stcAddr, _stcAmount);
uint256 tokens = calculateTokensByAUsdContribution(aUsdAmount);
IERC20Mintable token = IERC20Mintable(org.token());
token.mint(address(gov), tokens);
_contributorRelay.relayStcToFund(ERC20Detailed(_stcAddr), _stcAmount);
// Register contribution in Governance contract
address contributorAcct = _contributorRelay.contributorAcct();
bool result = gov.registerContribution(contributorAcct, _stcAddr, _stcAmount, tokens);
return result;
}
/**
* @dev Finishes configuration and starts the CrowdSale.
* Executed by admin once after configuration complete
*/
function start() public onlyOwner {
require(state == State.Init);
state = State.PreSoftCap;
}
/**
* @dev the owner (governance) can finish the CrowdSale prematurely
* (only after SoftCap raised)
*/
function finish() public onlyOwner {
require(state == State.PostSoftCap);
selfdestruct(msg.sender);
}
/**
* @dev Try to switch state
* It made public intentionally to make state transition autonomous
* (anybody can try to initiate it from any account)
*/
function tryToSwitchState() public {
require(state != State.Init);
if (raisedAUsd >= HARDCAP_AUSD || now >= HARDCAP_DEADLINE) {
transferOwnership(address(gov));
gov.proxyClaimOwnership(address(this));
gov.makeVotable();
selfdestruct(msg.sender);
}
if (raisedAUsd >= SOFTCAP_AUSD) {
transferOwnership(address(gov));
gov.proxyClaimOwnership(address(this));
gov.makeVotable();
state = State.PostSoftCap;
return;
}
if (now >= SOFTCAP_DEADLINE) {
gov.startRefunding();
selfdestruct(msg.sender);
}
}
/**
* @dev Convert given amount of specific Stablecoin uinits to attoUsd (10e-18 USD)
* Since stablecoins have different decimals, the USD price of minimal unit is different
*/
function convertStcAmountToAUsd(
address _stcAddr,
uint256 _stcAmount
) public view returns (uint256) {
uint8 decimals = ERC20Detailed(_stcAddr).decimals();
uint256 remainingDecimals = uint256(AUSD_DECIMALS).sub(decimals);
uint256 multiplier = 10 ** remainingDecimals;
return _stcAmount.mul(multiplier);
}
/**
* @dev Calculate token amount (in minimal units of the token) for given
* contribution in attoUSD (10e-18 USD)
*/
// solhint-disable-next-line code-complexity
function calculateTokensByAUsdContribution(uint256 aUsdAmount)
public
view
returns (uint256)
{
uint256 tokenDecimals = ERC20Detailed(org.token()).decimals();
uint256 decDivider = 10 ** (18 - tokenDecimals);
uint256 baseTokens = aUsdAmount.mul(20).div(decDivider);
if (aUsdAmount < 500000 * USD) {
return baseTokens;
}
if (aUsdAmount < 1000000 * USD) {
return baseTokens.add(baseTokens.mul(5).div(100));
}
if (aUsdAmount < 2000000 * USD) {
return baseTokens.add(baseTokens.mul(10).div(100));
}
if (aUsdAmount < 3000000 * USD) {
return baseTokens.add(baseTokens.mul(15).div(100));
}
if (aUsdAmount < 4000000 * USD) {
return baseTokens.add(baseTokens.mul(20).div(100));
}
if (aUsdAmount < 5000000 * USD) {
return baseTokens.add(baseTokens.mul(25).div(100));
}
if (aUsdAmount < 6000000 * USD) {
return baseTokens.add(baseTokens.mul(30).div(100));
}
if (aUsdAmount < 7000000 * USD) {
return baseTokens.add(baseTokens.mul(35).div(100));
}
if (aUsdAmount < 8000000 * USD) {
return baseTokens.add(baseTokens.mul(40).div(100));
}
if (aUsdAmount < 9000000 * USD) {
return baseTokens.add(baseTokens.mul(45).div(100));
}
return baseTokens.add(baseTokens.mul(50).div(100));
}
}
|
creates personal ContributorRelay contract for individual contributor _contributorAcct address of desired Token. return bool operation result./
|
function newContributorRelay(address _contributorAcct) public {
require(state != State.Init);
address contributorRelay = address(new ContributorRelay(_contributorAcct));
emit ContributorRelayDeployed(contributorRelay);
}
| 15,812,855
|
./partial_match/1/0x5fa60726E62c50Af45Ff2F6280C468DA438A7837/sources/contracts/exchangeV2/BlurExchangeV2.sol
|
required by the OZ UUPS module
|
{
address public governor;
import { IBlurExchangeV2 } from "./interfaces/IBlurExchangeV2.sol";
import { ReentrancyGuardUpgradeable } from "./lib/ReentrancyGuardUpgradeable.sol";
function _authorizeUpgrade(address) internal override onlyOwner {}
constructor(address delegate, address pool, address proxy) Executor(delegate, pool, proxy) {
_disableInitializers();
}
function initialize() external initializer {
__UUPSUpgradeable_init();
__Ownable_init();
__Reentrancy_init();
verifyDomain();
}
modifier onlyGovernor() {
if (msg.sender != governor) {
revert Unauthorized();
}
_;
}
modifier onlyGovernor() {
if (msg.sender != governor) {
revert Unauthorized();
}
_;
}
function setProtocolFee(address recipient, uint16 rate) external onlyGovernor {
if (rate > _MAX_PROTOCOL_FEE_RATE) {
revert ProtocolFeeTooHigh();
}
protocolFee = FeeRate(recipient, rate);
emit NewProtocolFee(recipient, rate);
}
function setProtocolFee(address recipient, uint16 rate) external onlyGovernor {
if (rate > _MAX_PROTOCOL_FEE_RATE) {
revert ProtocolFeeTooHigh();
}
protocolFee = FeeRate(recipient, rate);
emit NewProtocolFee(recipient, rate);
}
function setGovernor(address _governor) external onlyOwner {
governor = _governor;
emit NewGovernor(_governor);
}
function setOracle(address oracle, bool approved) external onlyOwner {
if (approved) {
oracles[oracle] = 1;
oracles[oracle] = 0;
}
emit SetOracle(oracle, approved);
}
function setOracle(address oracle, bool approved) external onlyOwner {
if (approved) {
oracles[oracle] = 1;
oracles[oracle] = 0;
}
emit SetOracle(oracle, approved);
}
} else {
function setBlockRange(uint256 _blockRange) external onlyOwner {
blockRange = _blockRange;
emit NewBlockRange(_blockRange);
}
function cancelTrades(Cancel[] memory cancels) external {
uint256 cancelsLength = cancels.length;
for (uint256 i; i < cancelsLength; ) {
Cancel memory cancel = cancels[i];
amountTaken[msg.sender][cancel.hash][cancel.index] += cancel.amount;
emit CancelTrade(msg.sender, cancel.hash, cancel.index, cancel.amount);
unchecked {
++i;
}
}
}
function cancelTrades(Cancel[] memory cancels) external {
uint256 cancelsLength = cancels.length;
for (uint256 i; i < cancelsLength; ) {
Cancel memory cancel = cancels[i];
amountTaken[msg.sender][cancel.hash][cancel.index] += cancel.amount;
emit CancelTrade(msg.sender, cancel.hash, cancel.index, cancel.amount);
unchecked {
++i;
}
}
}
function cancelTrades(Cancel[] memory cancels) external {
uint256 cancelsLength = cancels.length;
for (uint256 i; i < cancelsLength; ) {
Cancel memory cancel = cancels[i];
amountTaken[msg.sender][cancel.hash][cancel.index] += cancel.amount;
emit CancelTrade(msg.sender, cancel.hash, cancel.index, cancel.amount);
unchecked {
++i;
}
}
}
function incrementNonce() external {
emit NonceIncremented(msg.sender, ++nonces[msg.sender]);
}
EXECUTION WRAPPERS
function takeAsk(
TakeAsk memory inputs,
bytes calldata oracleSignature
)
public
payable
nonReentrant
verifyOracleSignature(_hashCalldata(msg.sender), oracleSignature)
{
_takeAsk(
inputs.orders,
inputs.exchanges,
inputs.takerFee,
inputs.signatures,
inputs.tokenRecipient
);
}
function takeBid(
TakeBid memory inputs,
bytes calldata oracleSignature
) public verifyOracleSignature(_hashCalldata(msg.sender), oracleSignature) {
_takeBid(inputs.orders, inputs.exchanges, inputs.takerFee, inputs.signatures);
}
function takeAskSingle(
TakeAskSingle memory inputs,
bytes calldata oracleSignature
)
public
payable
nonReentrant
verifyOracleSignature(_hashCalldata(msg.sender), oracleSignature)
{
_takeAskSingle(
inputs.order,
inputs.exchange,
inputs.takerFee,
inputs.signature,
inputs.tokenRecipient
);
}
function takeBidSingle(
TakeBidSingle memory inputs,
bytes calldata oracleSignature
) external verifyOracleSignature(_hashCalldata(msg.sender), oracleSignature) {
_takeBidSingle(inputs.order, inputs.exchange, inputs.takerFee, inputs.signature);
}
EXECUTION POOL WRAPPERS
function takeAskSinglePool(
TakeAskSingle memory inputs,
bytes calldata oracleSignature,
uint256 amountToWithdraw
) external payable {
_withdrawFromPool(msg.sender, amountToWithdraw);
takeAskSingle(inputs, oracleSignature);
}
function takeAskPool(
TakeAsk memory inputs,
bytes calldata oracleSignature,
uint256 amountToWithdraw
) external payable {
_withdrawFromPool(msg.sender, amountToWithdraw);
takeAsk(inputs, oracleSignature);
}
EXECUTION FUNCTIONS
function _takeAskSingle(
Order memory order,
Exchange memory exchange,
FeeRate memory takerFee,
bytes memory signature,
address tokenRecipient
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
Listing memory listing = exchange.listing;
uint256 takerAmount = exchange.taker.amount;
if (!_validateOrderAndListing(order, OrderType.ASK, exchange, signature, fees)) {
revert InvalidOrder();
}
order,
OrderType.ASK,
listing.tokenId,
takerAmount,
tokenRecipient
);
unchecked {
amountTaken[order.trader][bytes32(order.salt)][listing.index] += takerAmount;
}
{
bool[] memory successfulTransfers = _executeNonfungibleTransfers(executionBatch, 1);
if (!successfulTransfers[0]) {
revert TokenTransferFailed();
}
}
(
uint256 totalPrice,
uint256 protocolFeeAmount,
uint256 makerFeeAmount,
uint256 takerFeeAmount
) = _computeFees(listing.price, takerAmount, order.makerFee, fees);
unchecked {
if (address(this).balance < totalPrice + takerFeeAmount) {
revert InsufficientFunds();
}
}
_transferETH(fees.takerFee.recipient, takerFeeAmount);
_transferETH(order.makerFee.recipient, makerFeeAmount);
unchecked {
_transferETH(order.trader, totalPrice - makerFeeAmount - protocolFeeAmount);
}
_emitExecutionEvent(executionBatch, order, listing.index, totalPrice, fees, OrderType.ASK);
}
function _takeAskSingle(
Order memory order,
Exchange memory exchange,
FeeRate memory takerFee,
bytes memory signature,
address tokenRecipient
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
Listing memory listing = exchange.listing;
uint256 takerAmount = exchange.taker.amount;
if (!_validateOrderAndListing(order, OrderType.ASK, exchange, signature, fees)) {
revert InvalidOrder();
}
order,
OrderType.ASK,
listing.tokenId,
takerAmount,
tokenRecipient
);
unchecked {
amountTaken[order.trader][bytes32(order.salt)][listing.index] += takerAmount;
}
{
bool[] memory successfulTransfers = _executeNonfungibleTransfers(executionBatch, 1);
if (!successfulTransfers[0]) {
revert TokenTransferFailed();
}
}
(
uint256 totalPrice,
uint256 protocolFeeAmount,
uint256 makerFeeAmount,
uint256 takerFeeAmount
) = _computeFees(listing.price, takerAmount, order.makerFee, fees);
unchecked {
if (address(this).balance < totalPrice + takerFeeAmount) {
revert InsufficientFunds();
}
}
_transferETH(fees.takerFee.recipient, takerFeeAmount);
_transferETH(order.makerFee.recipient, makerFeeAmount);
unchecked {
_transferETH(order.trader, totalPrice - makerFeeAmount - protocolFeeAmount);
}
_emitExecutionEvent(executionBatch, order, listing.index, totalPrice, fees, OrderType.ASK);
}
bytes memory executionBatch = _initializeSingleExecution(
function _takeAskSingle(
Order memory order,
Exchange memory exchange,
FeeRate memory takerFee,
bytes memory signature,
address tokenRecipient
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
Listing memory listing = exchange.listing;
uint256 takerAmount = exchange.taker.amount;
if (!_validateOrderAndListing(order, OrderType.ASK, exchange, signature, fees)) {
revert InvalidOrder();
}
order,
OrderType.ASK,
listing.tokenId,
takerAmount,
tokenRecipient
);
unchecked {
amountTaken[order.trader][bytes32(order.salt)][listing.index] += takerAmount;
}
{
bool[] memory successfulTransfers = _executeNonfungibleTransfers(executionBatch, 1);
if (!successfulTransfers[0]) {
revert TokenTransferFailed();
}
}
(
uint256 totalPrice,
uint256 protocolFeeAmount,
uint256 makerFeeAmount,
uint256 takerFeeAmount
) = _computeFees(listing.price, takerAmount, order.makerFee, fees);
unchecked {
if (address(this).balance < totalPrice + takerFeeAmount) {
revert InsufficientFunds();
}
}
_transferETH(fees.takerFee.recipient, takerFeeAmount);
_transferETH(order.makerFee.recipient, makerFeeAmount);
unchecked {
_transferETH(order.trader, totalPrice - makerFeeAmount - protocolFeeAmount);
}
_emitExecutionEvent(executionBatch, order, listing.index, totalPrice, fees, OrderType.ASK);
}
function _takeAskSingle(
Order memory order,
Exchange memory exchange,
FeeRate memory takerFee,
bytes memory signature,
address tokenRecipient
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
Listing memory listing = exchange.listing;
uint256 takerAmount = exchange.taker.amount;
if (!_validateOrderAndListing(order, OrderType.ASK, exchange, signature, fees)) {
revert InvalidOrder();
}
order,
OrderType.ASK,
listing.tokenId,
takerAmount,
tokenRecipient
);
unchecked {
amountTaken[order.trader][bytes32(order.salt)][listing.index] += takerAmount;
}
{
bool[] memory successfulTransfers = _executeNonfungibleTransfers(executionBatch, 1);
if (!successfulTransfers[0]) {
revert TokenTransferFailed();
}
}
(
uint256 totalPrice,
uint256 protocolFeeAmount,
uint256 makerFeeAmount,
uint256 takerFeeAmount
) = _computeFees(listing.price, takerAmount, order.makerFee, fees);
unchecked {
if (address(this).balance < totalPrice + takerFeeAmount) {
revert InsufficientFunds();
}
}
_transferETH(fees.takerFee.recipient, takerFeeAmount);
_transferETH(order.makerFee.recipient, makerFeeAmount);
unchecked {
_transferETH(order.trader, totalPrice - makerFeeAmount - protocolFeeAmount);
}
_emitExecutionEvent(executionBatch, order, listing.index, totalPrice, fees, OrderType.ASK);
}
function _takeAskSingle(
Order memory order,
Exchange memory exchange,
FeeRate memory takerFee,
bytes memory signature,
address tokenRecipient
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
Listing memory listing = exchange.listing;
uint256 takerAmount = exchange.taker.amount;
if (!_validateOrderAndListing(order, OrderType.ASK, exchange, signature, fees)) {
revert InvalidOrder();
}
order,
OrderType.ASK,
listing.tokenId,
takerAmount,
tokenRecipient
);
unchecked {
amountTaken[order.trader][bytes32(order.salt)][listing.index] += takerAmount;
}
{
bool[] memory successfulTransfers = _executeNonfungibleTransfers(executionBatch, 1);
if (!successfulTransfers[0]) {
revert TokenTransferFailed();
}
}
(
uint256 totalPrice,
uint256 protocolFeeAmount,
uint256 makerFeeAmount,
uint256 takerFeeAmount
) = _computeFees(listing.price, takerAmount, order.makerFee, fees);
unchecked {
if (address(this).balance < totalPrice + takerFeeAmount) {
revert InsufficientFunds();
}
}
_transferETH(fees.takerFee.recipient, takerFeeAmount);
_transferETH(order.makerFee.recipient, makerFeeAmount);
unchecked {
_transferETH(order.trader, totalPrice - makerFeeAmount - protocolFeeAmount);
}
_emitExecutionEvent(executionBatch, order, listing.index, totalPrice, fees, OrderType.ASK);
}
function _takeAskSingle(
Order memory order,
Exchange memory exchange,
FeeRate memory takerFee,
bytes memory signature,
address tokenRecipient
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
Listing memory listing = exchange.listing;
uint256 takerAmount = exchange.taker.amount;
if (!_validateOrderAndListing(order, OrderType.ASK, exchange, signature, fees)) {
revert InvalidOrder();
}
order,
OrderType.ASK,
listing.tokenId,
takerAmount,
tokenRecipient
);
unchecked {
amountTaken[order.trader][bytes32(order.salt)][listing.index] += takerAmount;
}
{
bool[] memory successfulTransfers = _executeNonfungibleTransfers(executionBatch, 1);
if (!successfulTransfers[0]) {
revert TokenTransferFailed();
}
}
(
uint256 totalPrice,
uint256 protocolFeeAmount,
uint256 makerFeeAmount,
uint256 takerFeeAmount
) = _computeFees(listing.price, takerAmount, order.makerFee, fees);
unchecked {
if (address(this).balance < totalPrice + takerFeeAmount) {
revert InsufficientFunds();
}
}
_transferETH(fees.takerFee.recipient, takerFeeAmount);
_transferETH(order.makerFee.recipient, makerFeeAmount);
unchecked {
_transferETH(order.trader, totalPrice - makerFeeAmount - protocolFeeAmount);
}
_emitExecutionEvent(executionBatch, order, listing.index, totalPrice, fees, OrderType.ASK);
}
function _takeAskSingle(
Order memory order,
Exchange memory exchange,
FeeRate memory takerFee,
bytes memory signature,
address tokenRecipient
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
Listing memory listing = exchange.listing;
uint256 takerAmount = exchange.taker.amount;
if (!_validateOrderAndListing(order, OrderType.ASK, exchange, signature, fees)) {
revert InvalidOrder();
}
order,
OrderType.ASK,
listing.tokenId,
takerAmount,
tokenRecipient
);
unchecked {
amountTaken[order.trader][bytes32(order.salt)][listing.index] += takerAmount;
}
{
bool[] memory successfulTransfers = _executeNonfungibleTransfers(executionBatch, 1);
if (!successfulTransfers[0]) {
revert TokenTransferFailed();
}
}
(
uint256 totalPrice,
uint256 protocolFeeAmount,
uint256 makerFeeAmount,
uint256 takerFeeAmount
) = _computeFees(listing.price, takerAmount, order.makerFee, fees);
unchecked {
if (address(this).balance < totalPrice + takerFeeAmount) {
revert InsufficientFunds();
}
}
_transferETH(fees.takerFee.recipient, takerFeeAmount);
_transferETH(order.makerFee.recipient, makerFeeAmount);
unchecked {
_transferETH(order.trader, totalPrice - makerFeeAmount - protocolFeeAmount);
}
_emitExecutionEvent(executionBatch, order, listing.index, totalPrice, fees, OrderType.ASK);
}
_transferETH(fees.protocolFee.recipient, protocolFeeAmount);
function _takeAskSingle(
Order memory order,
Exchange memory exchange,
FeeRate memory takerFee,
bytes memory signature,
address tokenRecipient
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
Listing memory listing = exchange.listing;
uint256 takerAmount = exchange.taker.amount;
if (!_validateOrderAndListing(order, OrderType.ASK, exchange, signature, fees)) {
revert InvalidOrder();
}
order,
OrderType.ASK,
listing.tokenId,
takerAmount,
tokenRecipient
);
unchecked {
amountTaken[order.trader][bytes32(order.salt)][listing.index] += takerAmount;
}
{
bool[] memory successfulTransfers = _executeNonfungibleTransfers(executionBatch, 1);
if (!successfulTransfers[0]) {
revert TokenTransferFailed();
}
}
(
uint256 totalPrice,
uint256 protocolFeeAmount,
uint256 makerFeeAmount,
uint256 takerFeeAmount
) = _computeFees(listing.price, takerAmount, order.makerFee, fees);
unchecked {
if (address(this).balance < totalPrice + takerFeeAmount) {
revert InsufficientFunds();
}
}
_transferETH(fees.takerFee.recipient, takerFeeAmount);
_transferETH(order.makerFee.recipient, makerFeeAmount);
unchecked {
_transferETH(order.trader, totalPrice - makerFeeAmount - protocolFeeAmount);
}
_emitExecutionEvent(executionBatch, order, listing.index, totalPrice, fees, OrderType.ASK);
}
_transferETH(msg.sender, address(this).balance);
function _takeBidSingle(
Order memory order,
Exchange memory exchange,
FeeRate memory takerFee,
bytes memory signature
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
Listing memory listing = exchange.listing;
uint256 takerAmount = exchange.taker.amount;
if (!_validateOrderAndListing(order, OrderType.BID, exchange, signature, fees)) {
revert InvalidOrder();
}
order,
OrderType.BID,
exchange.taker.tokenId,
takerAmount,
msg.sender
);
{
bool[] memory successfulTransfers = _executeNonfungibleTransfers(executionBatch, 1);
if (!successfulTransfers[0]) {
revert TokenTransferFailed();
}
}
(
uint256 totalPrice,
uint256 protocolFeeAmount,
uint256 makerFeeAmount,
uint256 takerFeeAmount
) = _computeFees(listing.price, takerAmount, order.makerFee, fees);
_transferPool(trader, order.makerFee.recipient, makerFeeAmount);
_transferPool(trader, fees.takerFee.recipient, takerFeeAmount);
_transferPool(trader, fees.protocolFee.recipient, protocolFeeAmount);
unchecked {
_transferPool(trader, msg.sender, totalPrice - takerFeeAmount - protocolFeeAmount);
amountTaken[trader][bytes32(order.salt)][listing.index] += exchange.taker.amount;
}
_emitExecutionEvent(executionBatch, order, listing.index, totalPrice, fees, OrderType.BID);
}
function _takeBidSingle(
Order memory order,
Exchange memory exchange,
FeeRate memory takerFee,
bytes memory signature
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
Listing memory listing = exchange.listing;
uint256 takerAmount = exchange.taker.amount;
if (!_validateOrderAndListing(order, OrderType.BID, exchange, signature, fees)) {
revert InvalidOrder();
}
order,
OrderType.BID,
exchange.taker.tokenId,
takerAmount,
msg.sender
);
{
bool[] memory successfulTransfers = _executeNonfungibleTransfers(executionBatch, 1);
if (!successfulTransfers[0]) {
revert TokenTransferFailed();
}
}
(
uint256 totalPrice,
uint256 protocolFeeAmount,
uint256 makerFeeAmount,
uint256 takerFeeAmount
) = _computeFees(listing.price, takerAmount, order.makerFee, fees);
_transferPool(trader, order.makerFee.recipient, makerFeeAmount);
_transferPool(trader, fees.takerFee.recipient, takerFeeAmount);
_transferPool(trader, fees.protocolFee.recipient, protocolFeeAmount);
unchecked {
_transferPool(trader, msg.sender, totalPrice - takerFeeAmount - protocolFeeAmount);
amountTaken[trader][bytes32(order.salt)][listing.index] += exchange.taker.amount;
}
_emitExecutionEvent(executionBatch, order, listing.index, totalPrice, fees, OrderType.BID);
}
bytes memory executionBatch = _initializeSingleExecution(
function _takeBidSingle(
Order memory order,
Exchange memory exchange,
FeeRate memory takerFee,
bytes memory signature
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
Listing memory listing = exchange.listing;
uint256 takerAmount = exchange.taker.amount;
if (!_validateOrderAndListing(order, OrderType.BID, exchange, signature, fees)) {
revert InvalidOrder();
}
order,
OrderType.BID,
exchange.taker.tokenId,
takerAmount,
msg.sender
);
{
bool[] memory successfulTransfers = _executeNonfungibleTransfers(executionBatch, 1);
if (!successfulTransfers[0]) {
revert TokenTransferFailed();
}
}
(
uint256 totalPrice,
uint256 protocolFeeAmount,
uint256 makerFeeAmount,
uint256 takerFeeAmount
) = _computeFees(listing.price, takerAmount, order.makerFee, fees);
_transferPool(trader, order.makerFee.recipient, makerFeeAmount);
_transferPool(trader, fees.takerFee.recipient, takerFeeAmount);
_transferPool(trader, fees.protocolFee.recipient, protocolFeeAmount);
unchecked {
_transferPool(trader, msg.sender, totalPrice - takerFeeAmount - protocolFeeAmount);
amountTaken[trader][bytes32(order.salt)][listing.index] += exchange.taker.amount;
}
_emitExecutionEvent(executionBatch, order, listing.index, totalPrice, fees, OrderType.BID);
}
function _takeBidSingle(
Order memory order,
Exchange memory exchange,
FeeRate memory takerFee,
bytes memory signature
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
Listing memory listing = exchange.listing;
uint256 takerAmount = exchange.taker.amount;
if (!_validateOrderAndListing(order, OrderType.BID, exchange, signature, fees)) {
revert InvalidOrder();
}
order,
OrderType.BID,
exchange.taker.tokenId,
takerAmount,
msg.sender
);
{
bool[] memory successfulTransfers = _executeNonfungibleTransfers(executionBatch, 1);
if (!successfulTransfers[0]) {
revert TokenTransferFailed();
}
}
(
uint256 totalPrice,
uint256 protocolFeeAmount,
uint256 makerFeeAmount,
uint256 takerFeeAmount
) = _computeFees(listing.price, takerAmount, order.makerFee, fees);
_transferPool(trader, order.makerFee.recipient, makerFeeAmount);
_transferPool(trader, fees.takerFee.recipient, takerFeeAmount);
_transferPool(trader, fees.protocolFee.recipient, protocolFeeAmount);
unchecked {
_transferPool(trader, msg.sender, totalPrice - takerFeeAmount - protocolFeeAmount);
amountTaken[trader][bytes32(order.salt)][listing.index] += exchange.taker.amount;
}
_emitExecutionEvent(executionBatch, order, listing.index, totalPrice, fees, OrderType.BID);
}
address trader = order.trader;
function _takeBidSingle(
Order memory order,
Exchange memory exchange,
FeeRate memory takerFee,
bytes memory signature
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
Listing memory listing = exchange.listing;
uint256 takerAmount = exchange.taker.amount;
if (!_validateOrderAndListing(order, OrderType.BID, exchange, signature, fees)) {
revert InvalidOrder();
}
order,
OrderType.BID,
exchange.taker.tokenId,
takerAmount,
msg.sender
);
{
bool[] memory successfulTransfers = _executeNonfungibleTransfers(executionBatch, 1);
if (!successfulTransfers[0]) {
revert TokenTransferFailed();
}
}
(
uint256 totalPrice,
uint256 protocolFeeAmount,
uint256 makerFeeAmount,
uint256 takerFeeAmount
) = _computeFees(listing.price, takerAmount, order.makerFee, fees);
_transferPool(trader, order.makerFee.recipient, makerFeeAmount);
_transferPool(trader, fees.takerFee.recipient, takerFeeAmount);
_transferPool(trader, fees.protocolFee.recipient, protocolFeeAmount);
unchecked {
_transferPool(trader, msg.sender, totalPrice - takerFeeAmount - protocolFeeAmount);
amountTaken[trader][bytes32(order.salt)][listing.index] += exchange.taker.amount;
}
_emitExecutionEvent(executionBatch, order, listing.index, totalPrice, fees, OrderType.BID);
}
function _takeAsk(
Order[] memory orders,
Exchange[] memory exchanges,
FeeRate memory takerFee,
bytes memory signatures,
address tokenRecipient
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
(bool[] memory validOrders, uint256[][] memory pendingAmountTaken) = _validateOrders(
orders,
OrderType.ASK,
signatures,
fees
);
uint256 exchangesLength = exchanges.length;
(
bytes memory executionBatch,
FungibleTransfers memory fungibleTransfers
) = _initializeBatch(exchangesLength, OrderType.ASK, tokenRecipient);
Order memory order;
Exchange memory exchange;
uint256 remainingETH = address(this).balance;
for (uint256 i; i < exchangesLength; ) {
exchange = exchanges[i];
order = orders[exchange.index];
if (
_validateListingFromBatch(
order,
OrderType.ASK,
exchange,
validOrders,
pendingAmountTaken
)
) {
bool inserted;
(remainingETH, inserted) = _insertExecutionAsk(
executionBatch,
fungibleTransfers,
order,
exchange,
fees,
remainingETH
);
if (inserted) {
unchecked {
pendingAmountTaken[exchange.index][exchange.listing.index] += exchange
.taker
.amount;
}
}
}
unchecked {
++i;
}
}
}
function _takeAsk(
Order[] memory orders,
Exchange[] memory exchanges,
FeeRate memory takerFee,
bytes memory signatures,
address tokenRecipient
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
(bool[] memory validOrders, uint256[][] memory pendingAmountTaken) = _validateOrders(
orders,
OrderType.ASK,
signatures,
fees
);
uint256 exchangesLength = exchanges.length;
(
bytes memory executionBatch,
FungibleTransfers memory fungibleTransfers
) = _initializeBatch(exchangesLength, OrderType.ASK, tokenRecipient);
Order memory order;
Exchange memory exchange;
uint256 remainingETH = address(this).balance;
for (uint256 i; i < exchangesLength; ) {
exchange = exchanges[i];
order = orders[exchange.index];
if (
_validateListingFromBatch(
order,
OrderType.ASK,
exchange,
validOrders,
pendingAmountTaken
)
) {
bool inserted;
(remainingETH, inserted) = _insertExecutionAsk(
executionBatch,
fungibleTransfers,
order,
exchange,
fees,
remainingETH
);
if (inserted) {
unchecked {
pendingAmountTaken[exchange.index][exchange.listing.index] += exchange
.taker
.amount;
}
}
}
unchecked {
++i;
}
}
}
function _takeAsk(
Order[] memory orders,
Exchange[] memory exchanges,
FeeRate memory takerFee,
bytes memory signatures,
address tokenRecipient
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
(bool[] memory validOrders, uint256[][] memory pendingAmountTaken) = _validateOrders(
orders,
OrderType.ASK,
signatures,
fees
);
uint256 exchangesLength = exchanges.length;
(
bytes memory executionBatch,
FungibleTransfers memory fungibleTransfers
) = _initializeBatch(exchangesLength, OrderType.ASK, tokenRecipient);
Order memory order;
Exchange memory exchange;
uint256 remainingETH = address(this).balance;
for (uint256 i; i < exchangesLength; ) {
exchange = exchanges[i];
order = orders[exchange.index];
if (
_validateListingFromBatch(
order,
OrderType.ASK,
exchange,
validOrders,
pendingAmountTaken
)
) {
bool inserted;
(remainingETH, inserted) = _insertExecutionAsk(
executionBatch,
fungibleTransfers,
order,
exchange,
fees,
remainingETH
);
if (inserted) {
unchecked {
pendingAmountTaken[exchange.index][exchange.listing.index] += exchange
.taker
.amount;
}
}
}
unchecked {
++i;
}
}
}
function _takeAsk(
Order[] memory orders,
Exchange[] memory exchanges,
FeeRate memory takerFee,
bytes memory signatures,
address tokenRecipient
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
(bool[] memory validOrders, uint256[][] memory pendingAmountTaken) = _validateOrders(
orders,
OrderType.ASK,
signatures,
fees
);
uint256 exchangesLength = exchanges.length;
(
bytes memory executionBatch,
FungibleTransfers memory fungibleTransfers
) = _initializeBatch(exchangesLength, OrderType.ASK, tokenRecipient);
Order memory order;
Exchange memory exchange;
uint256 remainingETH = address(this).balance;
for (uint256 i; i < exchangesLength; ) {
exchange = exchanges[i];
order = orders[exchange.index];
if (
_validateListingFromBatch(
order,
OrderType.ASK,
exchange,
validOrders,
pendingAmountTaken
)
) {
bool inserted;
(remainingETH, inserted) = _insertExecutionAsk(
executionBatch,
fungibleTransfers,
order,
exchange,
fees,
remainingETH
);
if (inserted) {
unchecked {
pendingAmountTaken[exchange.index][exchange.listing.index] += exchange
.taker
.amount;
}
}
}
unchecked {
++i;
}
}
}
function _takeAsk(
Order[] memory orders,
Exchange[] memory exchanges,
FeeRate memory takerFee,
bytes memory signatures,
address tokenRecipient
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
(bool[] memory validOrders, uint256[][] memory pendingAmountTaken) = _validateOrders(
orders,
OrderType.ASK,
signatures,
fees
);
uint256 exchangesLength = exchanges.length;
(
bytes memory executionBatch,
FungibleTransfers memory fungibleTransfers
) = _initializeBatch(exchangesLength, OrderType.ASK, tokenRecipient);
Order memory order;
Exchange memory exchange;
uint256 remainingETH = address(this).balance;
for (uint256 i; i < exchangesLength; ) {
exchange = exchanges[i];
order = orders[exchange.index];
if (
_validateListingFromBatch(
order,
OrderType.ASK,
exchange,
validOrders,
pendingAmountTaken
)
) {
bool inserted;
(remainingETH, inserted) = _insertExecutionAsk(
executionBatch,
fungibleTransfers,
order,
exchange,
fees,
remainingETH
);
if (inserted) {
unchecked {
pendingAmountTaken[exchange.index][exchange.listing.index] += exchange
.taker
.amount;
}
}
}
unchecked {
++i;
}
}
}
function _takeAsk(
Order[] memory orders,
Exchange[] memory exchanges,
FeeRate memory takerFee,
bytes memory signatures,
address tokenRecipient
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
(bool[] memory validOrders, uint256[][] memory pendingAmountTaken) = _validateOrders(
orders,
OrderType.ASK,
signatures,
fees
);
uint256 exchangesLength = exchanges.length;
(
bytes memory executionBatch,
FungibleTransfers memory fungibleTransfers
) = _initializeBatch(exchangesLength, OrderType.ASK, tokenRecipient);
Order memory order;
Exchange memory exchange;
uint256 remainingETH = address(this).balance;
for (uint256 i; i < exchangesLength; ) {
exchange = exchanges[i];
order = orders[exchange.index];
if (
_validateListingFromBatch(
order,
OrderType.ASK,
exchange,
validOrders,
pendingAmountTaken
)
) {
bool inserted;
(remainingETH, inserted) = _insertExecutionAsk(
executionBatch,
fungibleTransfers,
order,
exchange,
fees,
remainingETH
);
if (inserted) {
unchecked {
pendingAmountTaken[exchange.index][exchange.listing.index] += exchange
.taker
.amount;
}
}
}
unchecked {
++i;
}
}
}
_executeBatchTransfer(executionBatch, fungibleTransfers, fees, OrderType.ASK);
_transferETH(msg.sender, address(this).balance);
function _takeBid(
Order[] memory orders,
Exchange[] memory exchanges,
FeeRate memory takerFee,
bytes memory signatures
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
(bool[] memory validOrders, uint256[][] memory pendingAmountTaken) = _validateOrders(
orders,
OrderType.BID,
signatures,
fees
);
uint256 exchangesLength = exchanges.length;
(
bytes memory executionBatch,
FungibleTransfers memory fungibleTransfers
) = _initializeBatch(exchangesLength, OrderType.BID, msg.sender);
Order memory order;
Exchange memory exchange;
for (uint256 i; i < exchangesLength; ) {
exchange = exchanges[i];
order = orders[exchange.index];
if (
_validateListingFromBatch(
order,
OrderType.BID,
exchange,
validOrders,
pendingAmountTaken
)
) {
_insertExecutionBid(executionBatch, fungibleTransfers, order, exchange, fees);
unchecked {
pendingAmountTaken[exchange.index][exchange.listing.index] += exchange
.taker
.amount;
}
}
unchecked {
++i;
}
}
}
EXECUTION HELPERS
function _takeBid(
Order[] memory orders,
Exchange[] memory exchanges,
FeeRate memory takerFee,
bytes memory signatures
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
(bool[] memory validOrders, uint256[][] memory pendingAmountTaken) = _validateOrders(
orders,
OrderType.BID,
signatures,
fees
);
uint256 exchangesLength = exchanges.length;
(
bytes memory executionBatch,
FungibleTransfers memory fungibleTransfers
) = _initializeBatch(exchangesLength, OrderType.BID, msg.sender);
Order memory order;
Exchange memory exchange;
for (uint256 i; i < exchangesLength; ) {
exchange = exchanges[i];
order = orders[exchange.index];
if (
_validateListingFromBatch(
order,
OrderType.BID,
exchange,
validOrders,
pendingAmountTaken
)
) {
_insertExecutionBid(executionBatch, fungibleTransfers, order, exchange, fees);
unchecked {
pendingAmountTaken[exchange.index][exchange.listing.index] += exchange
.taker
.amount;
}
}
unchecked {
++i;
}
}
}
EXECUTION HELPERS
function _takeBid(
Order[] memory orders,
Exchange[] memory exchanges,
FeeRate memory takerFee,
bytes memory signatures
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
(bool[] memory validOrders, uint256[][] memory pendingAmountTaken) = _validateOrders(
orders,
OrderType.BID,
signatures,
fees
);
uint256 exchangesLength = exchanges.length;
(
bytes memory executionBatch,
FungibleTransfers memory fungibleTransfers
) = _initializeBatch(exchangesLength, OrderType.BID, msg.sender);
Order memory order;
Exchange memory exchange;
for (uint256 i; i < exchangesLength; ) {
exchange = exchanges[i];
order = orders[exchange.index];
if (
_validateListingFromBatch(
order,
OrderType.BID,
exchange,
validOrders,
pendingAmountTaken
)
) {
_insertExecutionBid(executionBatch, fungibleTransfers, order, exchange, fees);
unchecked {
pendingAmountTaken[exchange.index][exchange.listing.index] += exchange
.taker
.amount;
}
}
unchecked {
++i;
}
}
}
EXECUTION HELPERS
function _takeBid(
Order[] memory orders,
Exchange[] memory exchanges,
FeeRate memory takerFee,
bytes memory signatures
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
(bool[] memory validOrders, uint256[][] memory pendingAmountTaken) = _validateOrders(
orders,
OrderType.BID,
signatures,
fees
);
uint256 exchangesLength = exchanges.length;
(
bytes memory executionBatch,
FungibleTransfers memory fungibleTransfers
) = _initializeBatch(exchangesLength, OrderType.BID, msg.sender);
Order memory order;
Exchange memory exchange;
for (uint256 i; i < exchangesLength; ) {
exchange = exchanges[i];
order = orders[exchange.index];
if (
_validateListingFromBatch(
order,
OrderType.BID,
exchange,
validOrders,
pendingAmountTaken
)
) {
_insertExecutionBid(executionBatch, fungibleTransfers, order, exchange, fees);
unchecked {
pendingAmountTaken[exchange.index][exchange.listing.index] += exchange
.taker
.amount;
}
}
unchecked {
++i;
}
}
}
EXECUTION HELPERS
function _takeBid(
Order[] memory orders,
Exchange[] memory exchanges,
FeeRate memory takerFee,
bytes memory signatures
) internal {
Fees memory fees = Fees(protocolFee, takerFee);
(bool[] memory validOrders, uint256[][] memory pendingAmountTaken) = _validateOrders(
orders,
OrderType.BID,
signatures,
fees
);
uint256 exchangesLength = exchanges.length;
(
bytes memory executionBatch,
FungibleTransfers memory fungibleTransfers
) = _initializeBatch(exchangesLength, OrderType.BID, msg.sender);
Order memory order;
Exchange memory exchange;
for (uint256 i; i < exchangesLength; ) {
exchange = exchanges[i];
order = orders[exchange.index];
if (
_validateListingFromBatch(
order,
OrderType.BID,
exchange,
validOrders,
pendingAmountTaken
)
) {
_insertExecutionBid(executionBatch, fungibleTransfers, order, exchange, fees);
unchecked {
pendingAmountTaken[exchange.index][exchange.listing.index] += exchange
.taker
.amount;
}
}
unchecked {
++i;
}
}
}
EXECUTION HELPERS
_executeBatchTransfer(executionBatch, fungibleTransfers, fees, OrderType.BID);
function _initializeBatch(
uint256 exchangesLength,
OrderType orderType,
address taker
)
internal
pure
returns (bytes memory executionBatch, FungibleTransfers memory fungibleTransfers)
{
uint256 arrayLength = Transfer_size * exchangesLength + One_word;
uint256 executionBatchLength = ExecutionBatch_base_size + arrayLength;
executionBatch = new bytes(executionBatchLength);
assembly {
let calldataPointer := add(executionBatch, ExecutionBatch_calldata_offset)
mstore(add(calldataPointer, ExecutionBatch_taker_offset), taker)
mstore(add(calldataPointer, ExecutionBatch_orderType_offset), orderType)
}
address[] memory feeRecipients = new address[](exchangesLength);
address[] memory makers = new address[](exchangesLength);
uint256[] memory makerTransfers = new uint256[](exchangesLength);
uint256[] memory feeTransfers = new uint256[](exchangesLength);
fungibleTransfers = FungibleTransfers({
totalProtocolFee: 0,
totalSellerTransfer: 0,
totalTakerFee: 0,
feeRecipientId: 0,
feeRecipients: feeRecipients,
makerId: 0,
makers: makers,
feeTransfers: feeTransfers,
makerTransfers: makerTransfers,
executions: executions
});
}
function _initializeBatch(
uint256 exchangesLength,
OrderType orderType,
address taker
)
internal
pure
returns (bytes memory executionBatch, FungibleTransfers memory fungibleTransfers)
{
uint256 arrayLength = Transfer_size * exchangesLength + One_word;
uint256 executionBatchLength = ExecutionBatch_base_size + arrayLength;
executionBatch = new bytes(executionBatchLength);
assembly {
let calldataPointer := add(executionBatch, ExecutionBatch_calldata_offset)
mstore(add(calldataPointer, ExecutionBatch_taker_offset), taker)
mstore(add(calldataPointer, ExecutionBatch_orderType_offset), orderType)
}
address[] memory feeRecipients = new address[](exchangesLength);
address[] memory makers = new address[](exchangesLength);
uint256[] memory makerTransfers = new uint256[](exchangesLength);
uint256[] memory feeTransfers = new uint256[](exchangesLength);
fungibleTransfers = FungibleTransfers({
totalProtocolFee: 0,
totalSellerTransfer: 0,
totalTakerFee: 0,
feeRecipientId: 0,
feeRecipients: feeRecipients,
makerId: 0,
makers: makers,
feeTransfers: feeTransfers,
makerTransfers: makerTransfers,
executions: executions
});
}
AtomicExecution[] memory executions = new AtomicExecution[](exchangesLength);
function _initializeBatch(
uint256 exchangesLength,
OrderType orderType,
address taker
)
internal
pure
returns (bytes memory executionBatch, FungibleTransfers memory fungibleTransfers)
{
uint256 arrayLength = Transfer_size * exchangesLength + One_word;
uint256 executionBatchLength = ExecutionBatch_base_size + arrayLength;
executionBatch = new bytes(executionBatchLength);
assembly {
let calldataPointer := add(executionBatch, ExecutionBatch_calldata_offset)
mstore(add(calldataPointer, ExecutionBatch_taker_offset), taker)
mstore(add(calldataPointer, ExecutionBatch_orderType_offset), orderType)
}
address[] memory feeRecipients = new address[](exchangesLength);
address[] memory makers = new address[](exchangesLength);
uint256[] memory makerTransfers = new uint256[](exchangesLength);
uint256[] memory feeTransfers = new uint256[](exchangesLength);
fungibleTransfers = FungibleTransfers({
totalProtocolFee: 0,
totalSellerTransfer: 0,
totalTakerFee: 0,
feeRecipientId: 0,
feeRecipients: feeRecipients,
makerId: 0,
makers: makers,
feeTransfers: feeTransfers,
makerTransfers: makerTransfers,
executions: executions
});
}
function _initializeSingleExecution(
Order memory order,
OrderType orderType,
uint256 tokenId,
uint256 amount,
address taker
) internal pure returns (bytes memory executionBatch) {
uint256 arrayLength = Transfer_size + One_word;
uint256 executionBatchLength = ExecutionBatch_base_size + arrayLength;
executionBatch = new bytes(executionBatchLength);
assembly {
let calldataPointer := add(executionBatch, ExecutionBatch_calldata_offset)
mstore(add(calldataPointer, ExecutionBatch_taker_offset), taker)
mstore(add(calldataPointer, ExecutionBatch_orderType_offset), orderType)
}
}
function _initializeSingleExecution(
Order memory order,
OrderType orderType,
uint256 tokenId,
uint256 amount,
address taker
) internal pure returns (bytes memory executionBatch) {
uint256 arrayLength = Transfer_size + One_word;
uint256 executionBatchLength = ExecutionBatch_base_size + arrayLength;
executionBatch = new bytes(executionBatchLength);
assembly {
let calldataPointer := add(executionBatch, ExecutionBatch_calldata_offset)
mstore(add(calldataPointer, ExecutionBatch_taker_offset), taker)
mstore(add(calldataPointer, ExecutionBatch_orderType_offset), orderType)
}
}
_insertNonfungibleTransfer(executionBatch, order, tokenId, amount);
}
| 4,003,397
|
./partial_match/1/0x515524EAb87B1F5902B51AB3b324E82c96ba59a8/sources/src/v2/interfaces/IHooks.sol
|
IHooks Interface for the hooks module.
|
interface IHooks {
function vault() external view returns (address vault);
function beforeDeposit(AssetValue[] memory amounts) external;
function afterDeposit(AssetValue[] memory amounts) external;
function beforeWithdraw(AssetValue[] memory amounts) external;
function afterWithdraw(AssetValue[] memory amounts) external;
function beforeSubmit(Operation[] memory operations) external;
function afterSubmit(Operation[] memory operations) external;
function beforeFinalize() external;
function afterFinalize() external;
function decommission() external;
pragma solidity 0.8.21;
import {AssetValue, Operation} from "../Types.sol";
}
| 2,807,651
|
./full_match/100/0x0Ac7ac8C6Eb5BbBEbE2d02E6B6f5B2B8e05759f1/sources/contracts/LP.sol
|
Make new bet. Emits bet token to `msg.sender`. See {ILP-bet}./
|
function bet(
address core,
uint128 amount,
uint64 expiresAt,
IBet.BetData calldata betData
) external override returns (uint256) {
TransferHelper.safeTransferFrom(
token,
msg.sender,
address(this),
amount
);
return _bet(msg.sender, core, amount, expiresAt, betData);
}
| 14,285,417
|
./partial_match/1/0x5f6deE1c84F7ba36fB2d21c88e680812eb670a05/sources/City.sol
|
Internal transfer, only can be called by this contract/ Prevent transfer to 0x0 address. Use burn() instead Check if the sender has enough Check for overflows Save this for an assertion in the future Subtract from the sender Add the same to the recipient Asserts are used to use static analysis to find bugs in your code. They should never fail
|
function _transfer(address _from, address _to, uint _value) internal {
require(_to != address(0));
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
require(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
| 16,018,532
|
/**
*Submitted for verification at Etherscan.io on 2022-03-07
*/
pragma solidity ^0.4.24;
/**
* @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){
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b,"Calculation error");
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,"Calculation error");
uint256 c = a / b;
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256){
require(b <= a,"Calculation error");
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,"Calculation error");
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,"Calculation error");
return a % b;
}
}
/**
* @title IToken
* @dev Contract interface for token contract
*/
contract IToken {
function balanceOf(address) public pure returns (uint256);
function transfer(address, uint256) public pure returns (bool);
function transferFrom(address, address, uint256) public pure returns (bool);
function approve(address , uint256) public pure returns (bool);
}
/**
* @title CLIQWETHLPStaking
* @dev CLIQWETHLP Staking Contract for LP token staking
*/
contract CLIQWETHLPStaking {
using SafeMath for uint256;
address private _owner; // variable for Owner of the Contract.
uint256 private _withdrawTime; // variable to manage withdraw time for Token
uint256 constant public PERIOD_SILVER = 90; // variable constant for time period managemnt
uint256 constant public PERIOD_GOLD = 180; // variable constant for time period managemnt
uint256 constant public PERIOD_PLATINUM = 270; // variable constant for time period managemnt
uint256 constant public WITHDRAW_TIME_SILVER = 45 * 1 days; // variable constant to manage withdraw time lock up
uint256 constant public WITHDRAW_TIME_GOLD = 90 * 1 days; // variable constant to manage withdraw time lock up
uint256 constant public WITHDRAW_TIME_PLATINUM = 135 * 1 days; // variable constant to manage withdraw time lock up
uint256 public TOKEN_REWARD_PERCENT_SILVER = 21788328; // variable constant to manage token reward percentage for silver
uint256 public TOKEN_REWARD_PERCENT_GOLD = 67332005; // variable constant to manage token reward percentage for gold
uint256 public TOKEN_REWARD_PERCENT_PLATINUM = 178233538; // variable constant to manage token reward percentage for platinum
uint256 public TOKEN_PENALTY_PERCENT_SILVER = 10894164; // variable constant to manage token penalty percentage for silver
uint256 public TOKEN_PENALTY_PERCENT_GOLD = 23566201; // variable constant to manage token penalty percentage for gold
uint256 public TOKEN_PENALTY_PERCENT_PLATINUM = 44558384; // variable constant to manage token penalty percentage for platinum
// events to handle staking pause or unpause for token
event Paused();
event Unpaused();
/*
* ---------------------------------------------------------------------------------------------------------------------------
* Functions for owner.
* ---------------------------------------------------------------------------------------------------------------------------
*/
/**
* @dev get address of smart contract owner
* @return address of owner
*/
function getowner() public view returns (address) {
return _owner;
}
/**
* @dev modifier to check if the message sender is owner
*/
modifier onlyOwner() {
require(isOwner(),"You are not authenticate to make this transfer");
_;
}
/**
* @dev Internal function for modifier
*/
function isOwner() internal view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Transfer ownership of the smart contract. For owner only
* @return request status
*/
function transferOwnership(address newOwner) public onlyOwner returns (bool){
_owner = newOwner;
return true;
}
/*
* ---------------------------------------------------------------------------------------------------------------------------
* Functionality of Constructor and Interface
* ---------------------------------------------------------------------------------------------------------------------------
*/
// constructor to declare owner of the contract during time of deploy
constructor() public {
_owner = msg.sender;
}
// Interface declaration for contract
IToken itoken;
// function to set Contract Address for Token Transfer Functions
function setContractAddress(address tokenContractAddress) external onlyOwner returns(bool){
itoken = IToken(tokenContractAddress);
return true;
}
/*
* ----------------------------------------------------------------------------------------------------------------------------
* Owner functions of get value, set value and other Functionality
* ----------------------------------------------------------------------------------------------------------------------------
*/
// function to add token reward in contract
function addTokenReward(uint256 token) external onlyOwner returns(bool){
_ownerTokenAllowance = _ownerTokenAllowance.add(token);
itoken.transferFrom(msg.sender, address(this), token);
return true;
}
// function to withdraw added token reward in contract
function withdrawAddedTokenReward(uint256 token) external onlyOwner returns(bool){
require(token < _ownerTokenAllowance,"Value is not feasible, Please Try Again!!!");
_ownerTokenAllowance = _ownerTokenAllowance.sub(token);
itoken.transfer(msg.sender, token);
return true;
}
// function to get token reward in contract
function getTokenReward() public view returns(uint256){
return _ownerTokenAllowance;
}
// function to pause Token Staking
function pauseTokenStaking() public onlyOwner {
tokenPaused = true;
emit Paused();
}
// function to unpause Token Staking
function unpauseTokenStaking() public onlyOwner {
tokenPaused = false;
emit Unpaused();
}
// function to set values
function setManager(uint256 tokenStakingCount, uint256 tokenTotalDays, address tokenStakingAddress, uint256 tokenStakingStartTime,
uint256 tokenStakingEndTime, uint256 usertokens) external onlyOwner returns(bool){
_tokenStakingCount = tokenStakingCount;
_tokenTotalDays[_tokenStakingCount] = tokenTotalDays;
_tokenStakingAddress[_tokenStakingCount] = tokenStakingAddress;
_tokenStakingId[tokenStakingAddress].push(_tokenStakingCount);
_tokenStakingEndTime[_tokenStakingCount] = tokenStakingEndTime;
_tokenStakingStartTime[_tokenStakingCount] = tokenStakingStartTime;
_usersTokens[_tokenStakingCount] = usertokens;
_TokenTransactionstatus[_tokenStakingCount] = false;
totalStakedToken = totalStakedToken.add(usertokens);
totalTokenStakesInContract = totalTokenStakesInContract.add(usertokens);
return true;
}
// function to set reward percent
function setRewardPercent(uint256 silver, uint256 gold, uint256 platinum) external onlyOwner returns(bool){
require(silver != 0 && gold != 0 && platinum !=0,"Invalid Reward Value or Zero value, Please Try Again!!!");
TOKEN_REWARD_PERCENT_SILVER = silver;
TOKEN_REWARD_PERCENT_GOLD = gold;
TOKEN_REWARD_PERCENT_PLATINUM = platinum;
return true;
}
// function to set penalty percent
function setPenaltyPercent(uint256 silver, uint256 gold, uint256 platinum) external onlyOwner returns(bool){
require(silver != 0 && gold != 0 && platinum !=0,"Invalid Penalty Value or Zero value, Please Try Again!!!");
TOKEN_PENALTY_PERCENT_SILVER = silver;
TOKEN_PENALTY_PERCENT_GOLD = gold;
TOKEN_PENALTY_PERCENT_PLATINUM = platinum;
return true;
}
// function to withdraw token from the contract
function withdrawToken(uint256 amount) external onlyOwner returns(bool){
itoken.transfer(msg.sender,amount);
return true;
}
// function to withdraw ETH from the contract
function withdrawETH() external onlyOwner returns(bool){
msg.sender.transfer(address(this).balance);
return true;
}
/*
* ----------------------------------------------------------------------------------------------------------------------------
* Variable, Mapping for Token Staking Functionality
* ----------------------------------------------------------------------------------------------------------------------------
*/
// mapping for users with id => address Staking Address
mapping (uint256 => address) private _tokenStakingAddress;
// mapping for users with address => id staking id
mapping (address => uint256[]) private _tokenStakingId;
// mapping for users with id => Staking Time
mapping (uint256 => uint256) private _tokenStakingStartTime;
// mapping for users with id => End Time
mapping (uint256 => uint256) private _tokenStakingEndTime;
// mapping for users with id => Tokens
mapping (uint256 => uint256) private _usersTokens;
// mapping for users with id => Status
mapping (uint256 => bool) private _TokenTransactionstatus;
// mapping to keep track of final withdraw value of staked token
mapping(uint256=>uint256) private _finalTokenStakeWithdraw;
// mapping to keep track total number of staking days
mapping(uint256=>uint256) private _tokenTotalDays;
// variable to keep count of Token Staking
uint256 private _tokenStakingCount = 0;
// variable to keep track on reward added by owner
uint256 private _ownerTokenAllowance = 0;
// variable for token time management
uint256 private _tokentime;
// variable for token staking pause and unpause mechanism
bool public tokenPaused = false;
// variable for total Token staked by user
uint256 public totalStakedToken = 0;
// variable for total stake token in contract
uint256 public totalTokenStakesInContract = 0;
// modifier to check the user for staking || Re-enterance Guard
modifier tokenStakeCheck(uint256 tokens, uint256 timePeriod){
require(tokens > 0, "Invalid Token Amount, Please Try Again!!! ");
require(timePeriod == PERIOD_SILVER || timePeriod == PERIOD_GOLD || timePeriod == PERIOD_PLATINUM, "Enter the Valid Time Period and Try Again !!!");
_;
}
/*
* ------------------------------------------------------------------------------------------------------------------------------
* Functions for Token Staking Functionality
* ------------------------------------------------------------------------------------------------------------------------------
*/
// function to performs staking for user tokens for a specific period of time
function stakeToken(uint256 tokens, uint256 time) public tokenStakeCheck(tokens, time) returns(bool){
require(tokenPaused == false, "Staking is Paused, Please try after staking get unpaused!!!");
_tokentime = now + (time * 1 days);
_tokenStakingCount = _tokenStakingCount +1;
_tokenTotalDays[_tokenStakingCount] = time;
_tokenStakingAddress[_tokenStakingCount] = msg.sender;
_tokenStakingId[msg.sender].push(_tokenStakingCount);
_tokenStakingEndTime[_tokenStakingCount] = _tokentime;
_tokenStakingStartTime[_tokenStakingCount] = now;
_usersTokens[_tokenStakingCount] = tokens;
_TokenTransactionstatus[_tokenStakingCount] = false;
totalStakedToken = totalStakedToken.add(tokens);
totalTokenStakesInContract = totalTokenStakesInContract.add(tokens);
itoken.transferFrom(msg.sender, address(this), tokens);
return true;
}
// function to get staking count for token
function getTokenStakingCount() public view returns(uint256){
return _tokenStakingCount;
}
// function to get total Staked tokens
function getTotalStakedToken() public view returns(uint256){
return totalStakedToken;
}
// function to calculate reward for the message sender for token
function getTokenRewardDetailsByStakingId(uint256 id) public view returns(uint256){
if(_tokenTotalDays[id] == PERIOD_SILVER) {
return (_usersTokens[id]*TOKEN_REWARD_PERCENT_SILVER/100000000);
} else if(_tokenTotalDays[id] == PERIOD_GOLD) {
return (_usersTokens[id]*TOKEN_REWARD_PERCENT_GOLD/100000000);
} else if(_tokenTotalDays[id] == PERIOD_PLATINUM) {
return (_usersTokens[id]*TOKEN_REWARD_PERCENT_PLATINUM/100000000);
} else{
return 0;
}
}
// function to calculate penalty for the message sender for token
function getTokenPenaltyDetailByStakingId(uint256 id) public view returns(uint256){
if(_tokenStakingEndTime[id] > now){
if(_tokenTotalDays[id]==PERIOD_SILVER){
return (_usersTokens[id]*TOKEN_PENALTY_PERCENT_SILVER/100000000);
} else if(_tokenTotalDays[id] == PERIOD_GOLD) {
return (_usersTokens[id]*TOKEN_PENALTY_PERCENT_GOLD/100000000);
} else if(_tokenTotalDays[id] == PERIOD_PLATINUM) {
return (_usersTokens[id]*TOKEN_PENALTY_PERCENT_PLATINUM/100000000);
} else {
return 0;
}
} else{
return 0;
}
}
// function for withdrawing staked tokens
function withdrawStakedTokens(uint256 stakingId) public returns(bool) {
require(_tokenStakingAddress[stakingId] == msg.sender,"No staked token found on this address and ID");
require(_TokenTransactionstatus[stakingId] != true,"Either tokens are already withdrawn or blocked by admin");
if(_tokenTotalDays[stakingId] == PERIOD_SILVER){
require(now >= _tokenStakingStartTime[stakingId] + WITHDRAW_TIME_SILVER, "Unable to Withdraw Staked token before 45 days of staking start time, Please Try Again Later!!!");
_TokenTransactionstatus[stakingId] = true;
if(now >= _tokenStakingEndTime[stakingId]){
_finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenRewardDetailsByStakingId(stakingId));
itoken.transfer(msg.sender,_finalTokenStakeWithdraw[stakingId]);
totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]);
} else {
_finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenPenaltyDetailByStakingId(stakingId));
itoken.transfer(msg.sender,_finalTokenStakeWithdraw[stakingId]);
totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]);
}
} else if(_tokenTotalDays[stakingId] == PERIOD_GOLD){
require(now >= _tokenStakingStartTime[stakingId] + WITHDRAW_TIME_GOLD, "Unable to Withdraw Staked token before 90 days of staking start time, Please Try Again Later!!!");
_TokenTransactionstatus[stakingId] = true;
if(now >= _tokenStakingEndTime[stakingId]){
_finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenRewardDetailsByStakingId(stakingId));
itoken.transfer(msg.sender,_finalTokenStakeWithdraw[stakingId]);
totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]);
} else {
_finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenPenaltyDetailByStakingId(stakingId));
itoken.transfer(msg.sender,_finalTokenStakeWithdraw[stakingId]);
totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]);
}
} else if(_tokenTotalDays[stakingId] == PERIOD_PLATINUM){
require(now >= _tokenStakingStartTime[stakingId] + WITHDRAW_TIME_PLATINUM, "Unable to Withdraw Staked token before 135 days of staking start time, Please Try Again Later!!!");
_TokenTransactionstatus[stakingId] = true;
if(now >= _tokenStakingEndTime[stakingId]){
_finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenRewardDetailsByStakingId(stakingId));
itoken.transfer(msg.sender,_finalTokenStakeWithdraw[stakingId]);
totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]);
} else {
_finalTokenStakeWithdraw[stakingId] = _usersTokens[stakingId].add(getTokenPenaltyDetailByStakingId(stakingId));
itoken.transfer(msg.sender,_finalTokenStakeWithdraw[stakingId]);
totalTokenStakesInContract = totalTokenStakesInContract.sub(_usersTokens[stakingId]);
}
} else {
return false;
}
return true;
}
// function to get Final Withdraw Staked value for token
function getFinalTokenStakeWithdraw(uint256 id) public view returns(uint256){
return _finalTokenStakeWithdraw[id];
}
// function to get total token stake in contract
function getTotalTokenStakesInContract() public view returns(uint256){
return totalTokenStakesInContract;
}
/*
* -------------------------------------------------------------------------------------------------------------------------------
* Get Functions for Stake Token Functionality
* -------------------------------------------------------------------------------------------------------------------------------
*/
// function to get Token Staking address by id
function getTokenStakingAddressById(uint256 id) external view returns (address){
require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!");
return _tokenStakingAddress[id];
}
// function to get Token staking id by address
function getTokenStakingIdByAddress(address add) external view returns(uint256[] memory){
require(add != address(0),"Invalid Address, Pleae Try Again!!!");
return _tokenStakingId[add];
}
// function to get Token Staking Starting time by id
function getTokenStakingStartTimeById(uint256 id) external view returns(uint256){
require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!");
return _tokenStakingStartTime[id];
}
// function to get Token Staking Ending time by id
function getTokenStakingEndTimeById(uint256 id) external view returns(uint256){
require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!");
return _tokenStakingEndTime[id];
}
// function to get Token Staking Total Days by Id
function getTokenStakingTotalDaysById(uint256 id) external view returns(uint256){
require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!");
return _tokenTotalDays[id];
}
// function to get Staking tokens by id
function getStakingTokenById(uint256 id) external view returns(uint256){
require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!");
return _usersTokens[id];
}
// function to get Token lockstatus by id
function getTokenLockStatus(uint256 id) external view returns(bool){
require(id <= _tokenStakingCount,"Unable to reterive data on specified id, Please try again!!");
return _TokenTransactionstatus[id];
}
}
|
function to get token reward in contract
|
function getTokenReward() public view returns(uint256){
return _ownerTokenAllowance;
}
| 2,348,609
|
pragma solidity ^0.5.0;
import "../VotingCheckpoint.sol";
import "./WeightedVoteCheckpointStorage.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/**
* @title Checkpoint module for token weighted vote
* @notice This voting system uses public votes
* @notice In this module every token holder has voting right (Should be greater than zero)
* Tally will be calculated as per the weight (balance of the token holder)
*/
contract WeightedVoteCheckpoint is WeightedVoteCheckpointStorage, VotingCheckpoint {
using SafeMath for uint256;
event BallotCreated(
uint256 indexed _ballotId,
uint256 indexed _checkpointId,
uint256 _startTime,
uint256 _endTime,
uint256 _noOfProposals,
uint256 _proposedQuorum
);
event VoteCast(address indexed _voter, uint256 _weight, uint256 indexed _ballotId, uint256 indexed _proposalId);
event BallotStatusChanged(uint256 indexed _ballotId, bool _isActive);
event ChangedBallotExemptedVotersList(uint256 indexed _ballotId, address indexed _voter, bool _change);
/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyToken Address of the polytoken
*/
constructor(address _securityToken, address _polyToken)
public
Module(_securityToken, _polyToken)
{
}
/**
* @notice This function returns the signature of configure function
*/
function getInitFunction() external pure returns(bytes4) {
return bytes4(0);
}
/**
* @notice Allows the token issuer to create a ballot
* @param _duration The duration of the voting period in seconds
* @param _noOfProposals Number of proposals
* @param _proposedQuorum Minimum Quorum percentage required to make a proposal won
*/
function createBallot(uint256 _duration, uint256 _noOfProposals, uint256 _proposedQuorum) external withPerm(ADMIN) {
require(_duration > 0, "Incorrect ballot duration");
uint256 checkpointId = ISecurityToken(securityToken).createCheckpoint();
uint256 endTime = now.add(_duration);
_createCustomBallot(checkpointId, _proposedQuorum, now, endTime, _noOfProposals);
}
function _createCustomBallot(
uint256 _checkpointId,
uint256 _proposedQuorum,
uint256 _startTime,
uint256 _endTime,
uint256 _noOfProposals
)
internal
{
require(_noOfProposals > 1, "Incorrect proposals no");
require(_endTime > _startTime, "Times are not valid");
require(_proposedQuorum <= 100 * 10 ** 16 && _proposedQuorum > 0, "Invalid quorum percentage"); // not more than 100 %
require(
uint64(_startTime) == _startTime &&
uint64(_endTime) == _endTime &&
uint64(_noOfProposals) == _noOfProposals,
"values get overflowed"
);
uint256 ballotId = ballots.length;
ballots.push(
Ballot(
_checkpointId, _proposedQuorum, uint64(_startTime), uint64(_endTime), uint64(_noOfProposals), uint56(0), true
)
);
emit BallotCreated(ballotId, _checkpointId, _startTime, _endTime, _noOfProposals, _proposedQuorum);
}
/**
* @notice Allows the token issuer to create a ballot with custom settings
* @param _checkpointId Index of the checkpoint to use for token balances
* @param _proposedQuorum Minimum Quorum percentage required to make a proposal won
* @param _startTime Start time of the voting period in Unix Epoch time
* @param _endTime End time of the voting period in Unix Epoch time
* @param _noOfProposals Number of proposals
*/
function createCustomBallot(uint256 _checkpointId, uint256 _proposedQuorum, uint256 _startTime, uint256 _endTime, uint256 _noOfProposals) external withPerm(ADMIN) {
require(_checkpointId <= ISecurityToken(securityToken).currentCheckpointId(), "Invalid checkpoint Id");
require(_startTime >= now, "Invalid startTime");
_createCustomBallot(_checkpointId, _proposedQuorum, _startTime, _endTime, _noOfProposals);
}
/**
* @notice Allows a token holder to cast their vote on a specific ballot
* @param _ballotId The index of the target ballot
* @param _proposalId Id of the proposal which investor want to vote for proposal
*/
function castVote(uint256 _ballotId, uint256 _proposalId) external {
_validBallotId(_ballotId);
Ballot storage ballot = ballots[_ballotId];
require(isVoterAllowed(_ballotId, msg.sender), "Invalid voter");
uint256 weight = ISecurityToken(securityToken).balanceOfAt(msg.sender, ballot.checkpointId);
require(weight > 0, "weight should be > 0");
require(ballot.totalProposals >= _proposalId && _proposalId > 0, "Incorrect proposals Id");
require(now >= ballot.startTime && now <= ballot.endTime, "Voting period is not active");
require(ballot.investorToProposal[msg.sender] == 0, "Token holder has already voted");
require(ballot.isActive, "Ballot is not active");
ballot.investorToProposal[msg.sender] = _proposalId;
ballot.totalVoters = ballot.totalVoters + 1;
ballot.proposalToVotes[_proposalId] = ballot.proposalToVotes[_proposalId].add(weight);
emit VoteCast(msg.sender, weight, _ballotId, _proposalId);
}
/**
* Change the given ballot exempted list
* @param _ballotId Given ballot Id
* @param _voter Address of the voter
* @param _change Whether it is exempted or not
*/
function changeBallotExemptedVotersList(uint256 _ballotId, address _voter, bool _change) external withPerm(ADMIN) {
_changeBallotExemptedVotersList(_ballotId, _voter, _change);
}
/**
* Change the given ballot exempted list (Multi)
* @param _ballotId Given ballot Id
* @param _voters Address of the voter
* @param _changes Whether it is exempted or not
*/
function changeBallotExemptedVotersListMulti(uint256 _ballotId, address[] calldata _voters, bool[] calldata _changes) external withPerm(ADMIN) {
require(_voters.length == _changes.length, "Array length mismatch");
for (uint256 i = 0; i < _voters.length; i++) {
_changeBallotExemptedVotersList(_ballotId, _voters[i], _changes[i]);
}
}
function _changeBallotExemptedVotersList(uint256 _ballotId, address _voter, bool _change) internal {
require(_voter != address(0), "Invalid address");
_validBallotId(_ballotId);
require(ballots[_ballotId].exemptedVoters[_voter] != _change, "No change");
ballots[_ballotId].exemptedVoters[_voter] = _change;
emit ChangedBallotExemptedVotersList(_ballotId, _voter, _change);
}
/**
* Use to check whether the voter is allowed to vote or not
* @param _ballotId The index of the target ballot
* @param _voter Address of the voter
* @return bool
*/
function isVoterAllowed(uint256 _ballotId, address _voter) public view returns(bool) {
bool allowed = (ballots[_ballotId].exemptedVoters[_voter] || (defaultExemptIndex[_voter] != 0));
return !allowed;
}
/**
* @notice Allows the token issuer to set the active stats of a ballot
* @param _ballotId The index of the target ballot
* @param _isActive The bool value of the active stats of the ballot
* @return bool success
*/
function changeBallotStatus(uint256 _ballotId, bool _isActive) external withPerm(ADMIN) {
require(uint64(now) <= ballots[_ballotId].endTime, "Already ended");
require(ballots[_ballotId].isActive != _isActive, "Active state unchanged");
ballots[_ballotId].isActive = _isActive;
emit BallotStatusChanged(_ballotId, _isActive);
}
/**
* @notice Queries the result of a given ballot
* @param _ballotId Id of the target ballot
* @return uint256 voteWeighting
* @return uint256 tieWith
* @return uint256 winningProposal
* @return bool isVotingSucceed
* @return uint256 totalVotes
*/
function getBallotResults(uint256 _ballotId) external view returns (
uint256[] memory voteWeighting,
uint256[] memory tieWith,
uint256 winningProposal,
bool isVotingSucceed,
uint256 totalVotes
) {
if (_ballotId >= ballots.length)
return (new uint256[](0), new uint256[](0), winningProposal, isVotingSucceed, totalVotes);
Ballot storage ballot = ballots[_ballotId];
uint256 i;
uint256 counter = 0;
uint256 maxWeight = 0;
uint256 supplyAtCheckpoint = ISecurityToken(securityToken).totalSupplyAt(ballot.checkpointId);
uint256 quorumWeight = (supplyAtCheckpoint.mul(ballot.quorum)).div(10 ** 18);
voteWeighting = new uint256[](ballot.totalProposals);
for (i = 0; i < ballot.totalProposals; i++) {
voteWeighting[i] = ballot.proposalToVotes[i + 1];
if (maxWeight < ballot.proposalToVotes[i + 1]) {
maxWeight = ballot.proposalToVotes[i + 1];
if (maxWeight >= quorumWeight)
winningProposal = i + 1;
}
}
if (maxWeight >= quorumWeight) {
isVotingSucceed = true;
for (i = 0; i < ballot.totalProposals; i++) {
if (maxWeight == ballot.proposalToVotes[i + 1] && (i + 1) != winningProposal)
counter ++;
}
}
tieWith = new uint256[](counter);
if (counter > 0) {
counter = 0;
for (i = 0; i < ballot.totalProposals; i++) {
if (maxWeight == ballot.proposalToVotes[i + 1] && (i + 1) != winningProposal) {
tieWith[counter] = i + 1;
counter ++;
}
}
}
totalVotes = uint256(ballot.totalVoters);
}
/**
* @notice Get the voted proposal
* @param _ballotId Id of the ballot
* @param _voter Address of the voter
*/
function getSelectedProposal(uint256 _ballotId, address _voter) external view returns(uint256 proposalId) {
if (_ballotId >= ballots.length)
return 0;
return ballots[_ballotId].investorToProposal[_voter];
}
/**
* @notice Get the details of the ballot
* @param _ballotId The index of the target ballot
* @return uint256 quorum
* @return uint256 totalSupplyAtCheckpoint
* @return uint256 checkpointId
* @return uint256 startTime
* @return uint256 endTime
* @return uint256 totalProposals
* @return uint256 totalVoters
* @return bool isActive
*/
function getBallotDetails(uint256 _ballotId) external view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, bool) {
Ballot memory ballot = ballots[_ballotId];
return (
ballot.quorum,
ISecurityToken(securityToken).totalSupplyAt(ballot.checkpointId),
ballot.checkpointId,
ballot.startTime,
ballot.endTime,
ballot.totalProposals,
ballot.totalVoters,
ballot.isActive
);
}
/**
* @notice Return the permissions flag that are associated with STO
* @return bytes32 array
*/
function getPermissions() public view returns(bytes32[] memory) {
bytes32[] memory allPermissions = new bytes32[](1);
allPermissions[0] = ADMIN;
return allPermissions;
}
function _validBallotId(uint256 _ballotId) internal view {
require(ballots.length > _ballotId, "Index out of bound");
}
}
|
Use to check whether the voter is allowed to vote or not _ballotId The index of the target ballot _voter Address of the voter return bool/
|
function isVoterAllowed(uint256 _ballotId, address _voter) public view returns(bool) {
bool allowed = (ballots[_ballotId].exemptedVoters[_voter] || (defaultExemptIndex[_voter] != 0));
return !allowed;
}
| 5,511,009
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './ERC721Enumerable.sol';
import './Strings.sol';
import './INiftyNafty.sol';
import './INiftyNaftyMetadata.sol';
contract NiftyNafty is ERC721Enumerable, INiftyNafty, INiftyNaftyMetadata {
using Strings for uint256;
uint256 private constant startIDFrom=1;// The initial token ID
uint256 public constant COUNT_PRESALE = 250;
uint256 public constant PUBLIC_MAX = 8999;
uint256 public constant GIFT_MAX = 1000;
uint256 public constant PURCHASE_LIMIT = 3;
uint256 public saleMode = 0;//0-none, 1-presale, 2-public
uint256 public PRICE_PRESALE = 0.05 ether;
uint256 public PRICE_WHITE = 0.07 ether;
uint256 public PRICE = 0.08 ether;
bool public isActive = true;
bool public isAllowListActive = false;
string public proof;
uint256 public allowListMaxMint = 3;
uint256 public totalGiftSupply;
uint256 public totalPublicSupply;
uint256 public startDate;
address[] internal _ownersList;
mapping(address => bool) private _allowList;
mapping(address => uint256) private _claimed;
string private _contractURI = '';
string private _tokenBaseURI = '';
string private _tokenRevealedBaseURI = '';
//---------------------------------------------------------------------------------------------------------------new
// Used for random index assignment
mapping(uint256 => uint256) private tokenMatrix;
address public addressDAO;
uint256 public constant DAO_PERCENT = 55;// 1/1000
uint256 private _allBalance;
uint256 private _sentDAO;
bytes32 public lastOperation;
address public lastOwner;
bool public revealed = false;
string public notRevealedUri;
constructor(string memory name, string memory symbol) ERC721(name, symbol) {
_ownersList.push(_msgSender());
}
function updateOwnersList(address[] calldata addresses) external override onlyTwoOwners {
_ownersList = addresses;
}
function onOwnersList(address addr) external view override returns (bool) {
for(uint i = 0; i < _ownersList.length; i++) {
if (_ownersList[i] == addr) {
return true;
}
}
return false;
}
function addToAllowList(address[] calldata addresses) external override onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Can't add the null address");
_allowList[addresses[i]] = true;
_claimed[addresses[i]] > 0 ? _claimed[addresses[i]] : 0;
}
}
function onAllowList(address addr) external view override returns (bool) {
return _allowList[addr];
}
function removeFromAllowList(address[] calldata addresses) external override onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Can't add the null address");
_allowList[addresses[i]] = false;
}
}
function setPricePreSale(uint256 newPrice) external onlyOwner {
PRICE_PRESALE = newPrice;
}
function setPriceWhite(uint256 newPrice) external onlyOwner {
PRICE_WHITE = newPrice;
}
function setPrice(uint256 newPrice) external override onlyOwner {
PRICE = newPrice;
}
function setStartDate(uint256 newDate) external override onlyOwner {
startDate = newDate;
}
function claimedBy(address addr) external view override returns (uint256){
require(addr != address(0), "Can't check the null address");
return _claimed[addr];
}
function purchase(uint256 numberOfTokens) external override payable {
require(block.timestamp > startDate, 'Sale not started');
require(isActive, 'Contract is not active');
require(saleMode>0, 'The sale mode is not enabled');
require(numberOfTokens <= PURCHASE_LIMIT, 'Would exceed PURCHASE_LIMIT');
if (isAllowListActive) {
require(_allowList[msg.sender], 'You are not on the Allow List');
}
//Mechanics of price selection
uint256 Price=PRICE;
if (saleMode == 1) {
Price=PRICE_PRESALE;
}
else
if(_allowList[msg.sender]){
Price=PRICE_WHITE;
}
//optimistic set
uint256 tokenCount=totalPublicSupply;
_allBalance += msg.value;
_claimed[msg.sender] += numberOfTokens;
totalPublicSupply += numberOfTokens;
//Mechanics of determining the end of the pre sale
if (saleMode == 1) {
require(totalPublicSupply <= COUNT_PRESALE, 'All PRESALE tokens have been minted');
if(totalPublicSupply >= COUNT_PRESALE)
saleMode=0;
}
require(_claimed[msg.sender] <= allowListMaxMint, 'Purchase exceeds max allowed');
require(totalPublicSupply <= PUBLIC_MAX, 'Purchase would exceed PUBLIC_MAX');
require(Price * numberOfTokens <= msg.value, 'ETH amount is not sufficient');
for (uint256 i = 0; i < numberOfTokens; i++) {
uint256 tokenId = nextToken(tokenCount);
tokenCount+=1;
_safeMint(msg.sender, tokenId);
}
}
function gift(address[] calldata to) external override onlyTwoOwners {
require(totalGiftSupply + to.length <= GIFT_MAX, 'Not enough tokens left to gift');
uint256 tokenCount=totalGiftSupply;
totalGiftSupply += to.length;
for(uint256 i = 0; i < to.length; i++) {
uint256 tokenId = tokenCount + PUBLIC_MAX + 1 + i;
_safeMint(to[i], tokenId);
}
}
function setIsActive(bool _isActive) external override onlyOwner {
isActive = _isActive;
}
function setIsAllowListActive(bool _isAllowListActive) external override onlyOwner {
isAllowListActive = _isAllowListActive;
}
function setSaleMode(uint256 _Mode) external onlyOwner {
saleMode = _Mode;
}
function setAllowListMaxMint(uint256 maxMint) external override onlyOwner {
allowListMaxMint = maxMint;
}
function setProof(string calldata proofString) external override onlyOwner {
proof = proofString;
}
function withdraw() external override onlyTwoOwners {
require(_ownersList.length > 0, "Can't withdraw where owners list empty");
int256 balance=int256(address(this).balance)-int256(getProfitDAO());
require(balance>0, "Can't withdraw - no funds available");
uint256 part = uint256(balance) / _ownersList.length;
if(part>0)
{
for(uint256 i = 0; i < _ownersList.length; i++) {
payable(_ownersList[i]).transfer(part);
}
}
}
function setContractURI(string calldata URI) external override onlyOwner {
_contractURI = URI;
}
function setBaseURI(string calldata URI) external override onlyOwner {
_tokenBaseURI = URI;
}
function setRevealedBaseURI(string calldata revealedBaseURI) external override onlyOwner {
_tokenRevealedBaseURI = revealedBaseURI;
}
function contractURI() public view override returns (string memory) {
return _contractURI;
}
function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) {
require(_exists(tokenId), 'Token does not exist');
if(revealed == false) {
return notRevealedUri;
}
string memory revealedBaseURI = _tokenRevealedBaseURI;
return bytes(revealedBaseURI).length > 0 ?
string(abi.encodePacked(revealedBaseURI, tokenId.toString(), '.json')) :
_tokenBaseURI;
}
function reveal() public onlyOwner {
revealed = true;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
//---------------------------------------------------------------------------------------------------------------new
function setDAO(address setAddress) external onlyOwner {
require(setAddress != address(0), "Can't check the null address");
addressDAO = setAddress;
}
function withdrawDAO() external onlyTwoOwners {
uint256 ProfitDAO=getProfitDAO();
require(ProfitDAO>0, "Can't withdraw - no funds available");
require(addressDAO!= address(0), "Can't withdraw - DAO not set");
(bool success,) = payable(addressDAO).call{value:ProfitDAO, gas: 100000}("");
if(success)
{
_sentDAO += ProfitDAO;
}
}
function getProfitDAO() public view returns (uint256 ProfitDAO) {
int256 Balance = int256(_allBalance * DAO_PERCENT/1000) - int256(_sentDAO);
if(Balance>0)
ProfitDAO=uint256(Balance);
else
ProfitDAO=0;
}
/// Get the next token ID
/// @dev Randomly gets a new token ID and keeps track of the ones that are still available.
/// @return the next token ID
function nextToken(uint256 tokenCount) internal returns (uint256) {
uint256 maxIndex = PUBLIC_MAX - tokenCount;
uint256 random = uint256(keccak256(
abi.encodePacked(
msg.sender,
block.coinbase,
block.difficulty,
block.gaslimit,
block.timestamp
)
)) % maxIndex;
uint256 value = 0;
if (tokenMatrix[random] == 0) {
// If this matrix position is empty, set the value to the generated random number.
value = random;
} else {
// Otherwise, use the previously stored number from the matrix.
value = tokenMatrix[random];
}
// If the last available tokenID is still unused...
if (tokenMatrix[maxIndex - 1] == 0) {
// ...store that ID in the current matrix position.
tokenMatrix[random] = maxIndex - 1;
} else {
// ...otherwise copy over the stored number to the current matrix position.
tokenMatrix[random] = tokenMatrix[maxIndex - 1];
}
return value + startIDFrom;
}
//---------------------------------------------------------------------------------------------------------MultSig 2/N
// MODIFIERS
/**
* @dev Allows to perform method by any of the owners
*/
modifier onlyOwner {
require(isOwner(), "onlyOwner: caller is not the owner");
_;
}
/**
* @dev Allows to perform method only after many owners call it with the same arguments
*/
modifier onlyTwoOwners {
require(isOwner(), "onlyTwoOwners: caller is not the owner");
bytes32 operation = keccak256(msg.data);
if(_ownersList.length == 1 || (lastOperation == operation && lastOwner != msg.sender))
{
resetVote();
_;
}
else
if(lastOperation != operation || lastOwner == msg.sender)
{
//new vote
lastOperation = operation;
lastOwner = msg.sender;
}
}
/**
* @dev Returns the address of the current owner
*/
function owner() public view virtual returns (address) {
return _ownersList[0];
}
/**
* @dev Returns a list of owners addresses
*/
function owners() public view virtual returns (address [] memory) {
return _ownersList;
}
function isOwner()internal view returns(bool) {
for(uint256 i = 0; i < _ownersList.length; i++)
{
if(_ownersList[i]==msg.sender)
{
return true;
}
}
return false;
}
function resetVote()internal{
lastOperation=0;
lastOwner=address(0);
}
/**
* @dev Allows owners to change their mind by cacnelling vote operations
*/
function cancelVote() public onlyOwner {
resetVote();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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;
interface INiftyNafty {
function updateOwnersList(address[] calldata addresses) external;
function onOwnersList(address addr) external returns (bool);
function addToAllowList(address[] calldata addresses) external;
function onAllowList(address addr) external returns (bool);
function removeFromAllowList(address[] calldata addresses) external;
function claimedBy(address owner) external returns (uint256);
function purchase(uint256 numberOfTokens) external payable;
function gift(address[] calldata to) external;
function setIsActive(bool isActive) external;
function setPrice(uint256 newPrice) external;
//function setMaxTotalSupply(uint256 newCount) external;
function setStartDate(uint256 newDate) external;
function setIsAllowListActive(bool isAllowListActive) external;
function setAllowListMaxMint(uint256 maxMint) external;
function setProof(string memory proofString) external;
function withdraw() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface INiftyNaftyMetadata {
function setContractURI(string calldata URI) external;
function setBaseURI(string calldata URI) external;
function setRevealedBaseURI(string calldata revealedBaseURI) external;
function contractURI() external view returns(string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./IERC721Metadata.sol";
import "./Address.sol";
import "./Context.sol";
import "./Strings.sol";
import "./ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) internal _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Returns the address of the current owner/
|
function owner() public view virtual returns (address) {
return _ownersList[0];
}
| 14,813,829
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "../structs/Payment.sol";
library LessorsLib {
struct Lessors {
mapping (address => Lessor) _lessors;
}
struct Lessor {
address payable owner;
uint256 numOfProperties;
Property[] properties;
}
struct Property {
uint id;
string title;
string description;
string imgUrl;
uint256 montlyPrice;
uint256 depositAmount;
uint256 depositPrice;
address lessor;
address payable tenant;
Payment lastPayment;
uint nextPayment;
bool available;
}
/**
* @dev create new property to this lessor
*/
function createProperty(
Lessors storage lessors,
string memory _title,
string memory _description,
string memory _imgUrl,
uint256 _amount,
uint256 _deposit
) internal returns(Lessor storage lessor)
{
Property memory property;
lessor = lessors._lessors[msg.sender];
property.title = _title;
property.description = _description;
property.imgUrl = _imgUrl;
property.montlyPrice = _amount;
property.depositPrice = _deposit;
property.available = true;
property.lessor = msg.sender;
property.id = lessor.numOfProperties++;
lessor.properties.push(property);
}
/**
* @dev retrieve a lessor property
*/
function getLessors(Lessors storage lessors, address[] memory numOfLessors) view internal returns(Lessor[] memory) {
uint256 numLength = numOfLessors.length;
Lessor[] memory memoryArray = new Lessor[](
numOfLessors.length);
for (uint256 i = 0; i < numLength; i++) {
memoryArray[i] = lessors._lessors[numOfLessors[i]];
}
return memoryArray;
}
/**
* @dev retrieve a lessor property
*/
function getLessor(Lessors storage lessors, address _lessorAddress) view internal returns(Lessor storage) {
return lessors._lessors[_lessorAddress];
}
/**
* @dev retrieve a lessor property
*/
function getLessorProperty(Lessors storage lessors, address _lessorAddress, uint _propertyId) view internal returns(Property memory) {
return lessors._lessors[_lessorAddress].properties[_propertyId];
}
}
|
retrieve a lessor property/
|
function getLessorProperty(Lessors storage lessors, address _lessorAddress, uint _propertyId) view internal returns(Property memory) {
return lessors._lessors[_lessorAddress].properties[_propertyId];
}
| 12,887,126
|
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./Ownable.sol";
contract FlightSuretyData is Ownable {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address[] multiCalls = new address[](0);
uint8 AIRLINE_LENGTH_LIMIT = 5;
//bool isAirlineRegistrationOperational = true;
address private contractOwner; // Account used to deploy contract
address[] enabledAirlines = new address[](0);
bool private operational = true; // Blocks all state changes throughout the contract if false
struct Airline {
bool isRegistered; // Flag for testing existence in mapping
uint256 funding;
bool isFunded;
}
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
string id;
}
// mapping of callers that are authorized to call the contract
mapping(address => uint8) authorizedCaller;
// mapping from airline addresses to their details
mapping(address => Airline) airlines; // All registered airlines
// mapping from flight numbers as strings to flight details
mapping(string => Flight) flights;
// available funds for passangers to widrawl
mapping(address => uint256) credits;
//mapping(address => uint256) funds;
mapping(bytes32 => uint256) flightSurety;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event AuthorizedCaller(address caller);
event DeAuthorizedCaller(address caller);
event CreditInsured(address passenger, string flight, uint256 amount);
event RegisterAirline // Event fired when a new Airline is registered
(
address indexed account // "indexed" keyword indicates that the data should be
// stored as a "topic" in event log data. This makes it
// searchable by event log filters. A maximum of three
// parameters may use the indexed keyword per event.
);
event RegisterFlight // Event fired when a new Airline is registered
(
string indexed account // "indexed" keyword indicates that the data should be
// stored as a "topic" in event log data. This makes it
// searchable by event log filters. A maximum of three
// parameters may use the indexed keyword per event.
);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor() public
{
contractOwner = msg.sender;
//adds first airline upon its constructor
airlines[contractOwner] = Airline({
isRegistered: true,
//account: contractOwner,
//ownership: 0,
funding: 0,
isFunded: false
});
emit RegisterAirline(contractOwner); // Log airline registration event
}
modifier requireIsCallerAuthorized()
{
require(authorizedCaller[msg.sender] == 1, "Caller is not authorized to call this function");
_;
}
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireRegisteredAirline(address caller){
require(airlines[caller].isRegistered, "Caller is not registered");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/* authorize caller */
function authorizeCaller(address _caller) public onlyOwner returns(bool)
{
authorizedCaller[_caller] = 1;
emit AuthorizedCaller(_caller);
return true;
}
/* deauthorize caller */
function deAuthorizeCaller(address _caller) public onlyOwner returns(bool)
{
authorizedCaller[_caller] = 0;
emit DeAuthorizedCaller(_caller);
return true;
}
function setOperatingStatus(bool mode, address sender) external requireContractOwner
{
require(mode != operational, "New mode must be different from existing mode");
bool isDuplicate = false;
for(uint c=0; c<multiCalls.length; c++) {
if (multiCalls[c] == sender) {
isDuplicate = true;
break;
}
}
require(!isDuplicate, "Caller has already called this function.");
multiCalls.push(sender);
if (multiCalls.length >= (enabledAirlines.length.div(2))) {
operational = mode;
multiCalls = new address[](0);
}
}
function isOperational() external view returns(bool)
{
return operational;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
function registerAirline(address airline, address registeringAirline) external requireIsCallerAuthorized requireIsOperational
{
// airline cannot be registered twice
require(!airlines[airline].isRegistered, "Airline already registered");
// only registered airlines can register other airlines
require(airlines[registeringAirline].isRegistered, "Airline trying to add no exists");
require(airlines[registeringAirline].isFunded, "Airlines need to be funded to be able register other airlines");
// up to the forth airline can be added without multiparty consensus
if (enabledAirlines.length < 4){
airlines[airline] = Airline({isRegistered: true, funding: 0, isFunded: false});
}
// else consensus is needed
else {
// check if registeringAirline airline has not voted already
bool isDuplicate = false;
for(uint c=0; c<multiCalls.length; c++) {
if (multiCalls[c] == registeringAirline) {
isDuplicate = true;
break;
}
}
require(!isDuplicate, "Caller has already voted");
// add registeringAirline to the list of airlines that have already voted.
multiCalls.push(registeringAirline);
// if half of the airlines have voted, the new airline is accepted
if (multiCalls.length == (enabledAirlines.length.div(2))) {
// new airline is registered without funding
airlines[airline] = Airline({isRegistered: true, funding: 0, isFunded: false});
// the voters array is reset
multiCalls = new address[](0);
//emit RegisterAirline(airline); // Log airline registration event
}
}
}
function registerFlight(address airline, string flightId, uint256 timestamp) external
requireIsCallerAuthorized
requireIsOperational
{
require(airlines[airline].isRegistered, "Airline does not exists");
flights[flightId] = Flight({
isRegistered: true,
statusCode: 0,
updatedTimestamp: timestamp,
airline: airline,
id: flightId
});
emit RegisterFlight(flightId); // Log airline registration event
}
function isAirline(address airline) external view requireIsCallerAuthorized requireIsOperational returns(bool)
{
return airlines[airline].isRegistered;
}
function getActiveAirlines() external view requireIsCallerAuthorized requireIsOperational returns(address[])
{
return enabledAirlines;
}
// method for buying insurance
function buy(address passenger, string flight) external payable requireIsOperational
{
// it's not possible to buy insurance for more tha 1 ETH
require(msg.value <= 1 ether, "Surety value cannot be higher than 1 ether");
// get's hash of passenger and flight
bytes32 key = keccak256(abi.encodePacked(passenger, flight));
require(flightSurety[key] == 0, "Passenger already bought surety on this flight");
flightSurety[key] = msg.value;
}
// returns the amount of insurance bought by passenger for flight
function flightSuretyInfo(address passenger, string flight) external requireIsCallerAuthorized requireIsOperational returns(uint256)
{
bytes32 key = keccak256(abi.encodePacked(passenger, flight));
// require(flightSurety[key] > 0, "Passenger does not have surety for this flight");
return flightSurety[key];
}
// function crediting passengers indirectly. credit does not go directly to their walled
function creditPassenger(address passenger, string flight) external payable requireIsCallerAuthorized
requireIsOperational
{
// get hash for passenger and flight
bytes32 key = keccak256(abi.encodePacked(passenger, flight));
// get insured amount
uint256 insuredAmount = flightSurety[key];
require(insuredAmount > 0, "No insurance was purchased by this passenger for this flight");
//Requirement #2
// calculate amount to credit from the insurance bought
uint256 amountToCredit = insuredAmount.mul(15).div(10);
uint256 currentCredit = credits[passenger];
// adds the amount to credit to the passenger existing credit.
credits[passenger] = currentCredit.add(amountToCredit);
emit CreditInsured(passenger, flight, amountToCredit);
}
function withdraw(address passenger, uint256 amount) external requireIsCallerAuthorized
requireIsOperational
{
// get credits for passenger
uint256 credit = credits[passenger];
// requires there should be some credit
require(credit > 0, "There is no credits to withdraw");
// transfer credit to passenger
passenger.transfer(credit);
// after withdrawl credits for passenger is reset to 0
credits[passenger] = 0;
}
function fund(address airline) public payable requireIsCallerAuthorized requireIsOperational
{
require(msg.value >= 10, "Minimum amount is 10");
require(airlines[airline].isRegistered, "Airline not registered");
uint256 currentAmount = airlines[airline].funding;
airline.transfer(msg.value);
// if airline has not been funded yet
if (!airlines[airline].isFunded) {
// declares it as funded
airlines[airline].isFunded = true;
// adds it to the list of airlines that can participate in the contract
enabledAirlines.push(airline);
}
airlines[airline].funding = currentAmount.add(msg.value);
}
function fetchFunding(address airline) external view requireIsOperational requireIsCallerAuthorized returns (uint256){
return airlines[airline].funding;
}
function isFunded(address airline) external view requireIsOperational requireIsCallerAuthorized returns (bool){
return airlines[airline].isFunded;
}
function getNumberOfRegisteredAirlines() requireIsOperational requireIsCallerAuthorized external view returns (uint256) {
return enabledAirlines.length;
}
function getPassengerCredit(address passenger) requireIsOperational requireIsCallerAuthorized external view
returns (uint256){
return credits[passenger];
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
requireIsCallerAuthorized
requireIsOperational
{
fund(msg.sender);
}
}
|
returns the amount of insurance bought by passenger for flight require(flightSurety[key] > 0, "Passenger does not have surety for this flight");
|
function flightSuretyInfo(address passenger, string flight) external requireIsCallerAuthorized requireIsOperational returns(uint256)
{
bytes32 key = keccak256(abi.encodePacked(passenger, flight));
return flightSurety[key];
}
| 12,539,381
|
/**
*Submitted for verification at Etherscan.io on 2021-05-20
*/
/*
.'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''..
.;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,.
';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,.
';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,.
...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''..
.,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. .....
.;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,..
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. ....
..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,.
..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'.
...'.. .';;;;;;;;;;;;;;,,,'.
...............
*/
// https://github.com/trusttoken/smart-contracts
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* // importANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Dependency file: @openzeppelin/contracts/math/SafeMath.sol
// pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Dependency file: contracts/trusttoken/interface/IBurnableERC20.sol
// pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IBurnableERC20 is IERC20 {
function burn(uint256 amount) external;
}
// Dependency file: contracts/governance/interface/IVoteToken.sol
// pragma solidity ^0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVoteToken {
function delegate(address delegatee) external;
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
function getCurrentVotes(address account) external view returns (uint96);
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96);
}
interface IVoteTokenWithERC20 is IVoteToken, IERC20 {}
// Dependency file: @openzeppelin/contracts/GSN/Context.sol
// pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Dependency file: contracts/common/Initializable.sol
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol
// Added public isInitialized() view of private initialized bool.
// pragma solidity 0.6.10;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly {
cs := extcodesize(self)
}
return cs == 0;
}
/**
* @dev Return true if and only if the contract has been initialized
* @return whether the contract has been initialized
*/
function isInitialized() public view returns (bool) {
return initialized;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// Dependency file: contracts/common/UpgradeableOwnable.sol
// pragma solidity 0.6.10;
// import {Context} from "@openzeppelin/contracts/GSN/Context.sol";
// import {Initializable} from "contracts/common/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// Dependency file: contracts/truefi/interface/IArbitraryDistributor.sol
// pragma solidity 0.6.10;
interface IArbitraryDistributor {
function amount() external returns (uint256);
function remaining() external returns (uint256);
function beneficiary() external returns (address);
function distribute(uint256 _amount) external;
function empty() external;
}
// Dependency file: contracts/truefi/interface/ILoanFactory.sol
// pragma solidity 0.6.10;
interface ILoanFactory {
function createLoanToken(
uint256 _amount,
uint256 _term,
uint256 _apy
) external;
function isLoanToken(address) external view returns (bool);
}
// Dependency file: contracts/truefi/interface/ILoanToken.sol
// pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ILoanToken is IERC20 {
enum Status {Awaiting, Funded, Withdrawn, Settled, Defaulted, Liquidated}
function borrower() external view returns (address);
function amount() external view returns (uint256);
function term() external view returns (uint256);
function apy() external view returns (uint256);
function start() external view returns (uint256);
function lender() external view returns (address);
function debt() external view returns (uint256);
function profit() external view returns (uint256);
function status() external view returns (Status);
function borrowerFee() external view returns (uint256);
function receivedAmount() external view returns (uint256);
function isLoanToken() external pure returns (bool);
function getParameters()
external
view
returns (
uint256,
uint256,
uint256
);
function fund() external;
function withdraw(address _beneficiary) external;
function settle() external;
function enterDefault() external;
function liquidate() external;
function redeem(uint256 _amount) external;
function repay(address _sender, uint256 _amount) external;
function repayInFull(address _sender) external;
function reclaim() external;
function allowTransfer(address account, bool _status) external;
function repaid() external view returns (uint256);
function isRepaid() external view returns (bool);
function balance() external view returns (uint256);
function value(uint256 _balance) external view returns (uint256);
function currencyToken() external view returns (IERC20);
function version() external pure returns (uint8);
}
// Dependency file: contracts/truefi/interface/ITrueFiPool.sol
// pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* TruePool is an ERC20 which represents a share of a pool
*
* This contract can be used to wrap opportunities to be compatible
* with TrueFi and allow users to directly opt-in through the TUSD contract
*
* Each TruePool is also a staking opportunity for TRU
*/
interface ITrueFiPool is IERC20 {
/// @dev pool token (TUSD)
function currencyToken() external view returns (IERC20);
/// @dev stake token (TRU)
function stakeToken() external view returns (IERC20);
/**
* @dev join pool
* 1. Transfer TUSD from sender
* 2. Mint pool tokens based on value to sender
*/
function join(uint256 amount) external;
/**
* @dev exit pool
* 1. Transfer pool tokens from sender
* 2. Burn pool tokens
* 3. Transfer value of pool tokens in TUSD to sender
*/
function exit(uint256 amount) external;
/**
* @dev borrow from pool
* 1. Transfer TUSD to sender
* 2. Only lending pool should be allowed to call this
*/
function borrow(uint256 amount, uint256 fee) external;
/**
* @dev join pool
* 1. Transfer TUSD from sender
* 2. Only lending pool should be allowed to call this
*/
function repay(uint256 amount) external;
}
// Dependency file: contracts/truefi/interface/ITrueRatingAgencyV2.sol
// pragma solidity 0.6.10;
interface ITrueRatingAgencyV2 {
function getResults(address id)
external
view
returns (
uint256,
uint256,
uint256
);
function submit(address id) external;
function retract(address id) external;
function resetCastRatings(address id) external;
function yes(address id) external;
function no(address id) external;
function claim(address id, address voter) external;
}
// Root file: contracts/truefi/TrueRatingAgencyV2.sol
pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
// import {IBurnableERC20} from "contracts/trusttoken/interface/IBurnableERC20.sol";
// import {IVoteTokenWithERC20} from "contracts/governance/interface/IVoteToken.sol";
// import {Ownable} from "contracts/common/UpgradeableOwnable.sol";
// import {IArbitraryDistributor} from "contracts/truefi/interface/IArbitraryDistributor.sol";
// import {ILoanFactory} from "contracts/truefi/interface/ILoanFactory.sol";
// import {ILoanToken} from "contracts/truefi/interface/ILoanToken.sol";
// import {ITrueFiPool} from "contracts/truefi/interface/ITrueFiPool.sol";
// import {ITrueRatingAgencyV2} from "contracts/truefi/interface/ITrueRatingAgencyV2.sol";
/**
* @title TrueRatingAgencyV2
* @dev Credit prediction market for LoanTokens
*
* TrueFi uses use a prediction market to signal how risky a loan is.
* The Credit Prediction Market estimates the likelihood of a loan defaulting.
* Any stkTRU holder can rate YES or NO and stake TRU as collateral on their rate.
* Voting weight is equal to delegated governance power (see VoteToken.sol)
* If a loan is funded, TRU is rewarded as incentive for participation
* Rating stkTRU in the prediction market allows raters to earn and claim TRU
* incentive when the loan is approved
*
* Voting Lifecycle:
* - Borrowers can apply for loans at any time by deploying a LoanToken
* - LoanTokens are registered with the prediction market contract
* - Once registered, stkTRU holders can rate at any time
*
* States:
* Void: Rated loan is invalid
* Pending: Waiting to be funded
* Retracted: Rating has been cancelled
* Running: Rated loan has been funded
* Settled: Rated loan has been paid back in full
* Defaulted: Rated loan has not been paid back in full
* Liquidated: Rated loan has defaulted and stakers have been liquidated
*/
contract TrueRatingAgencyV2 is ITrueRatingAgencyV2, Ownable {
using SafeMath for uint256;
enum LoanStatus {Void, Pending, Retracted, Running, Settled, Defaulted, Liquidated}
struct Loan {
address creator;
uint256 timestamp;
uint256 blockNumber;
mapping(bool => uint256) prediction;
mapping(address => mapping(bool => uint256)) ratings;
mapping(address => uint256) claimed;
uint256 reward;
}
// TRU is 1e8 decimals
uint256 private constant TOKEN_PRECISION_DIFFERENCE = 10**10;
// ================ WARNING ==================
// ===== THIS CONTRACT IS INITIALIZABLE ======
// === STORAGE VARIABLES ARE DECLARED BELOW ==
// REMOVAL OR REORDER OF VARIABLES WILL RESULT
// ========= IN STORAGE CORRUPTION ===========
mapping(address => bool) public allowedSubmitters;
mapping(address => Loan) public loans;
IBurnableERC20 public TRU;
IVoteTokenWithERC20 public stkTRU;
IArbitraryDistributor public distributor;
ILoanFactory public factory;
/**
* @dev % multiplied by 100. e.g. 10.5% = 1050
*/
uint256 public ratersRewardFactor;
// reward multiplier for raters
uint256 public rewardMultiplier;
// are submissions paused?
bool public submissionPauseStatus;
mapping(address => bool) public canChangeAllowance;
// ======= STORAGE DECLARATION END ============
event CanChangeAllowanceChanged(address indexed who, bool status);
event Allowed(address indexed who, bool status);
event RatersRewardFactorChanged(uint256 ratersRewardFactor);
event LoanSubmitted(address id);
event LoanRetracted(address id);
event Rated(address loanToken, address rater, bool choice, uint256 stake);
event Withdrawn(address loanToken, address rater, uint256 stake, uint256 received, uint256 burned);
event RewardMultiplierChanged(uint256 newRewardMultiplier);
event Claimed(address loanToken, address rater, uint256 claimedReward);
event SubmissionPauseStatusChanged(bool status);
event LoanFactoryChanged(address newLoanFactory);
/**
* @dev Only whitelisted borrowers can submit for credit ratings
*/
modifier onlyAllowedSubmitters() {
require(allowedSubmitters[msg.sender], "TrueRatingAgencyV2: Sender is not allowed to submit");
_;
}
/**
* @dev Only loan submitter can perform certain actions
*/
modifier onlyCreator(address id) {
require(loans[id].creator == msg.sender, "TrueRatingAgencyV2: Not sender's loan");
_;
}
/**
* @dev Cannot submit the same loan multiple times
*/
modifier onlyNotExistingLoans(address id) {
require(status(id) == LoanStatus.Void, "TrueRatingAgencyV2: Loan was already created");
_;
}
/**
* @dev Only loans in Pending state
*/
modifier onlyPendingLoans(address id) {
require(status(id) == LoanStatus.Pending, "TrueRatingAgencyV2: Loan is not currently pending");
_;
}
/**
* @dev Only loans that have been funded
*/
modifier onlyFundedLoans(address id) {
require(status(id) >= LoanStatus.Running, "TrueRatingAgencyV2: Loan was not funded");
_;
}
/**
* @dev Initialize Rating Agency
* Distributor contract decides how much TRU is rewarded to stakers
* @param _TRU TRU contract
* @param _distributor Distributor contract
* @param _factory Factory contract for deploying tokens
*/
function initialize(
IBurnableERC20 _TRU,
IVoteTokenWithERC20 _stkTRU,
IArbitraryDistributor _distributor,
ILoanFactory _factory
) public initializer {
require(address(this) == _distributor.beneficiary(), "TrueRatingAgencyV2: Invalid distributor beneficiary");
Ownable.initialize();
TRU = _TRU;
stkTRU = _stkTRU;
distributor = _distributor;
factory = _factory;
ratersRewardFactor = 10000;
}
/**
* @dev Set new loan factory.
* @param _factory New LoanFactory contract address
*/
function setLoanFactory(ILoanFactory _factory) external onlyOwner {
factory = _factory;
emit LoanFactoryChanged(address(_factory));
}
/**
* @dev Set rater reward factor.
* Reward factor decides what percentage of rewarded TRU is goes to raters
*/
function setRatersRewardFactor(uint256 newRatersRewardFactor) external onlyOwner {
require(newRatersRewardFactor <= 10000, "TrueRatingAgencyV2: Raters reward factor cannot be greater than 100%");
ratersRewardFactor = newRatersRewardFactor;
emit RatersRewardFactorChanged(newRatersRewardFactor);
}
/**
* @dev Set reward multiplier.
* Reward multiplier increases reward for TRU stakers
*/
function setRewardMultiplier(uint256 newRewardMultiplier) external onlyOwner {
rewardMultiplier = newRewardMultiplier;
emit RewardMultiplierChanged(newRewardMultiplier);
}
/**
* @dev Get number of NO ratings for a specific account and loan
* @param id Loan ID
* @param rater Rater account
*/
function getNoRate(address id, address rater) public view returns (uint256) {
return loans[id].ratings[rater][false];
}
/**
* @dev Get number of YES ratings for a specific account and loan
* @param id Loan ID
* @param rater Rater account
*/
function getYesRate(address id, address rater) public view returns (uint256) {
return loans[id].ratings[rater][true];
}
/**
* @dev Get total NO ratings for a specific loan
* @param id Loan ID
*/
function getTotalNoRatings(address id) public view returns (uint256) {
return loans[id].prediction[false];
}
/**
* @dev Get total YES ratings for a specific loan
* @param id Loan ID
*/
function getTotalYesRatings(address id) public view returns (uint256) {
return loans[id].prediction[true];
}
/**
* @dev Get timestamp at which voting started for a specific loan
* @param id Loan ID
*/
function getVotingStart(address id) public view returns (uint256) {
return loans[id].timestamp;
}
/**
* @dev Get current results for a specific loan
* @param id Loan ID
* @return (start_time, total_no, total_yes)
*/
function getResults(address id)
external
override
view
returns (
uint256,
uint256,
uint256
)
{
return (getVotingStart(id), getTotalNoRatings(id), getTotalYesRatings(id));
}
/**
* @dev Allows addresses to whitelist borrowers
*/
function allowChangingAllowances(address who, bool status) external onlyOwner {
canChangeAllowance[who] = status;
emit CanChangeAllowanceChanged(who, status);
}
/**
* @dev Whitelist borrowers to submit loans for rating
* @param who Account to whitelist
* @param status Flag to whitelist accounts
*/
function allow(address who, bool status) external {
require(canChangeAllowance[msg.sender], "TrueFiPool: Cannot change allowances");
allowedSubmitters[who] = status;
emit Allowed(who, status);
}
/**
* @dev Pause submitting loans for rating
* @param status Flag of the status
*/
function pauseSubmissions(bool status) public onlyOwner {
submissionPauseStatus = status;
emit SubmissionPauseStatusChanged(status);
}
/**
* @dev Submit a loan for rating
* Cannot submit the same loan twice
* @param id Loan ID
*/
function submit(address id) external override onlyAllowedSubmitters onlyNotExistingLoans(id) {
require(!submissionPauseStatus, "TrueRatingAgencyV2: New submissions are paused");
require(ILoanToken(id).borrower() == msg.sender, "TrueRatingAgencyV2: Sender is not borrower");
require(factory.isLoanToken(id), "TrueRatingAgencyV2: Only LoanTokens created via LoanFactory are supported");
loans[id] = Loan({creator: msg.sender, timestamp: block.timestamp, blockNumber: block.number, reward: 0});
emit LoanSubmitted(id);
}
/**
* @dev Remove Loan from rating agency
* Can only be retracted by loan creator
* @param id Loan ID
*/
function retract(address id) external override onlyPendingLoans(id) onlyCreator(id) {
loans[id].creator = address(0);
loans[id].prediction[true] = 0;
loans[id].prediction[false] = 0;
emit LoanRetracted(id);
}
/**
* @dev Rate on a loan by staking TRU
* @param id Loan ID
* @param choice Rater choice. false = NO, true = YES
*/
function rate(address id, bool choice) internal {
uint256 stake = stkTRU.getPriorVotes(msg.sender, loans[id].blockNumber);
require(stake > 0, "TrueRatingAgencyV2: Cannot rate with empty balance");
resetCastRatings(id);
loans[id].prediction[choice] = loans[id].prediction[choice].add(stake);
loans[id].ratings[msg.sender][choice] = loans[id].ratings[msg.sender][choice].add(stake);
emit Rated(id, msg.sender, choice, stake);
}
/**
* @dev Internal function to help reset ratings
* @param id Loan ID
* @param choice Boolean representing choice
*/
function _resetCastRatings(address id, bool choice) internal {
loans[id].prediction[choice] = loans[id].prediction[choice].sub(loans[id].ratings[msg.sender][choice]);
loans[id].ratings[msg.sender][choice] = 0;
}
/**
* @dev Cancel ratings of msg.sender
* @param id ID to cancel ratings for
*/
function resetCastRatings(address id) public override onlyPendingLoans(id) {
if (getYesRate(id, msg.sender) > 0) {
_resetCastRatings(id, true);
} else if (getNoRate(id, msg.sender) > 0) {
_resetCastRatings(id, false);
}
}
/**
* @dev Rate YES on a loan by staking TRU
* @param id Loan ID
*/
function yes(address id) external override onlyPendingLoans(id) {
rate(id, true);
}
/**
* @dev Rate NO on a loan by staking TRU
* @param id Loan ID
*/
function no(address id) external override onlyPendingLoans(id) {
rate(id, false);
}
/**
* @dev Internal view to convert values to 8 decimals precision
* @param input Value to convert to TRU precision
* @return output TRU amount
*/
function toTRU(uint256 input) internal pure returns (uint256 output) {
output = input.div(TOKEN_PRECISION_DIFFERENCE);
}
/**
* @dev Update total TRU reward for a Loan
* Reward is divided proportionally based on # TRU staked
* chi = (TRU remaining in distributor) / (Total TRU allocated for distribution)
* interest = (loan APY * term * principal)
* R = Total Reward = (interest * chi * rewardFactor)
* @param id Loan ID
*/
modifier calculateTotalReward(address id) {
if (loans[id].reward == 0) {
uint256 interest = ILoanToken(id).profit();
// calculate reward
// prettier-ignore
uint256 totalReward = toTRU(
interest
.mul(distributor.remaining())
.mul(rewardMultiplier)
.div(distributor.amount())
);
uint256 ratersReward = totalReward.mul(ratersRewardFactor).div(10000);
loans[id].reward = ratersReward;
if (totalReward > 0) {
distributor.distribute(totalReward);
TRU.transfer(address(stkTRU), totalReward.sub(ratersReward));
}
}
_;
}
/**
* @dev Claim TRU rewards for raters
* - Only can claim TRU rewards for funded loans
* - Claimed automatically when a user withdraws stake
*
* chi = (TRU remaining in distributor) / (Total TRU allocated for distribution)
* interest = (loan APY * term * principal)
* R = Total Reward = (interest * chi)
* R is distributed to raters based on their proportion of ratings/total_ratings
*
* Claimable reward = R x (current time / total time)
* * (account TRU staked / total TRU staked) - (amount claimed)
*
* @param id Loan ID
* @param rater Rater account
*/
function claim(address id, address rater) external override onlyFundedLoans(id) calculateTotalReward(id) {
uint256 claimableRewards = claimable(id, rater);
if (claimableRewards > 0) {
// track amount of claimed tokens
loans[id].claimed[rater] = loans[id].claimed[rater].add(claimableRewards);
// transfer tokens
require(TRU.transfer(rater, claimableRewards));
emit Claimed(id, rater, claimableRewards);
}
}
/**
* @dev Get amount claimed for loan ID and rater address
* @param id Loan ID
* @param rater Rater address
* @return Amount claimed for id and address
*/
function claimed(address id, address rater) external view returns (uint256) {
return loans[id].claimed[rater];
}
/**
* @dev Get amount claimable for loan ID and rater address
* @param id Loan ID
* @param rater Rater address
* @return Amount claimable for id and address
*/
function claimable(address id, address rater) public view returns (uint256) {
if (status(id) < LoanStatus.Running) {
return 0;
}
// calculate how many tokens user can claim
// claimable = stakedByRater / totalStaked
uint256 stakedByRater = loans[id].ratings[rater][false].add(loans[id].ratings[rater][true]);
uint256 totalStaked = loans[id].prediction[false].add(loans[id].prediction[true]);
// calculate claimable rewards at current time
uint256 totalClaimable = loans[id].reward.mul(stakedByRater).div(totalStaked);
return totalClaimable.sub(loans[id].claimed[rater]);
}
/**
* @dev Get status for a specific loan
* We rely on correct implementation of LoanToken
* @param id Loan ID
* @return Status of loan
*/
function status(address id) public view returns (LoanStatus) {
Loan storage loan = loans[id];
// Void loan doesn't exist because timestamp is zero
if (loan.creator == address(0) && loan.timestamp == 0) {
return LoanStatus.Void;
}
// Retracted loan was cancelled by borrower
if (loan.creator == address(0) && loan.timestamp != 0) {
return LoanStatus.Retracted;
}
// get internal status
ILoanToken.Status loanInternalStatus = ILoanToken(id).status();
// Running is Funded || Withdrawn
if (loanInternalStatus == ILoanToken.Status.Funded || loanInternalStatus == ILoanToken.Status.Withdrawn) {
return LoanStatus.Running;
}
// Settled has been paid back in full and past term
if (loanInternalStatus == ILoanToken.Status.Settled) {
return LoanStatus.Settled;
}
// Defaulted has not been paid back in full and past term
if (loanInternalStatus == ILoanToken.Status.Defaulted) {
return LoanStatus.Defaulted;
}
// Liquidated is same as defaulted and stakers have been liquidated
if (loanInternalStatus == ILoanToken.Status.Liquidated) {
return LoanStatus.Liquidated;
}
// otherwise return Pending
return LoanStatus.Pending;
}
}
|
Whitelist borrowers to submit loans for rating who Account to whitelist status Flag to whitelist accounts/
|
function allow(address who, bool status) external {
require(canChangeAllowance[msg.sender], "TrueFiPool: Cannot change allowances");
allowedSubmitters[who] = status;
emit Allowed(who, status);
}
| 2,058,513
|
./full_match/1/0x5478a4e605D7AA798dC70eCD0A1C3299aaeaFDD7/sources/contracts/libraries/IntegralMath.sol
|
does not revert on overflow
|
function unsafeAdd(uint256 x, uint256 y) internal pure returns (uint256) { unchecked {
return x + y;
}}
| 4,961,904
|
./full_match/4/0xbF9005A19e347541F7aE273c512969110A339af8/sources/contracts/Workshop.sol
|
Cannot be undone./
|
function freeze() public onlyOwner {
frozen = true;
}
| 13,293,403
|
pragma solidity ^0.4.21;
contract ERC721 {
// Required methods
function approve(address _to, uint256 _tokenId) public;
function balanceOf(address _owner) public view returns (uint256 balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint256 _tokenId) public view returns (address addr);
function takeOwnership(uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 tokenId);
event Approval(address indexed owner, address indexed approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId);
// function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract CountryJackpot is ERC721, Ownable{
using SafeMath for uint256;
/// @dev The TokenSold event is fired whenever a token is sold.
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name);
/// @dev Transfer event as defined in current draft of ERC721.
event Transfer(address from, address to, uint256 tokenId);
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "EtherCup2018"; // solhint-disable-line
string public constant SYMBOL = "EthCup"; // solhint-disable-line
//starting price for country token
uint256 private startingPrice = 0.01 ether;
//step limits to increase purchase price of token effectively
uint256 private firstStepLimit = 1 ether;
uint256 private secondStepLimit = 3 ether;
uint256 private thirdStepLimit = 10 ether;
//Final Jackpot value, when all buying/betting closes
uint256 private finalJackpotValue = 0;
//Flag to show if the Jackpot has completed
bool public jackpotCompleted = false;
/*** DATATYPES ***/
struct Country {
string name;
}
Country[] private countries;
/// @dev A mapping from country IDs to the address that owns them. All countries have some valid owner address.
mapping (uint256 => address) public countryIndexToOwner;
// A mapping from country id to address to show if the Country approved for transfer
mapping (uint256 => address) public countryIndexToApproved;
// A mapping from country id to ranks to show what rank of the Country
mapping (uint256 => uint256) public countryToRank;
//A mapping from country id to price to store the last purchase price of a country
mapping (uint256 => uint256) private countryToLastPrice;
// A mapping from country id to boolean which checks if the user has claimed jackpot for his country token
mapping (uint256 => bool) public jackpotClaimedForCountry;
// A mapping from ranks to the ether to be won from the jackpot.
mapping (uint256 => uint256) public rankShare;
// Counts how many tokens a user has.
mapping (address => uint256) private ownershipTokenCount;
// @dev A mapping from countryIds to the price of the token.
mapping (uint256 => uint256) private countryIndexToPrice;
//@notice Constructor that setups the share for each rank
function CountryJackpot() public{
rankShare[1] = 76;
rankShare[2] = 56;
rankShare[3] = 48;
rankShare[4] = 44;
rankShare[5] = 32;
rankShare[6] = 24;
rankShare[7] = 16;
}
//@notice Aprrove the transfer of token. A user must own the token to approve it
function approve( address _to, uint256 _tokenId) public {
// Caller must own token.
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
countryIndexToApproved[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
//@notice Get count of how many tokens an address has
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
//@notice Create a country with a name, called only by the owner
function createCountry(string _name) public onlyOwner{
_createCountry(_name, startingPrice);
}
//@notice An address can claim his win from the jackpot after the jackpot is completed
function getEther(uint256 _countryIndex) public {
require(countryIndexToOwner[_countryIndex] == msg.sender);
require(jackpotCompleted);
require(countryToRank[_countryIndex] != 0);
require(!jackpotClaimedForCountry[_countryIndex]);
jackpotClaimedForCountry[_countryIndex] = true;
uint256 _rankShare = rankShare[countryToRank[_countryIndex]];
uint256 amount = ((finalJackpotValue).mul(_rankShare)).div(1000);
msg.sender.transfer(amount);
}
//@notice Get complete information about a country token
function getCountry(uint256 _tokenId) public view returns (
string ,
uint256 ,
address ,
uint256
) {
Country storage country = countries[_tokenId];
string memory countryName = country.name;
uint256 sellingPrice = countryIndexToPrice[_tokenId];
uint256 rank = countryToRank[_tokenId];
address owner = countryIndexToOwner[_tokenId];
return (countryName, sellingPrice, owner, rank);
}
//@notice Get the current balance of the contract.
function getContractBalance() public view returns(uint256) {
return (address(this).balance);
}
//@notice Get the total jackpot value, which is contract balance if the jackpot is not completed.Else
//its retrieved from variable jackpotCompleted
function getJackpotTotalValue() public view returns(uint256) {
if(jackpotCompleted){
return finalJackpotValue;
} else{
return address(this).balance;
}
}
function implementsERC721() public pure returns (bool) {
return true;
}
/// @dev Required for ERC-721 compliance.
function name() public pure returns (string) {
return NAME;
}
//@notice Get the owner of a country token
/// For querying owner of token
/// @param _tokenId The tokenID for owner inquiry
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
public
view
returns (address)
{
address owner = countryIndexToOwner[_tokenId];
return (owner);
}
//@dev this function is required to recieve funds
function () payable {
}
//@notice Allows someone to send ether and obtain a country token
function purchase(uint256 _tokenId) public payable {
require(!jackpotCompleted);
require(msg.sender != owner);
address oldOwner = countryIndexToOwner[_tokenId];
address newOwner = msg.sender;
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= sellingPrice);
uint256 sellingPrice = countryIndexToPrice[_tokenId];
uint256 lastSellingPrice = countryToLastPrice[_tokenId];
// Update prices
if (sellingPrice.mul(2) < firstStepLimit) {
// first stage
countryIndexToPrice[_tokenId] = sellingPrice.mul(2);
} else if (sellingPrice.mul(4).div(10) < secondStepLimit) {
// second stage
countryIndexToPrice[_tokenId] = sellingPrice.add(sellingPrice.mul(4).div(10));
} else if(sellingPrice.mul(2).div(10) < thirdStepLimit){
// third stage
countryIndexToPrice[_tokenId] = sellingPrice.add(sellingPrice.mul(2).div(10));
}else {
// fourth stage
countryIndexToPrice[_tokenId] = sellingPrice.add(sellingPrice.mul(15).div(100));
}
_transfer(oldOwner, newOwner, _tokenId);
//update last price to current selling price
countryToLastPrice[_tokenId] = sellingPrice;
// Pay previous tokenOwner if owner is not initial creator of country
if (oldOwner != owner) {
uint256 priceDifference = sellingPrice.sub(lastSellingPrice);
uint256 oldOwnerPayment = lastSellingPrice.add(priceDifference.sub(priceDifference.div(2)));
oldOwner.transfer(oldOwnerPayment);
}
emit TokenSold(_tokenId, sellingPrice, countryIndexToPrice[_tokenId], oldOwner, newOwner, countries[_tokenId].name);
uint256 purchaseExcess = msg.value.sub(sellingPrice);
msg.sender.transfer(purchaseExcess);
}
//@notice set country rank by providing index, country name and rank
function setCountryRank(uint256 _tokenId, string _name, uint256 _rank) public onlyOwner{
require(_compareStrings(countries[_tokenId].name, _name));
countryToRank[_tokenId] = _rank;
}
///@notice set jackpotComplete to true and transfer 20 percent share of jackpot to owner
function setJackpotCompleted() public onlyOwner{
jackpotCompleted = true;
finalJackpotValue = address(this).balance;
uint256 jackpotShare = ((address(this).balance).mul(20)).div(100);
msg.sender.transfer(jackpotShare);
}
/// @dev Required for ERC-721 compliance.
function symbol() public pure returns (string) {
return SYMBOL;
}
/// @notice Allow pre-approved user to take ownership of a token
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint256 _tokenId) public {
address newOwner = msg.sender;
address oldOwner = countryIndexToOwner[_tokenId];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure transfer is approved
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
/// @notice Get all tokens of a particular address
function tokensOfOwner(address _owner) public 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 totalCountries = totalSupply();
uint256 resultIndex = 0;
uint256 countryId;
for (countryId = 0; countryId < totalCountries; countryId++) {
if (countryIndexToOwner[countryId] == _owner)
{
result[resultIndex] = countryId;
resultIndex++;
}
}
return result;
}
}
/// @notice Total amount of country tokens.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256 total) {
return countries.length;
}
/// @notice Owner initates the transfer of the token to another account
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
) public {
require(!jackpotCompleted);
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Third-party initiates transfer of token from address _from to address _to
/// @param _from The address for the token to be transferred from.
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
) public {
require(!jackpotCompleted);
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
/*** PRIVATE FUNCTIONS ***/
/// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
/// For checking approval of transfer for address _to
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return countryIndexToApproved[_tokenId] == _to;
}
/// For creating Country
function _createCountry(string _name, uint256 _price) private {
Country memory country = Country({
name: _name
});
uint256 newCountryId = countries.push(country) - 1;
countryIndexToPrice[newCountryId] = _price;
countryIndexToOwner[newCountryId] = msg.sender;
ownershipTokenCount[msg.sender] = ownershipTokenCount[msg.sender].add(1);
}
/// Check for token ownership
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == countryIndexToOwner[_tokenId];
}
/// @dev Assigns ownership of a specific Country to an address.
function _transfer(address _from, address _to, uint256 _tokenId) private {
// clear any previously approved ownership exchange
delete countryIndexToApproved[_tokenId];
// Since the number of countries is capped to 32 we can't overflow this
ownershipTokenCount[_to] = ownershipTokenCount[_to].add(1);
//transfer ownership
countryIndexToOwner[_tokenId] = _to;
ownershipTokenCount[_from] = ownershipTokenCount[_from].sub(1);
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
}
function _compareStrings(string a, string b) private pure returns (bool){
return keccak256(a) == keccak256(b);
}
}
|
Create a country with a name, called only by the owner
|
function createCountry(string _name) public onlyOwner{
_createCountry(_name, startingPrice);
}
| 1,971,143
|
/**
*Submitted for verification at Etherscan.io on 2021-11-17
*/
pragma solidity ^0.8.5;
// SPDX-License-Identifier: MIT
interface IERC20 {
/**
* @dev Returns the total tokens supply
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
// 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, 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 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;
}
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data; // msg.data is used to handle array, bytes, string
}
}
/**
* @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.
*
* 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.
*
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function getUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(block.timestamp > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
_previousOwner = address(0);
}
}
// pragma solidity >=0.5.0;
interface IUniswapFactory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// pragma solidity >=0.5.0;
interface IUniswapPair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// pragma solidity >=0.6.2;
interface IUniswapRouter01 {
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);
}
// pragma solidity >=0.6.2;
interface IUniswapRouter02 is IUniswapRouter01 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract PirateCoin is Context, IERC20, Ownable { // change contract name
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _tOwned; // total Owned tokens
mapping (address => mapping (address => uint256)) private _allowances; // allowed allowance for spender
mapping (address => bool) public _isExcludedFromFee; // excluded address from all fee
mapping (address => uint256) private _transactionCheckpoint;
mapping (address => bool) public _isBlacklisted; // blocks an address from buy and selling
mapping(address => bool) public _isExcludedFromTransactionlock; // Address to be excluded from transaction cooldown
address payable public _charityAddress = payable(0x1c061E64238F8e490Fbea3c9162b32b79140b57E); // charity Address
string private _name = "PirateCoin"; // token name
string private _symbol = "PirateCoin"; // token symbol
uint8 private _decimals = 18; // 1 token can be divided into 1e_decimals parts
uint256 private constant MAX = ~uint256(0); // maximum possible number uint256 decimal value
uint256 private _tTotal = 1000000 * 10**6 * 10**_decimals;
uint256 private _tFeeTotal; // total fee collected including tax fee and liquidity fee
// All fees are with one decimal value. so if you want 0.5 set value to 5, for 10 set 100. so on...
uint256 public _charityFee = 30; // charity fee 3%
uint256 private _previousCharityFee = _charityFee; // charity fee
uint256 public _liquidityFee = 40; // actual liquidity fee 4%
uint256 private _previousLiquidityFee = _liquidityFee; // restore actual liquidity fee
uint256 private _totalDeductableFee = _charityFee.add(_liquidityFee); // liquidity + charity fee on each transaction
uint256 private _previousDeductableFee = _totalDeductableFee; // restore old liquidity fee
uint256 private _transactionLockTime = 0; //Cool down time between each transaction per address
IUniswapRouter02 public uniswapRouter; // uniswap router assiged using address
address public uniswapPair; // for creating WETH pair with our token
bool inSwapAndLiquify; // after each successfull swapandliquify disable the swapandliquify
bool public swapAndLiquifyEnabled = true; // set auto swap to ETH and liquify collected liquidity fee
uint256 public _maxTxAmount = 5000 * 10**6 * 10**_decimals; // max allowed tokens tranfer per transaction
uint256 public _minTokensSwapToAndTransferTo = 500 * 10**6 * 10**_decimals; // min token liquidity fee collected before swapandLiquify
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); //event fire min token liquidity fee collected before swapandLiquify
event SwapAndLiquifyEnabledUpdated(bool enabled); // event fire set auto swap to ETH and liquify collected liquidity fee
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqiudity
); // fire event how many tokens were swapedandLiquified
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
} // modifier to after each successfull swapandliquify disable the swapandliquify
constructor () {
_tOwned[_msgSender()] = _tTotal; // assigning the max token to owner's address
IUniswapRouter02 _uniswapRouter = IUniswapRouter02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
uniswapPair = IUniswapFactory(_uniswapRouter.factory())
.createPair(address(this), _uniswapRouter.WETH());
// set the rest of the contract variables
uniswapRouter = _uniswapRouter;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_charityAddress] = true;
//exclude below addresses from transaction cooldown
_isExcludedFromTransactionlock[owner()] = true;
_isExcludedFromTransactionlock[address(this)] = true;
_isExcludedFromTransactionlock[uniswapPair] = true;
_isExcludedFromTransactionlock[_charityAddress] = true;
_isExcludedFromTransactionlock[address(_uniswapRouter)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return _tOwned[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev approves allowance of a spender
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev transfers from a sender to receipent with subtracting spenders allowance with each successfull transfer
*/
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev approves allowance of a spender should set it to zero first than increase
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev decrease allowance of spender that it can spend on behalf of owner
*/
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 Total collected Tax fee
*/
function totalFeesCollected() public view returns (uint256) {
return _tFeeTotal;
}
/**
* @dev exclude an address from fee
*/
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
/**
* @dev include an address for fee
*/
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
/**
* @dev set's charity fee percentage
*/
function setCharityFeePercent(uint256 Fee) external onlyOwner {
_charityFee = Fee;
_totalDeductableFee = _liquidityFee.add(_charityFee);
}
/**
* @dev set's liquidity fee percentage
*/
function setLiquidityFeePercent(uint256 Fee) external onlyOwner {
_liquidityFee = Fee;
_totalDeductableFee = _liquidityFee.add(_charityFee);
}
/**
* @dev set's max amount of tokens percentage
* that can be transfered in each transaction from an address
*/
function setMaxTxnTokens(uint256 maxTxTokens) external onlyOwner {
_maxTxAmount = maxTxTokens.mul( 10**_decimals );
}
/**
* @dev set's minimmun amount of tokens required
* before swaped and ETH send to wallet
* same value will be used for auto swapandliquifiy threshold
*/
function setMinTokensSwapAndTransfer(uint256 minAmount) public onlyOwner
{
_minTokensSwapToAndTransferTo = minAmount.mul( 10 ** _decimals);
}
/**
* @dev set's address
*/
function setCharityAddress(address payable charityAddress) external onlyOwner {
_charityAddress = charityAddress;
}
/**
* @dev Sets transactions on time periods or cooldowns. Buzz Buzz Bots.
* Can only be set by owner set in seconds.
*/
function setTransactionCooldownTime(uint256 transactiontime) public onlyOwner {
_transactionLockTime = transactiontime;
}
/**
* @dev set's auto SwapandLiquify when contract's token balance threshold is reached
*/
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
/**
* @dev Exclude's an address from transactions from cooldowns.
* Can only be set by owner.
*/
function excludedFromTransactionCooldown(address account) public onlyOwner {
_isExcludedFromTransactionlock[account] = true;
}
/**
* @dev Include's an address in transactions from cooldowns.
* Can only be set by owner.
*/
function includeInTransactionCooldown(address account) public onlyOwner {
_isExcludedFromTransactionlock[account] = false;
}
//to recieve ETH from uniswapRouter when swaping
receive() external payable {}
/**
* @dev get/calculates taxfee, liquidity fee
* without reward amount
*/
function _getValues(uint256 tAmount) private view returns (uint256, uint256) {
uint256 tTotalDeductable = calculateTotalDeductableFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tTotalDeductable);
return (tTransferAmount, tTotalDeductable);
}
/**
* @dev take's liquidity fee tokens from tansaction and saves in contract
*/
function _takeTotalDeductable(address sender, uint256 tTotalDeductable) private {
_tOwned[address(this)] = _tOwned[address(this)].add(tTotalDeductable);
emit Transfer(sender, address(this), tTotalDeductable);
}
/**
* @dev calculates liquidity fee tokens to be deducted
*/
function calculateTotalDeductableFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_totalDeductableFee).div(
10**3
);
}
/**
* @dev removes all fee from transaction if takefee is set to false
*/
function removeAllFee() private {
if(_totalDeductableFee == 0 && _charityFee == 0
&& _liquidityFee == 0) return;
_previousLiquidityFee = _liquidityFee;
_previousCharityFee = _charityFee;
_previousDeductableFee = _totalDeductableFee;
_charityFee = 0;
_liquidityFee = 0;
_totalDeductableFee = 0;
}
/**
* @dev restores all fee after exclude fee transaction completes
*/
function restoreAllFee() private {
_liquidityFee = _previousLiquidityFee;
_charityFee = _previousCharityFee;
_totalDeductableFee = _previousDeductableFee;
}
/**
* @dev approves amount of token spender can spend on behalf of an owner
*/
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev transfers token from sender to recipient also auto
* swapsandliquify if contract's token balance threshold is reached
*/
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(_isBlacklisted[from] == false, "You are banned");
require(_isBlacklisted[to] == false, "The recipient is banned");
require(amount > 0, "Transfer amount must be greater than zero");
require(_isExcludedFromTransactionlock[from] || block.timestamp >= _transactionCheckpoint[from] + _transactionLockTime,
"Wait for transaction cooldown time to end before making a tansaction");
require(_isExcludedFromTransactionlock[to] || block.timestamp >= _transactionCheckpoint[to] + _transactionLockTime,
"Wait for transaction cooldown time to end before making a tansaction");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
_transactionCheckpoint[from] = block.timestamp;
_transactionCheckpoint[to] = block.timestamp;
// 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 >=_minTokensSwapToAndTransferTo;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapPair &&
swapAndLiquifyEnabled
) {
contractTokenBalance =_minTokensSwapToAndTransferTo;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
/**
* @dev swapsAndLiquify tokens to uniswap if swapandliquify is enabled
*/
function swapAndLiquify(uint256 tokenBalance) private lockTheSwap {
// first split contract into fee and liquidity fee
uint256 swapPercent = _charityFee.add(_liquidityFee/2);
uint256 swapTokens = tokenBalance.mul(swapPercent).div(_totalDeductableFee);
uint256 liquidityTokens = tokenBalance.sub(swapTokens);
uint256 initialBalance = address(this).balance;
swapTokensForEth(swapTokens);
uint256 swappedAmount = address(this).balance.sub(initialBalance);
if(_charityFee > 0)
{
_charityAddress.transfer(swappedAmount.mul(_charityFee).div(swapPercent));
}
if(_liquidityFee > 0)
{
uint256 liquidityETH = swappedAmount.mul(_liquidityFee/2).div(swapPercent);
// add liquidity to uniswap
addLiquidity(owner(), liquidityTokens, liquidityETH);
emit SwapAndLiquify(liquidityTokens, liquidityETH, liquidityTokens);
}
}
/**
* @dev swap's exact amount of tokens for ETH if swapandliquify is enabled
*/
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] = uniswapRouter.WETH();
_approve(address(this), address(uniswapRouter), tokenAmount);
// make the swap
uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
/**
* @dev add's liquidy to uniswap if swapandliquify is enabled
*/
function addLiquidity(address recipient, uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapRouter), tokenAmount);
// add the liquidity
uniswapRouter.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
recipient,
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
_transferStandard(sender, recipient, amount);
if(!takeFee)
restoreAllFee();
}
/**
* @dev deducteds balance from sender and
* add to recipient with reward for both addresses
*/
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 tTransferAmount, uint256 tTotalDeductable) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_takeTotalDeductable(sender, tTotalDeductable);
emit Transfer(sender, recipient, tTransferAmount);
}
/**
* @dev Blacklist a singel wallet from buying and selling
*/
function blacklistSingleWallet(address account) public onlyOwner{
if(_isBlacklisted[account] == true) return;
_isBlacklisted[account] = true;
}
/**
* @dev Blacklist multiple wallets from buying and selling
*/
function blacklistMultipleWallets(address[] calldata accounts) public onlyOwner{
require(accounts.length < 800, "Can not blacklist more then 800 address in one transaction");
for (uint256 i; i < accounts.length; ++i) {
_isBlacklisted[accounts[i]] = true;
}
}
/**
* @dev un blacklist a singel wallet from buying and selling
*/
function unBlacklistSingleWallet(address account) external onlyOwner{
if(_isBlacklisted[account] == false) return;
_isBlacklisted[account] = false;
}
/**
* @dev un blacklist multiple wallets from buying and selling
*/
function unBlacklistMultipleWallets(address[] calldata accounts) public onlyOwner{
require(accounts.length < 800, "Can not Unblacklist more then 800 address in one transaction");
for (uint256 i; i < accounts.length; ++i) {
_isBlacklisted[accounts[i]] = false;
}
}
/**
* @dev recovers any tokens stuck in Contract's balance
* NOTE! if ownership is renounced then it will not work
* NOTE! Contract's Address and Owner's address MUST NOT
*/
function recoverTokens() public onlyOwner
{
address recipient = _msgSender();
uint256 tokensToRecover = balanceOf(address(this));
_tOwned[address(this)] = _tOwned[address(this)].sub(tokensToRecover);
_tOwned[recipient] = _tOwned[recipient].add(tokensToRecover);
emit Transfer(address(this), recipient, tokensToRecover);
}
/**
* @dev recovers any ETH stuck in Contract's balance
* NOTE! if ownership is renounced then it will not work
*/
function recoverETH() public onlyOwner
{
address payable recipient = _msgSender();
if(address(this).balance > 0)
recipient.transfer(address(this).balance);
}
//New uniswap router version?
//No problem, just change it!
function setRouterAddress(address newRouter) public onlyOwner {
IUniswapRouter02 _newUniswapRouter = IUniswapRouter02(newRouter);
uniswapPair = IUniswapFactory(_newUniswapRouter.factory()).createPair(address(this), _newUniswapRouter.WETH());
uniswapRouter = _newUniswapRouter;
}
}
|
Total collected Tax fee/
|
function totalFeesCollected() public view returns (uint256) {
return _tFeeTotal;
}
| 6,719,386
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import '@openzeppelin/contracts/access/Ownable.sol';
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import '@openzeppelin/contracts/security/Pausable.sol';
import "@openzeppelin/contracts/utils/Counters.sol";
/*
* @title Contract for Pixelvault giveaways using Chainlink VRF
*
* @author Niftydude
*/
contract Pixelvault1155Giveaway is VRFConsumerBase, ERC1155Holder, Ownable, Pausable {
using Counters for Counters.Counter;
Counters.Counter private counter;
bytes32 internal keyHash;
uint256 internal fee;
mapping(uint256 => Giveaway) public giveaways;
IERC1155 public erc1155Contract;
event Claimed(uint indexed index, address indexed account, uint amount);
struct Giveaway {
uint256 snapshotEntries;
uint256 amountOfWinners;
uint256 randomNumber;
uint256 tokenId;
uint256 claimOpen;
uint256 claimClose;
bool isFulfilled;
bool allowDuplicates;
string entryListIpfsHash;
address contractAddress;
mapping(address => uint256) claimed;
bytes32 merkleRoot;
}
constructor(
address _vrfCoordinator,
address _linkToken,
bytes32 _keyHash,
uint256 _fee
) VRFConsumerBase(_vrfCoordinator, _linkToken) {
keyHash = _keyHash;
fee = _fee;
}
/**
* @notice set merkle root for a given draw
*
* @param _merkleRoot the merkle root to verify eligile claims
*/
function setMerkleRoot(
bytes32 _merkleRoot,
uint256 _drawId
) external onlyOwner {
require(giveaways[_drawId].isFulfilled, "setMerkleRoot: draw not fulfilled");
giveaways[_drawId].merkleRoot = _merkleRoot;
}
/**
* @notice return all winning entries for a given draw
*
* @param giveawayId the giveaway id to return winners for
*/
function getWinners(uint256 giveawayId) external view returns (uint256[] memory) {
require(giveaways[giveawayId].isFulfilled, "GetWinners: draw not fulfilled");
require(giveaways[giveawayId].amountOfWinners > 0, "GetWinners: not a draw");
uint256[] memory expandedValues = new uint256[](giveaways[giveawayId].amountOfWinners);
bool[] memory isNumberPicked = new bool[](giveaways[giveawayId].snapshotEntries);
uint256 resultIndex;
uint256 i;
while (resultIndex < giveaways[giveawayId].amountOfWinners) {
uint256 number = (uint256(keccak256(abi.encode(giveaways[giveawayId].randomNumber, i))) % giveaways[giveawayId].snapshotEntries) + 1;
if(giveaways[giveawayId].allowDuplicates || !isNumberPicked[number-1]) {
expandedValues[resultIndex] = number;
isNumberPicked[number-1] = true;
resultIndex++;
}
i++;
}
return expandedValues;
}
function withdrawLink() external onlyOwner {
LINK.transfer(owner(), LINK.balanceOf(address(this)));
}
/**
* @notice initiate a new draw
*
* @param _snapshotEntries the number of entries in the snapshot
* @param _amountOfWinners the amount of winners to pick
* @param _tokenId the token id which can be won
* @param _contractAddress the contract address of the token
* @param _entryListIpfsHash ipfs hash pointing to the list of entries
* @param _allowDuplicates if true, a single entry is allowed to win multiple times
*
*/
function startDraw(
uint256 _snapshotEntries,
uint256 _amountOfWinners,
uint256 _tokenId,
address _contractAddress,
string memory _entryListIpfsHash,
bool _allowDuplicates,
uint256 _claimOpen,
uint256 _claimClose
) external onlyOwner returns (bytes32 requestId) {
require(counter.current() == 0 || giveaways[counter.current()-1].isFulfilled, "Draw: previous draw not fulfilled");
require(_amountOfWinners < _snapshotEntries, "Draw: amount of winners must be smaller than number of entries");
require(
LINK.balanceOf(address(this)) >= fee,
"Not enough LINK - fill contract with faucet"
);
Giveaway storage d = giveaways[counter.current()];
d.snapshotEntries = _snapshotEntries;
d.amountOfWinners = _amountOfWinners;
d.tokenId = _tokenId;
d.contractAddress = _contractAddress;
d.entryListIpfsHash = _entryListIpfsHash;
d.allowDuplicates = _allowDuplicates;
d.claimOpen = _claimOpen;
d.claimClose = _claimClose;
counter.increment();
return requestRandomness(keyHash, fee);
}
/**
* @notice initiate a new giveaway
*
* @param _tokenId the token id which can be won
* @param _contractAddress the contract address of the token
* @param _merkleRoot the merkle root to verify eligile claims
*/
function startGiveaway(
uint256 _tokenId,
address _contractAddress,
bytes32 _merkleRoot,
uint256 _claimOpen,
uint256 _claimClose
) external onlyOwner {
require(counter.current() == 0 || giveaways[counter.current()-1].isFulfilled, "Giveaway: previous giveaway not fulfilled");
Giveaway storage d = giveaways[counter.current()];
d.tokenId = _tokenId;
d.isFulfilled = true;
d.contractAddress = _contractAddress;
d.merkleRoot = _merkleRoot;
d.claimOpen = _claimOpen;
d.claimClose = _claimClose;
counter.increment();
}
/**
* @notice claim tokens
*
* @param amount the amount of tokens to claim
* @param giveawayId the id of the token to claim
* @param index the index of the merkle proof
* @param maxAmount the max amount of tokens sender is eligible to claim
* @param merkleProof the valid merkle proof of sender for given token id
*/
function claim(
uint256 amount,
uint256 giveawayId,
uint256 index,
uint256 maxAmount,
bytes32[] calldata merkleProof
) external whenNotPaused {
require(giveaways[giveawayId].claimed[msg.sender] + amount <= maxAmount, "Claim: Not allowed to claim given amount");
require (block.timestamp >= giveaways[giveawayId].claimOpen && block.timestamp <= giveaways[giveawayId].claimClose, "Claim: time window closed");
bytes32 node = keccak256(abi.encodePacked(index, msg.sender, maxAmount));
require(
MerkleProof.verify(merkleProof, giveaways[giveawayId].merkleRoot, node),
"MerkleDistributor: Invalid proof."
);
giveaways[giveawayId].claimed[msg.sender] = giveaways[giveawayId].claimed[msg.sender] + amount;
IERC1155(giveaways[giveawayId].contractAddress).safeTransferFrom(address(this), msg.sender, giveaways[giveawayId].tokenId, amount, "");
emit Claimed(giveaways[giveawayId].tokenId, msg.sender, amount);
}
/**
* @notice withdraw ERC1155 tokens from contract
*
* @param _contractAddress the contract address of the token
* @param _tokenId the id of the token
* @param _amount the amount of tokens
*/
function withdrawTokens(address _contractAddress, uint256 _tokenId, uint256 _amount) external onlyOwner {
IERC1155(_contractAddress).safeTransferFrom(address(this), msg.sender, _tokenId, _amount, "");
}
/**
* @notice pause claims
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice unpause claims
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @notice emergency function to force fulfillment
*
* @param _giveawayId the id of the giveaway to fulfill
*/
function forceFulfill(uint256 _giveawayId) external onlyOwner {
giveaways[_giveawayId].isFulfilled = true;
}
/**
* @notice edit claim window for a specific giveaway
*
* @param _giveawayId the id of the giveaway to edit
* @param _claimOpen UNIX opening timestamp
* @param _claimClose UNIX closing timestamp
*/
function setClaimWindow(uint256 _giveawayId, uint256 _claimOpen, uint256 _claimClose) external onlyOwner {
require(_giveawayId < counter.current(), "Draw id does not exist");
giveaways[_giveawayId].claimOpen = _claimOpen;
giveaways[_giveawayId].claimClose = _claimClose;
}
/**
* @notice return the number of tokens a given account
* has already claimed for a given draw
*
* @param drawId the id of the draw
* @param userAdress the address of the user
*/
function getClaimedTokens(uint256 drawId, address userAdress) public view returns (uint256) {
return giveaways[drawId].claimed[userAdress];
}
/**
* Callback function used by VRF Coordinator
*/
function fulfillRandomness(bytes32, uint256 randomness) internal override {
giveaways[counter.current()-1].randomNumber = randomness;
giveaways[counter.current()-1].isFulfilled = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/LinkTokenInterface.sol";
import "./VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(
bytes32 requestId,
uint256 randomness
)
internal
virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 constant private USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(
bytes32 _keyHash,
uint256 _fee
)
internal
returns (
bytes32 requestId
)
{
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(
address _vrfCoordinator,
address _link
) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(
bytes32 requestId,
uint256 randomness
)
external
{
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
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: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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;
interface LinkTokenInterface {
function allowance(
address owner,
address spender
)
external
view
returns (
uint256 remaining
);
function approve(
address spender,
uint256 value
)
external
returns (
bool success
);
function balanceOf(
address owner
)
external
view
returns (
uint256 balance
);
function decimals()
external
view
returns (
uint8 decimalPlaces
);
function decreaseApproval(
address spender,
uint256 addedValue
)
external
returns (
bool success
);
function increaseApproval(
address spender,
uint256 subtractedValue
) external;
function name()
external
view
returns (
string memory tokenName
);
function symbol()
external
view
returns (
string memory tokenSymbol
);
function totalSupply()
external
view
returns (
uint256 totalTokensIssued
);
function transfer(
address to,
uint256 value
)
external
returns (
bool success
);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
)
external
returns (
bool success
);
function transferFrom(
address from,
address to,
uint256 value
)
external
returns (
bool success
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
)
internal
pure
returns (
uint256
)
{
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(
bytes32 _keyHash,
uint256 _vRFInputSeed
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// 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 "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
|
unpause claims/
|
function unpause() external onlyOwner {
_unpause();
}
| 12,575,800
|
pragma solidity 0.6.12;
import "../OpenZeppelin/access/AccessControl.sol";
import "./ERC20/ERC20Burnable.sol";
import "./ERC20/ERC20Pausable.sol";
import "../interfaces/IMisoToken.sol";
// ---------------------------------------------------------------------
//
// From the MISO Token Factory
//
// Made for Sushi.com
//
// Enjoy. (c) Chef Gonpachi 2021
// <https://github.com/chefgonpachi/MISO/>
//
// ---------------------------------------------------------------------
// SPDX-License-Identifier: GPL-3.0
// ---------------------------------------------------------------------
contract MintableToken is AccessControl, ERC20Burnable, ERC20Pausable, IMisoToken {
/// @notice Miso template id for the token factory.
/// @dev For different token types, this must be incremented.
uint256 public constant override tokenTemplate = 2;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
function initToken(string memory _name, string memory _symbol, address _owner, uint256 _initialSupply) public {
_initERC20(_name, _symbol);
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
_setupRole(MINTER_ROLE, _owner);
_setupRole(PAUSER_ROLE, _owner);
_mint(msg.sender, _initialSupply);
}
function init(bytes calldata _data) external override payable {}
function initToken(
bytes calldata _data
) public override {
(string memory _name,
string memory _symbol,
address _owner,
uint256 _initialSupply) = abi.decode(_data, (string, string, address, uint256));
initToken(_name,_symbol,_owner,_initialSupply);
}
/**
* @dev Generates init data for Token Factory
* @param _name - Token name
* @param _symbol - Token symbol
* @param _owner - Contract owner
* @param _initialSupply Amount of tokens minted on creation
*/
function getInitData(
string calldata _name,
string calldata _symbol,
address _owner,
uint256 _initialSupply
)
external
pure
returns (bytes memory _data)
{
return abi.encode(_name, _symbol, _owner, _initialSupply);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "MintableToken: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "MintableToken: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "MintableToken: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
pragma solidity 0.6.12;
import "../utils/EnumerableSet.sol";
import "../utils/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, 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;
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());
}
}
}
pragma solidity ^0.6.0;
import "../ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the callers
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
pragma solidity ^0.6.0;
import "../ERC20.sol";
import "../../OpenZeppelin/utils/Pausable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20Pausable is ERC20, Pausable {
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
pragma solidity 0.6.12;
interface IMisoToken {
function init(bytes calldata data) external payable;
function initToken( bytes calldata data ) external;
function tokenTemplate() external view returns (uint256);
}
pragma solidity 0.6.12;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity 0.6.12;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity 0.6.12;
import "../OpenZeppelin/GSN/Context.sol";
import "../OpenZeppelin/math/SafeMath.sol";
import "../interfaces/IERC20.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 IERC20, Context {
using SafeMath for uint256;
bytes32 public DOMAIN_SEPARATOR;
mapping (address => uint256) private _balances;
mapping(address => uint256) public nonces;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
bool private _initialized;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function _initERC20(string memory name_, string memory symbol_) internal {
require(!_initialized, "ERC20: token has already been initialized!");
_name = name_;
_symbol = symbol_;
_decimals = 18;
uint256 chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(abi.encode(keccak256("EIP712Domain(uint256 chainId,address verifyingContract)"), chainId, address(this)));
_initialized = true;
}
/**
* @dev Returns the name of the token.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_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 override 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 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;
}
// See https://eips.ethereum.org/EIPS/eip-191
string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01";
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(owner_ != address(0), "ERC20: Owner cannot be 0");
require(block.timestamp < deadline, "ERC20: Expired");
bytes32 digest =
keccak256(
abi.encodePacked(
EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA,
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress == owner_, "ERC20: Invalid Signature");
_approve(owner_, spender, value);
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public override virtual 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);
_afterTokenTransfer(sender, 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 = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_afterTokenTransfer(address(0), 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);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
_afterTokenTransfer(account, address(0), 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 { }
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
pragma solidity 0.6.12;
import "../utils/Context.sol";
pragma solidity 0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
pragma solidity 0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
pragma solidity 0.6.12;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
|
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);
_afterTokenTransfer(address(0), account, amount);
emit Transfer(address(0), account, amount);
}
| 1,329,163
|
./full_match/1/0x76B634B0d9137ceF5694D0cCf95189Cd448A29f1/sources/src/L1/gateways/L1ERC20Gateway.sol
|
@inheritdoc IL1ERC20Gateway
|
function depositERC20(
address _token,
address _to,
uint256 _amount,
uint256 _gasLimit
) external payable override {
_deposit(_token, _to, _amount, new bytes(0), _gasLimit);
}
| 8,338,319
|
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-periphery/contracts/libraries/OracleLibrary.sol';
import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol';
import './interfaces/IDexPriceAggregator.sol';
import './libraries/SpotOracleLibrary.sol';
import './libraries/SafeCast.sol';
import './Owned.sol';
/// @title DexPriceAggregatorUniswapV3
/// @notice A DexPriceAggregator sourcing prices from Uniswap V3.
/// Provides the minimum output between an asset's "spot" price and TWAP from the last n seconds.
/// The "spot" price is always the last block's ending price.
contract DexPriceAggregatorUniswapV3 is IDexPriceAggregator, Owned {
address public immutable uniswapV3Factory;
address public immutable weth;
uint24 public immutable defaultPoolFee;
mapping(bytes32 => address) public overriddenPoolForRoute;
constructor(
address _owner,
address _uniswapV3Factory,
address _weth,
uint24 _defaultPoolFee
) Owned(_owner) {
uniswapV3Factory = _uniswapV3Factory;
weth = _weth;
defaultPoolFee = _defaultPoolFee;
}
/********************
* Oracle functions *
********************/
/// @inheritdoc IDexPriceAggregator
function assetToAsset(
address _tokenIn,
uint256 _amountIn,
address _tokenOut,
uint256 _twapPeriod
) public view override returns (uint256 amountOut) {
if (_tokenIn == weth) {
return ethToAsset(_amountIn, _tokenOut, _twapPeriod);
} else if (_tokenOut == weth) {
return assetToEth(_tokenIn, _amountIn, _twapPeriod);
} else {
return _fetchAmountCrossingPools(_tokenIn, _amountIn, _tokenOut, _twapPeriod);
}
}
/// @notice Given a token and its amount, return the equivalent value in ETH
/// @param _tokenIn Address of an ERC20 token contract to be converted
/// @param _amountIn Amount of tokenIn to be converted
/// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate
/// @return ethAmountOut Amount of ETH received for amountIn of tokenIn
function assetToEth(
address _tokenIn,
uint256 _amountIn,
uint256 _twapPeriod
) public view returns (uint256 ethAmountOut) {
address tokenOut = weth;
address pool = _getPoolForRoute(PoolAddress.getPoolKey(_tokenIn, tokenOut, defaultPoolFee));
return _fetchAmountFromSinglePool(_tokenIn, _amountIn, tokenOut, pool, _twapPeriod);
}
/// @notice Given an amount of ETH, return the equivalent value in another token
/// @param _ethAmountIn Amount of ETH to be converted
/// @param _tokenOut Address of an ERC20 token contract to convert into
/// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate
/// @return amountOut Amount of tokenOut received for ethAmountIn of ETH
function ethToAsset(
uint256 _ethAmountIn,
address _tokenOut,
uint256 _twapPeriod
) public view returns (uint256 amountOut) {
address tokenIn = weth;
address pool = _getPoolForRoute(PoolAddress.getPoolKey(tokenIn, _tokenOut, defaultPoolFee));
return _fetchAmountFromSinglePool(tokenIn, _ethAmountIn, _tokenOut, pool, _twapPeriod);
}
/************************
* Management functions *
************************/
/// @notice Override the Uniswap V3 pool queried on a tokenA:tokenB route
/// @dev Override can be reset by using address(0) for _pool
/// @param _tokenA Address of an ERC20 token contract
/// @param _tokenB Address of another ERC20 token contract
/// @param _pool Address of a Uniswap V3 pool constructed with _tokenA and _tokenB
function setPoolForRoute(
address _tokenA,
address _tokenB,
address _pool
) public onlyOwner {
PoolAddress.PoolKey memory poolKey = PoolAddress.getPoolKey(
_tokenA,
_tokenB,
uint24(0) // pool fee is unused
);
if (_pool != address(0)) {
require(
poolKey.token0 == IUniswapV3Pool(_pool).token0() && poolKey.token1 == IUniswapV3Pool(_pool).token1(),
'Tokens or pool not correct'
);
}
overriddenPoolForRoute[_identifyRouteFromPoolKey(poolKey)] = _pool;
emit PoolForRouteSet(poolKey.token0, poolKey.token1, _pool);
}
/// @notice Fetch the Uniswap V3 pool to be queried for a tokenA:tokenB route
/// @param _tokenA Address of an ERC20 token contract
/// @param _tokenB Address of another ERC20 token contract
/// @return pool Address of a Uniswap V3 pool constructed with _tokenA and _tokenB
function getPoolForRoute(address _tokenA, address _tokenB) public view returns (address pool) {
return _getPoolForRoute(PoolAddress.getPoolKey(_tokenA, _tokenB, defaultPoolFee));
}
/**************************
* Utility view functions *
**************************/
/// @notice Fetch a Uniswap V3 pool's current "spot" and TWAP tick values
/// @param _pool Address of a Uniswap V3 pool
/// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate
/// @return spotTick The pool's current "spot" tick
/// @return twapTick The twap tick for the last _twapPeriod seconds
function fetchCurrentTicks(address _pool, uint32 _twapPeriod) public view returns (int24 spotTick, int24 twapTick) {
spotTick = SpotOracleLibrary.consult(_pool);
twapTick = OracleLibrary.consult(_pool, _twapPeriod);
}
/// @notice Given a tick and a token amount, calculates the amount of token received in exchange
/// @param _tokenIn Address of an ERC20 token contract to be converted
/// @param _amountIn Amount of tokenIn to be converted
/// @param _tokenOut Address of an ERC20 token contract to convert into
/// @param _tick Tick value representing conversion ratio between _tokenIn and _tokenOut
/// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn
function getQuoteAtTick(
address _tokenIn,
uint128 _amountIn,
address _tokenOut,
int24 _tick
) public pure returns (uint256 amountOut) {
return OracleLibrary.getQuoteAtTick(_tick, _amountIn, _tokenIn, _tokenOut);
}
/// @notice Similar to getQuoteAtTick() but calculates the amount of token received in exchange
/// by first adjusting into ETH
/// (ie. when a route goes through an intermediary pool with ETH)
/// @param _tokenIn Address of an ERC20 token contract to be converted
/// @param _amountIn Amount of tokenIn to be converted
/// @param _tokenOut Address of an ERC20 token contract to convert into
/// @param _tick1 First tick value representing conversion ratio between _tokenIn and ETH
/// @param _tick2 Second tick value representing conversion ratio between ETH and _tokenOut
/// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn
function getQuoteCrossingTicksThroughWeth(
address _tokenIn,
uint128 _amountIn,
address _tokenOut,
int24 _tick1,
int24 _tick2
) public view returns (uint256 amountOut) {
return _getQuoteCrossingTicksThroughWeth(_tokenIn, _amountIn, _tokenOut, _tick1, _tick2);
}
/*************
* Internals *
*************/
/// @notice Given a token and amount, return the equivalent value in another token by exchanging
/// within a single liquidity pool
/// @dev _pool _must_ be previously checked to contain _tokenIn and _tokenOut.
/// It is exposed as a parameter only as a gas optimization.
/// @param _tokenIn Address of an ERC20 token contract to be converted
/// @param _amountIn Amount of tokenIn to be converted
/// @param _tokenOut Address of an ERC20 token contract to convert into
/// @param _pool Address of a Uniswap V3 pool containing _tokenIn and _tokenOut
/// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate
/// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn
function _fetchAmountFromSinglePool(
address _tokenIn,
uint256 _amountIn,
address _tokenOut,
address _pool,
uint256 _twapPeriod
) internal view returns (uint256 amountOut) {
// Leave ticks as int256s to avoid solidity casting
int256 spotTick = SpotOracleLibrary.consult(_pool);
int256 twapTick = OracleLibrary.consult(_pool, SafeCast.toUint32(_twapPeriod));
// Return min amount between spot price and twap
// Ticks are based on the ratio between token0:token1 so if the input token is token1 then
// we need to treat the tick as an inverse
int256 minTick;
if (_tokenIn < _tokenOut) {
minTick = spotTick < twapTick ? spotTick : twapTick;
} else {
minTick = spotTick > twapTick ? spotTick : twapTick;
}
return
OracleLibrary.getQuoteAtTick(
int24(minTick), // can assume safe being result from consult()
SafeCast.toUint128(_amountIn),
_tokenIn,
_tokenOut
);
}
/// @notice Given a token and amount, return the equivalent value in another token by "crossing"
/// liquidity across an intermediary pool with ETH (ie. _tokenIn:ETH and ETH:_tokenOut)
/// @dev If an overridden pool has been set for _tokenIn and _tokenOut, this pool will be used
/// used directly in lieu of "crossing" against an intermediary pool with ETH
/// @param _tokenIn Address of an ERC20 token contract to be converted
/// @param _amountIn Amount of tokenIn to be converted
/// @param _tokenOut Address of an ERC20 token contract to convert into
/// @param _twapPeriod Number of seconds in the past to consider for the TWAP rate
/// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn
function _fetchAmountCrossingPools(
address _tokenIn,
uint256 _amountIn,
address _tokenOut,
uint256 _twapPeriod
) internal view returns (uint256 amountOut) {
// If the tokenIn:tokenOut route was overridden to use a single pool, derive price directly from that pool
address overriddenPool = _getOverriddenPool(
PoolAddress.getPoolKey(
_tokenIn,
_tokenOut,
uint24(0) // pool fee is unused
)
);
if (overriddenPool != address(0)) {
return _fetchAmountFromSinglePool(_tokenIn, _amountIn, _tokenOut, overriddenPool, _twapPeriod);
}
// Otherwise, derive the price by "crossing" through tokenIn:ETH -> ETH:tokenOut
// To keep consistency, we cross through with the same price source (spot vs. twap)
address pool1 = _getPoolForRoute(PoolAddress.getPoolKey(_tokenIn, weth, defaultPoolFee));
address pool2 = _getPoolForRoute(PoolAddress.getPoolKey(_tokenOut, weth, defaultPoolFee));
int24 spotTick1 = SpotOracleLibrary.consult(pool1);
int24 spotTick2 = SpotOracleLibrary.consult(pool2);
uint256 spotAmountOut = _getQuoteCrossingTicksThroughWeth(_tokenIn, _amountIn, _tokenOut, spotTick1, spotTick2);
uint32 castedTwapPeriod = SafeCast.toUint32(_twapPeriod);
int24 twapTick1 = OracleLibrary.consult(pool1, castedTwapPeriod);
int24 twapTick2 = OracleLibrary.consult(pool2, castedTwapPeriod);
uint256 twapAmountOut = _getQuoteCrossingTicksThroughWeth(_tokenIn, _amountIn, _tokenOut, twapTick1, twapTick2);
// Return min amount between spot price and twap
return spotAmountOut < twapAmountOut ? spotAmountOut : twapAmountOut;
}
/// @notice Similar to OracleLibrary#getQuoteAtTick but calculates the amount of token received
/// in exchange by first adjusting into ETH
/// (ie. when a route goes through an intermediary pool with ETH)
/// @param _tokenIn Address of an ERC20 token contract to be converted
/// @param _amountIn Amount of tokenIn to be converted
/// @param _tokenOut Address of an ERC20 token contract to convert into
/// @param _tick1 First tick value used to adjust from _tokenIn to ETH
/// @param _tick2 Second tick value used to adjust from ETH to _tokenOut
/// @return amountOut Amount of _tokenOut received for _amountIn of _tokenIn
function _getQuoteCrossingTicksThroughWeth(
address _tokenIn,
uint256 _amountIn,
address _tokenOut,
int24 _tick1,
int24 _tick2
) internal view returns (uint256 amountOut) {
uint256 ethAmountOut = OracleLibrary.getQuoteAtTick(_tick1, SafeCast.toUint128(_amountIn), _tokenIn, weth);
return OracleLibrary.getQuoteAtTick(_tick2, SafeCast.toUint128(ethAmountOut), weth, _tokenOut);
}
/// @notice Fetch the Uniswap V3 pool to be queried for a route denoted by a PoolKey
/// @param _poolKey PoolKey representing the route
/// @return pool Address of the Uniswap V3 pool to use for the route
function _getPoolForRoute(PoolAddress.PoolKey memory _poolKey) internal view returns (address pool) {
pool = _getOverriddenPool(_poolKey);
if (pool == address(0)) {
pool = PoolAddress.computeAddress(uniswapV3Factory, _poolKey);
}
}
/// @notice Obtain the canonical identifier for a route denoted by a PoolKey
/// @param _poolKey PoolKey representing the route
/// @return id identifier for the route
function _identifyRouteFromPoolKey(PoolAddress.PoolKey memory _poolKey) internal pure returns (bytes32 id) {
return keccak256(abi.encodePacked(_poolKey.token0, _poolKey.token1));
}
/// @notice Fetch an overridden pool for a route denoted by a PoolKey, if any
/// @param _poolKey PoolKey representing the route
/// @return pool Address of the Uniswap V3 pool overridden for the route.
/// address(0) if no overridden pool has been set.
function _getOverriddenPool(PoolAddress.PoolKey memory _poolKey) internal view returns (address pool) {
return overriddenPoolForRoute[_identifyRouteFromPoolKey(_poolKey)];
}
/**********
* Events *
**********/
event PoolForRouteSet(address indexed token0, address indexed token1, address indexed pool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.8.0;
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol';
import '../libraries/PoolAddress.sol';
/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
/// @notice Fetches time-weighted average tick using Uniswap V3 oracle
/// @param pool Address of Uniswap V3 pool that we want to observe
/// @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 consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) {
require(period != 0, 'BP');
uint32[] memory secondAgos = new uint32[](2);
secondAgos[0] = period;
secondAgos[1] = 0;
(int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).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);
// Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
if (sqrtRatioX96 <= type(uint128).max) {
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);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
/// @title DexPriceAggregator interface
/// @notice Provides interface for querying an asset's price from one or more DEXes
interface IDexPriceAggregator {
/// @notice Given a token and its amount, return the equivalent value in another token
/// @param tokenIn Address of an ERC20 token contract to be converted
/// @param amountIn Amount of tokenIn to be converted
/// @param tokenOut Address of an ERC20 token contract to convert into
/// @param twapPeriod Number of seconds in the past to consider for the TWAP rate, if applicable
/// @return amountOut Amount of tokenOut received for amountIn of tokenIn
function assetToAsset(
address tokenIn,
uint256 amountIn,
address tokenOut,
uint256 twapPeriod
) external view returns (uint256 amountOut);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.8.0;
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol';
/// @title Spot Oracle library
/// @notice Provides functions to integrate with a V3 pool's "safe" spot price
library SpotOracleLibrary {
/// @notice Fetches spot tick using Uniswap V3 oracle
/// @param pool Address of Uniswap V3 pool to observe
/// @return spotTick The spot tick, which is the prior block's ending tick
function consult(address pool) internal view returns (int24 spotTick) {
(, int24 currentTick, uint16 currentObservationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();
(uint32 currentObservationTimestamp, int56 currentTickCumulative , , ) = IUniswapV3Pool(pool).observations(currentObservationIndex);
// Stored timestamps are truncated, so assume the last observation was made within a uint32 second time window (~136 years)
if (beforeNow(currentObservationTimestamp)) {
// The last observation was written prior to this block, so no trades have occurred since then
// The pool's current tick can be considered its spot tick
spotTick = currentTick;
} else {
// The last observation was written in this block, making the current tick value
// unreliable as it could have been manipulated.
// Instead, provide spot as prior block's ending tick.
(uint32 priorTimestamp, int56 priorTickCumulative) =
fetchPriorObservation(pool, 1, currentObservationIndex, observationCardinality);
spotTick = untransformCumulativesIntoTick(
currentObservationTimestamp,
currentTickCumulative,
priorTimestamp,
priorTickCumulative
);
}
}
/// @notice Fetches a previously observed tick from a Uniswap V3 oracle
/// @param pool Address of Uniswap V3 pool to observe
/// @param prevSteps Number of tick observations to go backwards from last
/// @return observedTick Previously observed tick
function consultPreviouslyObservedTick(address pool, uint16 prevSteps) internal view returns (int24 observedTick) {
(, , uint16 currentObservationIndex, uint16 observationCardinality, , , ) = IUniswapV3Pool(pool).slot0();
(uint32 targetTimestamp, int56 targetTickCumulative) =
fetchPriorObservation(pool, prevSteps, currentObservationIndex, observationCardinality);
(uint32 targetMinusOneTimestamp, int56 targetMinusOneTickCumulative) =
fetchPriorObservation(pool, prevSteps + 1, currentObservationIndex, observationCardinality);
observedTick = untransformCumulativesIntoTick(
targetTimestamp,
targetTickCumulative,
targetMinusOneTimestamp,
targetMinusOneTickCumulative
);
}
/// @dev Returns whether given timestamp (truncated to 32 bits) is before current block timestamp.
/// Safe in comparisons across uint32 overflow boundaries.
/// `beforeOrNow` _must_ originally have been within one uint32 time period chronologically
/// before or equal to `block.timestamp`.
/// @param beforeOrNow A timestamp chronologically before or equal to the current block timestamp
/// @return bool Whether `beforeOrNow` is chronologically < block.timestamp
function beforeNow(uint32 beforeOrNow) private view returns (bool) {
// If `beforeOrNow` was within one uint32 period to `block.timestamp` then a lower value is
// naturally an earlier time and a higher value is also an earlier time, only pre-overflow
return beforeOrNow != uint32(block.timestamp); // truncation is desired
}
/// @dev Fetch a prior observation `prevSteps` before a starting index.
/// Handles cardinality wrapping and uninitialized observations after cardinality growth.
/// @param pool Address of Uniswap V3 pool to observe
/// @param prevSteps Number of tick observations to go backwards from starting
/// @param startingObservationIndex Observation index to start from
/// @param observationCardinality Observation cardinality
/// @return timestamp Prior observation's timestamp
/// @return tickCumulative Prior observation's tick cumulative value
function fetchPriorObservation(
address pool,
uint16 prevSteps,
uint16 startingObservationIndex,
uint16 observationCardinality
) private view returns (uint32 timestamp, int56 tickCumulative) {
bool initialized;
for(; !initialized && prevSteps < observationCardinality; ++prevSteps) {
// This loop handles a specific case when the pool's cardinality has increased but has
// not yet observed enough new trades to fill out the new indices.
// If we loop back from 0 to the last index, we will find uninitialized observations and
// will have to keep looking back.
uint16 observationIndex = prevObservationIndex(prevSteps, startingObservationIndex, observationCardinality);
(timestamp, tickCumulative, , initialized) = IUniswapV3Pool(pool).observations(observationIndex);
}
require(initialized, 'BC'); // ensure found observation is initialized and within cardinality
}
/// @dev Calculate the index of a past observation `prevSteps` before a starting index.
/// Handles cardinality wrapping.
/// `prevSteps` _must_ be lte `cardinality`.
/// @param prevSteps Number of indices to go backwards from starting
/// @param starting Index to start from
/// @param cardinality Observation cardinality
/// @return uint16 Index of past observation
function prevObservationIndex(uint16 prevSteps, uint16 starting, uint16 cardinality) private pure returns (uint16) {
if (starting < prevSteps) {
return cardinality - prevSteps + starting;
} else {
return starting - prevSteps;
}
}
/// @dev Untransform two observations into the more recent observation's tick value at write time
/// @param soonerTimestamp More recent observation's timestamp
/// @param soonerTickCumulative More recent observation's tick cumulative
/// @param laterTimestamp Less recent observation's timestamp
/// @param laterTickCumulative Less recent observation's tick cumulative
/// @return tick More recent observation's tick
function untransformCumulativesIntoTick(
uint32 soonerTimestamp,
int56 soonerTickCumulative,
uint32 laterTimestamp,
int56 laterTickCumulative
) private pure returns (int24 tick) {
// "Untransform" sooner and later into the sooner's tick value
// Assume these two observations were made within a uint32 second time window (~136 years)
uint32 timeDelta = soonerTimestamp - laterTimestamp; // underflow is desired
int56 tickDelta = soonerTickCumulative - laterTickCumulative;
tick = int24(tickDelta / timeDelta);
// Always round observed tick to negative infinity
if (tickDelta < 0 && (tickDelta % timeDelta != 0)) tick--;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
/// Adapted from UniswapV3: https://github.com/Uniswap/uniswap-v3-core/blob/v1.0.0/contracts/libraries/SafeCast.sol
library SafeCast {
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint128
function toUint128(uint256 y) internal pure returns (uint128 z) {
require((z = uint128(y)) == y);
}
/// @notice Cast a uint256 to a uint32, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint32
function toUint32(uint256 y) internal pure returns (uint32 z) {
require((z = uint32(y)) == y);
}
}
// SPDX-License-Identifier: MIT
// Adapted from https://github.com/Synthetixio/synthetix/blob/v2.46.0/contracts/Owned.sol
pragma solidity >=0.5.0 <0.8.0;
/// @title Only-owner utility
/// @notice Provides subclasses with only-owner permission utilities
abstract contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) {
require(_owner != address(0), 'Owner address cannot be 0');
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, 'You must be nominated before you can accept ownership');
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner() {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, 'Only the contract owner may perform this action');
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(aΓbΓ·denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(aΓbΓ·denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.0;
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
}
|
Untransform two observations into the more recent observation's tick value at write time soonerTimestamp More recent observation's timestamp soonerTickCumulative More recent observation's tick cumulative laterTimestamp Less recent observation's timestamp laterTickCumulative Less recent observation's tick cumulative return tick More recent observation's tick "Untransform" sooner and later into the sooner's tick value Assume these two observations were made within a uint32 second time window (~136 years) Always round observed tick to negative infinity
|
function untransformCumulativesIntoTick(
uint32 soonerTimestamp,
int56 soonerTickCumulative,
uint32 laterTimestamp,
int56 laterTickCumulative
) private pure returns (int24 tick) {
int56 tickDelta = soonerTickCumulative - laterTickCumulative;
tick = int24(tickDelta / timeDelta);
if (tickDelta < 0 && (tickDelta % timeDelta != 0)) tick--;
}
| 1,491,954
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {StringsUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {IFlurryStakingRewards} from "../interfaces/IFlurryStakingRewards.sol";
import {BaseRewards} from "./BaseRewards.sol";
import {ILPStakingRewards} from "../interfaces/ILPStakingRewards.sol";
import {IRhoTokenRewards} from "../interfaces/IRhoTokenRewards.sol";
/**
* @title Rewards for FLURRY Token Stakers
* @notice This reward scheme enables users to stake (lock) FLURRY tokens to earn more FLURRY tokens
* @notice FlurryToken is an ERC20 * BEP20 compliant token with 18 decimals.
* @dev all FLURRY rewards in the flurry protocol are held by this contract
* @dev This contract is also used by LPStakingRewards & RhoTokenRewards for claiming FLURRY
*/
contract FlurryStakingRewards is IFlurryStakingRewards, BaseRewards {
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @dev events
event FlurryRewardsRateChanged(uint256 blockNumber, uint256 rewardsRate);
event RewardsEndUpdated(uint256 blockNumber, uint256 rewardsEndBlock);
event Staked(address indexed user, uint256 blockNumber, uint256 amount);
event Withdrawn(address indexed user, uint256 blockNumber, uint256 amount);
event TotalStakesChanged(uint256 totalStakes);
/// @dev roles of other rewards contracts
bytes32 public constant LP_TOKEN_REWARDS_ROLE = keccak256("LP_TOKEN_REWARDS_ROLE");
bytes32 public constant RHO_TOKEN_REWARDS_ROLE = keccak256("RHO_TOKEN_REWARDS_ROLE");
/// @dev no. of FLURRY reward per block
uint256 public override rewardsRate;
/// @dev last block of time lock
uint256 public lockEndBlock;
/// @dev block number that staking reward was last accrued at
uint256 public lastUpdateBlock;
/// @dev staking reward entitlement per FLURRY staked
uint256 public rewardsPerTokenStored;
/// @dev last block when rewards distubution end
uint256 public rewardsEndBlock;
IERC20Upgradeable public flurryToken;
uint256 public override totalStakes;
uint256 public flurryTokenOne;
/**
* @notice UserInfo
* @param stake FLURRY stakes for each staker
* @param rewardPerTokenPaid amount of reward already paid to staker per token
* @param reward accumulated FLURRY reward
*/
struct UserInfo {
uint256 stake;
uint256 rewardPerTokenPaid;
uint256 reward;
}
mapping(address => UserInfo) public userInfo;
ILPStakingRewards public override lpStakingRewards;
IRhoTokenRewards public override rhoTokenRewards;
/**
* @notice initialize function is used in place of constructor for upgradeability
* @dev Have to call initializers in the parent classes to proper initialize
*/
function initialize(address flurryTokenAddr) external initializer notZeroAddr(flurryTokenAddr) {
BaseRewards.__initialize();
flurryToken = IERC20Upgradeable(flurryTokenAddr);
flurryTokenOne = getTokenOne(flurryTokenAddr);
}
function totalRewardsPool() external view override returns (uint256) {
return _totalRewardsPool();
}
function _totalRewardsPool() internal view returns (uint256) {
return flurryToken.balanceOf(address(this)) - totalStakes;
}
function stakeOf(address user) external view override notZeroAddr(user) returns (uint256) {
return userInfo[user].stake;
}
function rewardOf(address user) external view override notZeroAddr(user) returns (uint256) {
return _earned(user);
}
function claimableRewardOf(address user) external view override notZeroAddr(user) returns (uint256) {
return block.number >= lockEndBlock ? _earned(user) : 0;
}
function lastBlockApplicable() internal view returns (uint256) {
return _lastBlockApplicable(rewardsEndBlock);
}
function rewardsPerToken() public view override returns (uint256) {
if (totalStakes == 0) return rewardsPerTokenStored;
return
rewardPerTokenInternal(
rewardsPerTokenStored,
lastBlockApplicable() - lastUpdateBlock,
rewardRatePerTokenInternal(rewardsRate, flurryTokenOne, 1, totalStakes, 1)
);
}
function rewardRatePerTokenStaked() external view override returns (uint256) {
if (totalStakes == 0) return type(uint256).max;
return rewardRatePerTokenInternal(rewardsRate, flurryTokenOne, 1, totalStakes, 1);
}
function updateRewardInternal() internal {
rewardsPerTokenStored = rewardsPerToken();
lastUpdateBlock = lastBlockApplicable();
}
function updateReward(address addr) internal {
updateRewardInternal();
if (addr != address(0)) {
userInfo[addr].reward = _earned(addr);
userInfo[addr].rewardPerTokenPaid = rewardsPerTokenStored;
}
}
function _earned(address addr) internal view returns (uint256) {
return
super._earned(
userInfo[addr].stake,
rewardsPerToken() - userInfo[addr].rewardPerTokenPaid,
flurryTokenOne,
userInfo[addr].reward
);
}
function setRewardsRate(uint256 newRewardsRate) external override onlyRole(DEFAULT_ADMIN_ROLE) whenNotPaused {
updateRewardInternal();
rewardsRate = newRewardsRate;
emit FlurryRewardsRateChanged(block.number, rewardsRate);
}
function startRewards(uint256 rewardsDuration)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
whenNotPaused
isValidDuration(rewardsDuration)
{
require(block.number > rewardsEndBlock, "Previous rewards period must complete before starting a new one");
updateRewardInternal();
lastUpdateBlock = block.number;
rewardsEndBlock = block.number + rewardsDuration;
emit RewardsEndUpdated(block.number, rewardsEndBlock);
}
function endRewards() external override onlyRole(DEFAULT_ADMIN_ROLE) whenNotPaused {
if (rewardsEndBlock > block.number) {
rewardsEndBlock = block.number;
emit RewardsEndUpdated(block.number, rewardsEndBlock);
}
}
function isLocked() external view override returns (bool) {
return block.number <= lockEndBlock;
}
function setTimeLock(uint256 lockDuration) external override onlyRole(DEFAULT_ADMIN_ROLE) whenNotPaused {
lockEndBlock = block.number + lockDuration;
}
function earlyUnlock() external override onlyRole(DEFAULT_ADMIN_ROLE) whenNotPaused {
lockEndBlock = block.number;
}
function setTimeLockEndBlock(uint256 _lockEndBlock) external override onlyRole(DEFAULT_ADMIN_ROLE) whenNotPaused {
lockEndBlock = _lockEndBlock;
}
function stake(uint256 amount) external override whenNotPaused nonReentrant {
address user = _msgSender();
// check and update
require(amount > 0, "Cannot stake 0 tokens");
require(flurryToken.balanceOf(user) >= amount, "Not Enough balance to stake");
updateReward(user);
// state change
userInfo[user].stake += amount;
totalStakes += amount;
// interaction
flurryToken.safeTransferFrom(user, address(this), amount);
emit Staked(user, block.number, amount);
emit TotalStakesChanged(totalStakes);
}
function withdraw(uint256 amount) external override whenNotPaused nonReentrant {
_withdrawUser(_msgSender(), amount);
}
function _withdrawUser(address user, uint256 amount) internal {
// check and update
require(amount > 0, "Cannot withdraw 0 amount");
require(userInfo[user].stake >= amount, "Exceeds staked amount");
updateReward(user);
// state change
userInfo[user].stake -= amount;
totalStakes -= amount;
// interaction
flurryToken.safeTransfer(user, amount);
emit Withdrawn(user, block.number, amount);
emit TotalStakesChanged(totalStakes);
}
function exit() external override whenNotPaused nonReentrant {
_withdrawUser(_msgSender(), userInfo[_msgSender()].stake);
}
function claimRewardInternal(address user) internal {
if (block.number > lockEndBlock) {
updateReward(user);
if (userInfo[user].reward > 0) {
userInfo[user].reward = grantFlurryInternal(user, userInfo[user].reward);
}
}
}
function claimReward() external override whenNotPaused nonReentrant {
require(this.claimableRewardOf(_msgSender()) > 0, "nothing to claim");
claimRewardInternal(_msgSender());
}
function claimAllRewards() external override whenNotPaused nonReentrant {
require(this.totalClaimableRewardOf(_msgSender()) > 0, "nothing to claim");
if (address(lpStakingRewards) != address(0)) lpStakingRewards.claimAllReward(_msgSender());
if (address(rhoTokenRewards) != address(0)) rhoTokenRewards.claimAllReward(_msgSender());
claimRewardInternal(_msgSender());
}
function grantFlurry(address addr, uint256 amount) external override onlyLPOrRhoTokenRewards returns (uint256) {
return grantFlurryInternal(addr, amount);
}
function grantFlurryInternal(address addr, uint256 amount) internal notZeroAddr(addr) returns (uint256) {
if (amount <= _totalRewardsPool()) {
flurryToken.safeTransfer(addr, amount);
emit RewardPaid(addr, amount);
return 0;
}
emit NotEnoughBalance(addr, amount);
return amount;
}
function isStakeholder(address addr) external view notZeroAddr(addr) returns (bool) {
return userInfo[addr].stake > 0;
}
function sweepERC20Token(address token, address to) external override onlyRole(SWEEPER_ROLE) {
require(token != address(flurryToken), "!safe");
_sweepERC20Token(token, to);
}
function totalRewardOf(address user) external view override notZeroAddr(user) returns (uint256) {
uint256 otherRewards;
if (address(lpStakingRewards) != address(0)) otherRewards += lpStakingRewards.totalRewardOf(user);
if (address(rhoTokenRewards) != address(0)) otherRewards += rhoTokenRewards.totalRewardOf(user);
return otherRewards + this.rewardOf(user);
}
function totalClaimableRewardOf(address user) external view override notZeroAddr(user) returns (uint256) {
uint256 otherRewards;
if (address(lpStakingRewards) != address(0)) otherRewards += lpStakingRewards.totalClaimableRewardOf(user);
if (address(rhoTokenRewards) != address(0)) otherRewards += rhoTokenRewards.totalClaimableRewardOf(user);
return otherRewards + this.claimableRewardOf(user);
}
function setRhoTokenRewardContract(address _rhoTokenRewardAddr)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
notZeroAddr(_rhoTokenRewardAddr)
whenNotPaused
{
rhoTokenRewards = IRhoTokenRewards(_rhoTokenRewardAddr);
}
function setLPRewardsContract(address lpRewardsAddr)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
notZeroAddr(lpRewardsAddr)
whenNotPaused
{
lpStakingRewards = ILPStakingRewards(lpRewardsAddr);
}
// modified from OZ onlyRole(), allowing the checking of multiple roles
modifier onlyLPOrRhoTokenRewards() {
require(
hasRole(LP_TOKEN_REWARDS_ROLE, _msgSender()) || hasRole(RHO_TOKEN_REWARDS_ROLE, _msgSender()),
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(_msgSender()), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(LP_TOKEN_REWARDS_ROLE), 32),
" or role ",
StringsUpgradeable.toHexString(uint256(RHO_TOKEN_REWARDS_ROLE), 32)
)
)
);
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {ILPStakingRewards} from "../interfaces/ILPStakingRewards.sol";
import {IRhoTokenRewards} from "../interfaces/IRhoTokenRewards.sol";
/**
* @title Flurry Staking Rewards Interface
* @notice Interface for Flurry token staking functions
*
*/
interface IFlurryStakingRewards {
/**
* @dev equals to balance of FLURRY minus total stakes
* @return amount of FLURRY rewards available for the three reward schemes
* (Flurry Staking, LP Token Staking and rhoToken Holding)
*/
function totalRewardsPool() external view returns (uint256);
/**
* @return aggregated FLURRY stakes from all stakers (in wei)
*/
function totalStakes() external view returns (uint256);
/**
* @notice Retrieve the stake balance for a stakeholder.
* @param user Stakeholder address
* @return user staked amount (in wei)
*/
function stakeOf(address user) external view returns (uint256);
/**
* @notice A method to allow a stakeholder to check his rewards.
* @param user The stakeholder to check rewards for.
* @return Accumulated rewards of addr holder (in wei)
*/
function rewardOf(address user) external view returns (uint256);
/**
* @notice A method to allow a stakeholder to check his claimable rewards.
* @param user The stakeholder to check rewards for.
* @return Accumulated rewards of addr holder (in wei)
*/
function claimableRewardOf(address user) external view returns (uint256);
/**
* @notice A method to allow a stakeholder to check all his rewards.
* Includes Staking Rewards + RhoToken Rewards + LP Token Rewards
* @param user The stakeholder to check rewards for.
* @return Accumulated rewards of addr holder (in wei)
*/
function totalRewardOf(address user) external view returns (uint256);
/**
* @notice A method to allow a stakeholderto check his claimable rewards.
* Includes Staking Rewards + RhoToken Rewards + LP Token Rewards
* @param user The stakeholder to check rewards for
* @return Accumulated rewards of addr holder (in wei)
*/
function totalClaimableRewardOf(address user) external view returns (uint256);
/**
* @return amount of FLURRY distrubuted to all FLURRY stakers per block
*/
function rewardsRate() external view returns (uint256);
/**
* @notice Total accumulated reward per token
* @return Reward entitlement per FLURRY token staked (in wei)
*/
function rewardsPerToken() external view returns (uint256);
/**
* @notice current reward rate per FLURRY token staked
* @return rewards rate in FLURRY per block per FLURRY staked scaled by 18 decimals
*/
function rewardRatePerTokenStaked() external view returns (uint256);
/**
* @notice A method to add a stake.
* @param amount amount of flurry tokens to be staked (in wei)
*/
function stake(uint256 amount) external;
/**
* @notice A method to unstake.
* @param amount amount to unstake (in wei)
*/
function withdraw(uint256 amount) external;
/**
* @notice A method to allow a stakeholder to withdraw his FLURRY staking rewards.
*/
function claimReward() external;
/**
* @notice A method to allow a stakeholder to claim all his rewards.
*/
function claimAllRewards() external;
/**
* @notice NOT for external use
* @dev only callable by LPStakingRewards or RhoTokenRewards for FLURRY distribution
* @param addr address of LP Token staker / rhoToken holder
* @param amount amount of FLURRY token rewards to grant (in wei)
* @return outstanding amount if claim is not successful, 0 if successful
*/
function grantFlurry(address addr, uint256 amount) external returns (uint256);
/**
* @notice A method to allow a stakeholder to withdraw full stake.
* Rewards are not automatically claimed. Use claimReward()
*/
function exit() external;
/**
* @notice Admin function - set rewards rate earned for FLURRY staking per block
* @param newRewardsRate amount of FLURRY (in wei) per block
*/
function setRewardsRate(uint256 newRewardsRate) external;
/**
* @notice Admin function - A method to start rewards distribution
* @param rewardsDuration rewards duration in number of blocks
*/
function startRewards(uint256 rewardsDuration) external;
/**
* @notice Admin function - End Rewards distribution earlier, if there is one running
*/
function endRewards() external;
/**
* @return true if reward is locked, false otherwise
*/
function isLocked() external view returns (bool);
/**
* @notice Admin function - lock all rewards for all users for a given duration
* This function should be called BEFORE startRewards()
* @param lockDuration lock duration in number of blocks
*/
function setTimeLock(uint256 lockDuration) external;
/**
* @notice Admin function - unlock all rewards immediately, if there is a time lock
*/
function earlyUnlock() external;
/**
* @notice Admin function - lock FLURRY staking rewards until a specific block
* @param _lockEndBlock lock rewards until specific block no.
*/
function setTimeLockEndBlock(uint256 _lockEndBlock) external;
/**
* @notice Admin function - withdraw other ERC20 tokens sent to this contract
* @param token ERC20 token address to be sweeped
* @param to address for sending sweeped tokens to
*/
function sweepERC20Token(address token, address to) external;
/**
* @notice Admin function - set RhoTokenReward contract reference
*/
function setRhoTokenRewardContract(address rhoTokenRewardAddr) external;
/**
* @notice Admin function - set LP Rewards contract reference
*/
function setLPRewardsContract(address lpRewardsAddr) external;
/**
* @return reference to LP Staking Rewards contract
*/
function lpStakingRewards() external returns (ILPStakingRewards);
/**
* @return reference to RhoToken Rewards contract
*/
function rhoTokenRewards() external returns (IRhoTokenRewards);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
/**
* @title BaseRewards Abstract Contract
* @notice Abstract Contract to be inherited by LPStakingReward, StakingReward and RhoTokenReward.
* Implements the core logic as internal functions.
* *** Note: avoid using `super` keyword to avoid confusion because the derived contracts use multiple inheritance ***
*/
import {MathUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
import {SafeERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import {IERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {
IERC20MetadataUpgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import {
AccessControlEnumerableUpgradeable
} from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
abstract contract BaseRewards is AccessControlEnumerableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
// events
event RewardPaid(address indexed user, uint256 reward);
event NotEnoughBalance(address indexed user, uint256 withdrawalAmount);
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant SWEEPER_ROLE = keccak256("SWEEPER_ROLE");
function __initialize() internal {
AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init();
ReentrancyGuardUpgradeable.__ReentrancyGuard_init();
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function getTokenOne(address token) internal view returns (uint256) {
return 10**IERC20MetadataUpgradeable(token).decimals();
}
/**
* @notice Calculate accrued but unclaimed reward for a user
* @param _tokenBalance balance of the rhoToken, OR staking ammount of LP/FLURRY
* @param _netRewardPerToken accumulated reward minus the reward already paid to user, on a per token basis
* @param _tokenOne decimal of the token
* @param accumulatedReward accumulated reward of the user
* @return claimable reward of the user
*/
function _earned(
uint256 _tokenBalance,
uint256 _netRewardPerToken,
uint256 _tokenOne,
uint256 accumulatedReward
) internal pure returns (uint256) {
return ((_tokenBalance * _netRewardPerToken) / _tokenOne) + accumulatedReward;
}
/**
* @notice Rewards are accrued up to this block (put aside in rewardsPerTokenPaid)
* @return min(The current block # or last rewards accrual block #)
*/
function _lastBlockApplicable(uint256 _rewardsEndBlock) internal view returns (uint256) {
return MathUpgradeable.min(block.number, _rewardsEndBlock);
}
function rewardRatePerTokenInternal(
uint256 rewardRate,
uint256 tokenOne,
uint256 allocPoint,
uint256 totalToken,
uint256 totalAllocPoint
) internal pure returns (uint256) {
return (rewardRate * tokenOne * allocPoint) / (totalToken * totalAllocPoint);
}
function rewardPerTokenInternal(
uint256 accruedRewardsPerToken,
uint256 blockDelta,
uint256 rewardRatePerToken
) internal pure returns (uint256) {
return accruedRewardsPerToken + blockDelta * rewardRatePerToken;
}
/**
* admin functions to withdraw random token transfer to this contract
*/
function _sweepERC20Token(address token, address to) internal notZeroTokenAddr(token) {
IERC20Upgradeable tokenToSweep = IERC20Upgradeable(token);
tokenToSweep.safeTransfer(to, tokenToSweep.balanceOf(address(this)));
}
/** Pausable */
function pause() external onlyRole(PAUSER_ROLE) {
_pause();
}
function unpause() external onlyRole(PAUSER_ROLE) {
_unpause();
}
modifier notZeroAddr(address addr) {
require(addr != address(0), "address is zero");
_;
}
modifier notZeroTokenAddr(address addr) {
require(addr != address(0), "token address is zero");
_;
}
modifier isValidDuration(uint256 rewardDuration) {
require(rewardDuration > 0, "Reward duration cannot be zero");
_;
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {IFlurryStakingRewards} from "../interfaces/IFlurryStakingRewards.sol";
/**
* @title LP Staking Rewards Interface
* @notice Interface for FLURRY token rewards when staking LP tokens
*/
interface ILPStakingRewards {
/**
* @notice checks whether the staking of a LP token is supported by the reward scheme
* @param lpToken address of LP Token contract
* @return true if the reward scheme supports `lpToken`, false otherwise
*/
function isSupported(address lpToken) external returns (bool);
/**
* @param user user address
* @return list of addresses of LP user has engaged in
*/
function getUserEngagedPool(address user) external view returns (address[] memory);
/**
* @return list of addresses of LP registered in this contract
*/
function getPoolList() external view returns (address[] memory);
/**
* @return amount of FLURRY distrubuted for all LP per block,
* to be shared by the staking pools according to allocation points
*/
function rewardsRate() external view returns (uint256);
/**
* @notice Admin function - set rewards rate earned for all LP per block
* @param newRewardsRate amount of FLURRY (in wei) per block
*/
function setRewardsRate(uint256 newRewardsRate) external;
/**
* @notice Retrieve the stake balance for a stakeholder.
* @param addr Stakeholder address
* @param lpToken Address of LP Token contract
* @return user staked amount (in wei)
*/
function stakeOf(address addr, address lpToken) external view returns (uint256);
/**
* @notice A method to allow a stakeholder to check his rewards for one LP token
* @param user The stakeholder to check rewards for
* @param lpToken Address of LP Token contract
* @return Accumulated rewards of addr holder (in wei)
*/
function rewardOf(address user, address lpToken) external view returns (uint256);
/**
* @notice A method to allow a stakeholder to check his rewards earned for all LP token
* @param user The stakeholder to check rewards for
* @return Accumulated rewards of addr holder (in wei)
*/
function totalRewardOf(address user) external view returns (uint256);
/**
* @notice A method to allow a stakeholder to check his claimble rewards for all LP token
* @param user The stakeholder to check rewards for
* @return Accumulated rewards of addr holder (in wei)
*/
function totalClaimableRewardOf(address user) external view returns (uint256);
/**
* @notice A method to add a stake.
* @param lpToken Address of LP Token contract
* @param amount amount of flurry tokens to be staked (in wei)
*/
function stake(address lpToken, uint256 amount) external;
/**
* @notice NOT for external use
* @dev allows Flurry Staking Rewards contract to claim rewards for one LP on behalf of a user
* @param onBehalfOf address of the user to claim rewards for
* @param lpToken Address of LP Token contract
*/
function claimReward(address onBehalfOf, address lpToken) external;
/**
* @notice A method to allow a LP token holder to claim his rewards for one LP token
* @param lpToken Address of LP Token contract
* Note: If stakingRewards contract do not have enough tokens to pay,
* this will fail silently and user rewards remains as a credit in this contract
*/
function claimReward(address lpToken) external;
/**
* @notice NOT for external use
* @dev allows Flurry Staking Rewards contract to claim rewards for all LP on behalf of a user
* @param onBehalfOf address of the user to claim rewards for
*/
function claimAllReward(address onBehalfOf) external;
/**
* @notice A method to allow a LP token holder to claim his rewards for all LP token
* Note: If stakingRewards contract do not have enough tokens to pay,
* this will fail silently and user rewards remains as a credit in this contract
*/
function claimAllReward() external;
/**
* @notice A method to unstake.
* @param lpToken Address of LP Token contract
* @param amount amount to unstake (in wei)
*/
function withdraw(address lpToken, uint256 amount) external;
/**
* @notice A method to allow a stakeholder to withdraw full stake.
* @param lpToken Address of LP Token contract
* Rewards are not automatically claimed. Use claimReward()
*/
function exit(address lpToken) external;
/**
* @notice Total accumulated reward per token
* @param lpToken Address of LP Token contract
* @return Reward entitlement per LP token staked (in wei)
*/
function rewardsPerToken(address lpToken) external view returns (uint256);
/**
* @notice current reward rate per LP token staked
* @param lpToken Address of LP Token contract
* @return rewards rate in FLURRY per block per LP staked scaled by 18 decimals
*/
function rewardRatePerTokenStaked(address lpToken) external view returns (uint256);
/**
* @notice Admin function - A method to set reward duration
* @param lpToken Address of LP Token contract
* @param rewardDuration Reward Duration in number of blocks
*/
function startRewards(address lpToken, uint256 rewardDuration) external;
/**
* @notice Admin function - End Rewards distribution earlier if there is one running
* @param lpToken Address of LP Token contract
*/
function endRewards(address lpToken) external;
/**
* @return true if rewards are locked for given lpToken, false if rewards are unlocked or if lpTokenis not supported
* @param lpToken address of LP Token contract
*/
function isLocked(address lpToken) external view returns (bool);
/**
* @notice Admin function - lock rewards for given lpToken
* @param lpToken address of the lpToken contract
* @param lockDuration lock duration in number of blocks
*/
function setTimeLock(address lpToken, uint256 lockDuration) external;
/**
* @notice Admin function - lock rewards for given lpToken until a specific block
* @param lpToken address of the lpToken contract
* @param lockEndBlock lock rewards until specific block no.
*/
function setTimeLockEndBlock(address lpToken, uint256 lockEndBlock) external;
/**
* @notice Admin function - lock all lpToken rewards
* @param lockDuration lock duration in number of blocks
*/
function setTimeLockForAllLPTokens(uint256 lockDuration) external;
/**
* @notice Admin function - lock all lpToken rewards until a specific block
* @param lockEndBlock lock rewards until specific block no.
*/
function setTimeLockEndBlockForAllLPTokens(uint256 lockEndBlock) external;
/**
* @notice Admin function - unlock rewards for given lpToken
* @param lpToken address of the lpToken contract
*/
function earlyUnlock(address lpToken) external;
/**
* @param lpToken address of the lpToken contract
* @return the current lock end block number
*/
function getLockEndBlock(address lpToken) external view returns (uint256);
/**
* @notice Admin function - register a LP to this contract
* @param lpToken address of the LP to be registered
* @param allocPoint allocation points (weight) assigned to the given LP
*/
function addLP(address lpToken, uint256 allocPoint) external;
/**
* @notice Admin function - change the allocation points of a LP registered in this contract
* @param lpToken address of the LP subject to change
* @param allocPoint allocation points (weight) assigned to the given LP
*/
function setLP(address lpToken, uint256 allocPoint) external;
/**
* @notice Admin function - withdraw random token transfer to this contract
* @param token ERC20 token address to be sweeped
* @param to address for sending sweeped tokens to
*/
function sweepERC20Token(address token, address to) external;
/**
* @return reference to RhoToken Rewards contract
*/
function flurryStakingRewards() external returns (IFlurryStakingRewards);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import {IFlurryStakingRewards} from "../interfaces/IFlurryStakingRewards.sol";
/**
* @title RhoToken Rewards Interface
* @notice Interface for bonus FLURRY token rewards contract for RhoToken holders
*/
interface IRhoTokenRewards {
/**
* @notice checks whether the rewards for a rhoToken is supported by the reward scheme
* @param rhoToken address of rhoToken contract
* @return true if the reward scheme supports `rhoToken`, false otherwise
*/
function isSupported(address rhoToken) external returns (bool);
/**
* @return list of addresses of rhoTokens registered in this contract
*/
function getRhoTokenList() external view returns (address[] memory);
/**
* @return amount of FLURRY distributed for all rhoTokens per block
*/
function rewardsRate() external view returns (uint256);
/**
* @notice Admin function - set reward rate earned for all rhoTokens per block
* @param newRewardsRate amount of FLURRY (in wei) per block
*/
function setRewardsRate(uint256 newRewardsRate) external;
/**
* @notice A method to allow a stakeholder to check his rewards.
* @param user The stakeholder to check rewards for.
* @param rhoToken Address of rhoToken contract
* @return Accumulated rewards of addr holder (in wei)
*/
function rewardOf(address user, address rhoToken) external view returns (uint256);
/**
* @notice A method to allow a stakeholder to check his rewards for all rhoToken
* @param user The stakeholder to check rewards for
* @return Accumulated rewards of addr holder (in wei)
*/
function totalRewardOf(address user) external view returns (uint256);
/**
* @notice A method to allow a stakeholder to check his rewards for all rhoToken
* @param user The stakeholder to check rewards for
* @return Accumulated rewards of addr holder (in wei)
*/
function totalClaimableRewardOf(address user) external view returns (uint256);
/**
* @notice Total accumulated reward per token
* @param rhoToken Address of rhoToken contract
* @return Reward entitlement for rho token
*/
function rewardsPerToken(address rhoToken) external view returns (uint256);
/**
* @notice current reward rate per token staked
* @param rhoToken Address of rhoToken contract
* @return reward rate denominated in FLURRY per block
*/
function rewardRatePerRhoToken(address rhoToken) external view returns (uint256);
/**
* @notice Admin function - A method to set reward duration
* @param rhoToken Address of rhoToken contract
* @param rewardDuration Reward duration in number of blocks
*/
function startRewards(address rhoToken, uint256 rewardDuration) external;
/**
* @notice Admin function - End Rewards distribution earlier, if there is one running
* @param rhoToken Address of rhoToken contract
*/
function endRewards(address rhoToken) external;
/**
* @notice Calculate and allocate rewards token for address holder
* Rewards should accrue from _lastUpdateBlock to lastBlockApplicable
* rewardsPerToken is based on the total supply of the RhoToken, hence
* this function needs to be called every time total supply changes
* @dev intended to be called externally by RhoToken contract modifier, and internally
* @param user the user to update reward for
* @param rhoToken the rhoToken to update reward for
*/
function updateReward(address user, address rhoToken) external;
/**
* @notice NOT for external use
* @dev allows Flurry Staking Rewards contract to claim rewards for one rhoToken on behalf of a user
* @param onBehalfOf address of the user to claim rewards for
* @param rhoToken Address of rhoToken contract
*/
function claimReward(address onBehalfOf, address rhoToken) external;
/**
* @notice A method to allow a rhoToken holder to claim his rewards for one rhoToken
* @param rhoToken Address of rhoToken contract
* Note: If stakingRewards contract do not have enough tokens to pay,
* this will fail silently and user rewards remains as a credit in this contract
*/
function claimReward(address rhoToken) external;
/**
* @notice NOT for external use
* @dev allows Flurry Staking Rewards contract to claim rewards for all rhoTokens on behalf of a user
* @param onBehalfOf address of the user to claim rewards for
*/
function claimAllReward(address onBehalfOf) external;
/**
* @notice A method to allow a rhoToken holder to claim his rewards for all rhoTokens
* Note: If stakingRewards contract do not have enough tokens to pay,
* this will fail silently and user rewards remains as a credit in this contract
*/
function claimAllReward() external;
/**
* @return true if rewards are locked for given rhoToken, false if rewards are unlocked or if rhoToken is not supported
* @param rhoToken address of rhoToken contract
*/
function isLocked(address rhoToken) external view returns (bool);
/**
* @notice Admin function - lock rewards for given rhoToken
* @param rhoToken address of the rhoToken contract
* @param lockDuration lock duration in number of blocks
*/
function setTimeLock(address rhoToken, uint256 lockDuration) external;
/**
* @notice Admin function - lock rewards for given rhoToken until a specific block
* @param rhoToken address of the rhoToken contract
* @param lockEndBlock lock rewards until specific block no.
*/
function setTimeLockEndBlock(address rhoToken, uint256 lockEndBlock) external;
/**
* @notice Admin function - lock all rho Staking rewards
* @param lockDuration lock duration in number of blocks
*/
function setTimeLockForAllRho(uint256 lockDuration) external;
/**
* @notice Admin function - lock all rho Staking rewards until a specific block
* @param lockEndBlock lock rewards until specific block no.
*/
function setTimeLockEndBlockForAllRho(uint256 lockEndBlock) external;
/**
* @notice Admin function - unlock rewards for given rhoToken
* @param rhoToken address of the rhoToken contract
*/
function earlyUnlock(address rhoToken) external;
/**
* @param rhoToken address of the rhoToken contract
* @return the current lock end block number
*/
function getLockEndBlock(address rhoToken) external view returns (uint256);
/**
* @notice Admin function - register a rhoToken to this contract
* @param rhoToken address of the rhoToken to be registered
* @param allocPoint allocation points (weight) assigned to the given rhoToken
*/
function addRhoToken(address rhoToken, uint256 allocPoint) external;
/**
* @notice Admin function - change the allocation points of a rhoToken registered in this contract
* @param rhoToken address of the rhoToken subject to change
* @param allocPoint allocation points (weight) assigned to the given rhoToken
*/
function setRhoToken(address rhoToken, uint256 allocPoint) external;
/**
* @notice Admin function - withdraw random token transfer to this contract
* @param token ERC20 token address to be sweeped
* @param to address for sending sweeped tokens to
*/
function sweepERC20Token(address token, address to) external;
/**
* @return reference to RhoToken Rewards contract
*/
function flurryStakingRewards() external returns (IFlurryStakingRewards);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @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.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Flurry Staking Rewards Interface Interface for Flurry token staking functions/
|
interface IFlurryStakingRewards {
function totalRewardsPool() external view returns (uint256);
function totalStakes() external view returns (uint256);
function stakeOf(address user) external view returns (uint256);
function rewardOf(address user) external view returns (uint256);
function claimableRewardOf(address user) external view returns (uint256);
function totalRewardOf(address user) external view returns (uint256);
function totalClaimableRewardOf(address user) external view returns (uint256);
function rewardsRate() external view returns (uint256);
function rewardsPerToken() external view returns (uint256);
function rewardRatePerTokenStaked() external view returns (uint256);
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function claimReward() external;
function claimAllRewards() external;
function grantFlurry(address addr, uint256 amount) external returns (uint256);
function exit() external;
function setRewardsRate(uint256 newRewardsRate) external;
function startRewards(uint256 rewardsDuration) external;
function endRewards() external;
function isLocked() external view returns (bool);
function setTimeLock(uint256 lockDuration) external;
function earlyUnlock() external;
function setTimeLockEndBlock(uint256 _lockEndBlock) external;
function sweepERC20Token(address token, address to) external;
function setRhoTokenRewardContract(address rhoTokenRewardAddr) external;
function setLPRewardsContract(address lpRewardsAddr) external;
function lpStakingRewards() external returns (ILPStakingRewards);
function rhoTokenRewards() external returns (IRhoTokenRewards);
}
pragma solidity 0.8.4;
import {ILPStakingRewards} from "../interfaces/ILPStakingRewards.sol";
import {IRhoTokenRewards} from "../interfaces/IRhoTokenRewards.sol";
}
| 6,305,819
|
/**
*Submitted for verification at BscScan.com on 2021-03-22
*/
pragma solidity >=0.4.22 <0.6.0;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title 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;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) public _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply = 0;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address 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;
}
}
contract Pausable is Ownable {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
function paused() public view returns (bool) {
return _paused;
}
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
function pause() public onlyOwner whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
function unpause() public onlyOwner whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
contract OlaCoin is ERC20, Pausable, ERC20Detailed {
address teamWallet = 0x61a76b4B4966276C29Eec50994Bd7e3df5a45BE5;
address serviceWallet = 0xc12fc289028092ae0FeA8a25F1992fF99f458FAb;
address partnerWallet = 0x4Cbf2dE71Cd129B8b62bB302Fd7a324Dd0886E9C;
address bountyWallet = 0xcECB0446adaDE379b47989E0EF6fca3b15B0fc2E;
uint256 private totalCoins;
struct LockItem {
uint256 releaseDate;
uint256 amount;
}
mapping (address => LockItem[]) public lockList;
mapping (uint => uint) public quarterMap;
address [] private lockedAddressList; // list of addresses that have some fund currently or previously locked
constructor() public ERC20Detailed("Ola Coin", "OLA", 6) {
quarterMap[1]=1609459200;//=Fri, 01 Jan 2021 00:00:00 GMT
quarterMap[2]=1617235200;//=Thu, 01 Apr 2021 00:00:00 GMT
quarterMap[3]=1625097600;//=Thu, 01 Jul 2021 00:00:00 GMT
quarterMap[4]=1633046400;//=Fri, 01 Oct 2021 00:00:00 GMT
quarterMap[5]=1640995200;//=Sat, 01 Jan 2022 00:00:00 GMT
quarterMap[6]=1648771200;//=Fri, 01 Apr 2022 00:00:00 GMT
quarterMap[7]=1656633600;//=Fri, 01 Jul 2022 00:00:00 GMT
quarterMap[8]=1664582400;//=Sat, 01 Oct 2022 00:00:00 GMT
quarterMap[9]=1672531200;//=Sun, 01 Jan 2023 00:00:00 GMT
quarterMap[10]=1680307200;//=Sat, 01 Apr 2023 00:00:00 GMT
quarterMap[11]=1688169600;//=Sat, 01 Jul 2023 00:00:00 GMT
quarterMap[12]=1696118400;//=Sun, 01 Oct 2023 00:00:00 GMT
quarterMap[13]=1704067200;//=Mon, 01 Jan 2024 00:00:00 GMT
quarterMap[14]=1711929600;//=Mon, 01 Apr 2024 00:00:00 GMT
quarterMap[15]=1719792000;//=Mon, 01 Jul 2024 00:00:00 GMT
quarterMap[16]=1727740800;//=Tue, 01 Oct 2024 00:00:00 GMT
quarterMap[17]=1735689600;//=Wed, 01 Jan 2025 00:00:00 GMT
quarterMap[18]=1743465600;//=Tue, 01 Apr 2025 00:00:00 GMT
quarterMap[19]=1751328000;//=Tue, 01 Jul 2025 00:00:00 GMT
quarterMap[20]=1759276800;//=Wed, 01 Oct 2025 00:00:00 GMT
quarterMap[21]=1767225600;//=Thu, 01 Jan 2026 00:00:00 GMT
quarterMap[22]=1775001600;//=Wed, 01 Apr 2026 00:00:00 GMT
quarterMap[23]=1782864000;//=Wed, 01 Jul 2026 00:00:00 GMT
quarterMap[24]=1790812800;//=Thu, 01 Oct 2026 00:00:00 GMT
quarterMap[25]=1798761600;//=Fri, 01 Jan 2027 00:00:00 GMT
quarterMap[26]=1806537600;//=Thu, 01 Apr 2027 00:00:00 GMT
quarterMap[27]=1814400000;//=Thu, 01 Jul 2027 00:00:00 GMT
quarterMap[28]=1822348800;//=Fri, 01 Oct 2027 00:00:00 GMT
quarterMap[29]=1830297600;//=Sat, 01 Jan 2028 00:00:00 GMT
quarterMap[30]=1838160000;//=Sat, 01 Apr 2028 00:00:00 GMT
quarterMap[31]=1846022400;//=Sat, 01 Jul 2028 00:00:00 GMT
quarterMap[32]=1853971200;//=Sun, 01 Oct 2028 00:00:00 GMT
quarterMap[33]=1861920000;//=Mon, 01 Jan 2029 00:00:00 GMT
quarterMap[34]=1869696000;//=Sun, 01 Apr 2029 00:00:00 GMT
quarterMap[35]=1877558400;//=Sun, 01 Jul 2029 00:00:00 GMT
quarterMap[36]=1885507200;//=Mon, 01 Oct 2029 00:00:00 GMT
quarterMap[37]=1893456000;//=Tue, 01 Jan 2030 00:00:00 GMT
quarterMap[38]=1901232000;//=Mon, 01 Apr 2030 00:00:00 GMT
quarterMap[39]=1909094400;//=Mon, 01 Jul 2030 00:00:00 GMT
totalCoins = 100000000000 * 10 ** uint256(decimals());
_mint(owner(), totalCoins); // total supply fixed at 100 billion coins
ERC20.transfer(teamWallet, 9000000000 * 10 ** uint256(decimals()));
ERC20.transfer(partnerWallet, 9000000000 * 10 ** uint256(decimals()));
ERC20.transfer(serviceWallet, 2000000000 * 10 ** uint256(decimals()));
ERC20.transfer(bountyWallet, 2000000000 * 10 ** uint256(decimals()));
for(uint i = 1; i<= 39;i++) {
transferAndLock(serviceWallet, 2000000000 * 10 ** uint256(decimals()), quarterMap[i]);
}
}
/**
* @dev transfer of token to another address.
* always require the sender has enough balance
* @return the bool true if success.
* @param _receiver The address to transfer to.
* @param _amount The amount to be transferred.
*/
function transfer(address _receiver, uint256 _amount) public whenNotPaused returns (bool success) {
require(_receiver != address(0));
require(_amount <= getAvailableBalance(msg.sender));
return ERC20.transfer(_receiver, _amount);
}
/**
* @dev transfer of token on behalf of the owner to another address.
* always require the owner has enough balance and the sender is allowed to transfer the given amount
* @return the bool true if success.
* @param _from The address to transfer from.
* @param _receiver The address to transfer to.
* @param _amount The amount to be transferred.
*/
function transferFrom(address _from, address _receiver, uint256 _amount) public whenNotPaused returns (bool) {
require(_from != address(0));
require(_receiver != address(0));
require(_amount <= allowance(_from, msg.sender));
require(_amount <= getAvailableBalance(_from));
return ERC20.transferFrom(_from, _receiver, _amount);
}
/**
* @dev transfer to a given address a given amount and lock this fund until a given time
* used for sending fund to team members, partners, or for owner to lock service fund over time
* @return the bool true if success.
* @param _receiver The address to transfer to.
* @param _amount The amount to transfer.
* @param _releaseDate The date to release token.
*/
function transferAndLock(address _receiver, uint256 _amount, uint256 _releaseDate) public whenNotPaused returns (bool success) {
require(msg.sender == teamWallet || msg.sender == partnerWallet || msg.sender == owner());
ERC20._transfer(msg.sender,_receiver,_amount);
if (lockList[_receiver].length==0) lockedAddressList.push(_receiver);
LockItem memory item = LockItem({amount:_amount, releaseDate:_releaseDate});
lockList[_receiver].push(item);
return true;
}
/**
* @return the total amount of locked funds of a given address.
* @param lockedAddress The address to check.
*/
function getLockedAmount(address lockedAddress) public view returns(uint256 _amount) {
uint256 lockedAmount =0;
for(uint256 j = 0; j<lockList[lockedAddress].length; j++) {
if(now < lockList[lockedAddress][j].releaseDate) {
uint256 temp = lockList[lockedAddress][j].amount;
lockedAmount += temp;
}
}
return lockedAmount;
}
/**
* @return the total amount of locked funds of a given address.
* @param lockedAddress The address to check.
*/
function getAvailableBalance(address lockedAddress) public view returns(uint256 _amount) {
uint256 bal = balanceOf(lockedAddress);
uint256 locked = getLockedAmount(lockedAddress);
return bal.sub(locked);
}
/**
* @dev function that burns an amount of the token of a given account.
* @param _amount The amount that will be burnt.
*/
function burn(uint256 _amount) public whenNotPaused {
_burn(msg.sender, _amount);
}
function () payable external {
revert();
}
// the following functions are useful for frontend dApps
/**
* @return the list of all addresses that have at least a fund locked currently or in the past
*/
function getLockedAddresses() public view returns (address[] memory) {
return lockedAddressList;
}
/**
* @return the number of addresses that have at least a fund locked currently or in the past
*/
function getNumberOfLockedAddresses() public view returns (uint256 _count) {
return lockedAddressList.length;
}
/**
* @return the number of addresses that have at least a fund locked currently
*/
function getNumberOfLockedAddressesCurrently() public view returns (uint256 _count) {
uint256 count=0;
for(uint256 i = 0; i<lockedAddressList.length; i++) {
if (getLockedAmount(lockedAddressList[i])>0) count++;
}
return count;
}
/**
* @return the list of all addresses that have at least a fund locked currently
*/
function getLockedAddressesCurrently() public view returns (address[] memory) {
address [] memory list = new address[](getNumberOfLockedAddressesCurrently());
uint256 j = 0;
for(uint256 i = 0; i<lockedAddressList.length; i++) {
if (getLockedAmount(lockedAddressList[i])>0) {
list[j] = lockedAddressList[i];
j++;
}
}
return list;
}
/**
* @return the total amount of locked funds at the current time
*/
function getLockedAmountTotal() public view returns(uint256 _amount) {
uint256 sum =0;
for(uint256 i = 0; i<lockedAddressList.length; i++) {
uint256 lockedAmount = getLockedAmount(lockedAddressList[i]);
sum = sum.add(lockedAmount);
}
return sum;
}
/**
* @return the total amount of circulating coins that are not locked at the current time
*
*/
function getCirculatingSupplyTotal() public view returns(uint256 _amount) {
return totalSupply().sub(getLockedAmountTotal());
}
/**
* @return the total amount of burned coins
*
*/
function getBurnedAmountTotal() public view returns(uint256 _amount) {
return totalCoins.sub(totalSupply());
}
}
|
function that burns an amount of the token of a given account. _amount The amount that will be burnt./
|
function burn(uint256 _amount) public whenNotPaused {
_burn(msg.sender, _amount);
}
| 1,001,122
|
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
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;
}
}
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;
}
}
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));
}
}
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);
}
}
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;
}
}
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 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");
}
}
}
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");
}
}
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;
}
}
}
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);
}
}
contract Migrations {
address public owner;
uint256 public last_completed_migration;
constructor() public {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner) _;
}
function setCompleted(uint256 completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
library FixedPoint {
using SafeMath for uint256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// 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;
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**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);
}
}
}
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;
}
}
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]);
}
}
}
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"
);
}
}
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
}
}
}
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;
}
}
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;
}
}
abstract contract Balancer {
function getSpotPriceSansFee(address tokenIn, address tokenOut) external virtual view returns (uint256 spotPrice);
}
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);
}
abstract contract OneSplit {
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) public virtual view returns (uint256 returnAmount, uint256[] memory distribution);
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) public virtual payable returns (uint256 returnAmount);
}
abstract contract Uniswap {
// Called after every swap showing the new uniswap "price" for this token pair.
event Sync(uint112 reserve0, uint112 reserve1);
}
contract BalancerMock is Balancer {
uint256 price = 0;
// these params arent used in the mock, but this is to maintain compatibility with balancer API
function getSpotPriceSansFee(address tokenIn, address tokenOut)
external
virtual
override
view
returns (uint256 spotPrice)
{
return price;
}
// this is not a balancer call, but for testing for changing price.
function setPrice(uint256 newPrice) external {
price = newPrice;
}
}
contract FixedPointTest {
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;
}
}
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) {}
}
contract OneSplitMock is OneSplit {
address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
mapping(bytes32 => uint256) prices;
receive() external payable {}
// Sets price of 1 FROM = <PRICE> TO
function setPrice(
address from,
address to,
uint256 price
) external {
prices[keccak256(abi.encodePacked(from, to))] = price;
}
function getExpectedReturn(
address fromToken,
address destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) public override view returns (uint256 returnAmount, uint256[] memory distribution) {
returnAmount = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount;
return (returnAmount, distribution);
}
function swap(
address fromToken,
address destToken,
uint256 amount,
uint256 minReturn,
uint256[] memory distribution,
uint256 flags
) public override payable returns (uint256 returnAmount) {
uint256 amountReturn = prices[keccak256(abi.encodePacked(fromToken, destToken))] * amount;
require(amountReturn >= minReturn, "Min Amount not reached");
if (destToken == ETH_ADDRESS) {
msg.sender.transfer(amountReturn);
} else {
require(IERC20(destToken).transfer(msg.sender, amountReturn), "erc20-send-failed");
}
}
}
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");
}
}
contract ReentrancyChecker {
bytes public txnData;
bool hasBeenCalled;
// Used to prevent infinite cycles where the reentrancy is cycled forever.
modifier skipIfReentered {
if (hasBeenCalled) {
return;
}
hasBeenCalled = true;
_;
hasBeenCalled = false;
}
function setTransactionData(bytes memory _txnData) public {
txnData = _txnData;
}
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool success) {
// 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
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
}
fallback() external skipIfReentered {
// Attampt to re-enter with the set txnData.
bool success = _executeCall(msg.sender, 0, txnData);
// Fail if the call succeeds because that means the re-entrancy was successful.
require(!success, "Re-entrancy was successful");
}
}
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;
}
}
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);
}
}
contract UniswapMock is Uniswap {
function setPrice(uint112 reserve0, uint112 reserve1) external {
emit Sync(reserve0, reserve1);
}
}
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);
}
}
abstract contract FeePayer is 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 {
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) nonReentrant() {
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 totalPaid) {
StoreInterface store = _getStore();
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Exit early if there is no collateral from which to pay fees.
if (collateralPool.isEqual(0)) {
return totalPaid;
}
// Exit early if fees were already paid during this block.
if (lastPaymentTime == time) {
return totalPaid;
}
(FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) = store.computeRegularFee(
lastPaymentTime,
time,
collateralPool
);
lastPaymentTime = time;
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return 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;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
_adjustCumulativeFeeMultiplier(totalPaid, collateralPool);
if (regularFee.isGreaterThan(0)) {
collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), regularFee);
}
if (latePenalty.isGreaterThan(0)) {
collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue);
}
return totalPaid;
}
/**
* @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() public view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _pfc();
}
/****************************************
* 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%.
require(collateralPool.isGreaterThan(amount), "Final fee is more than PfC");
_adjustCumulativeFeeMultiplier(amount, collateralPool);
}
emit FinalFeesPaid(amount.rawValue);
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), amount);
}
function _pfc() internal virtual view 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);
}
// 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));
}
}
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));
}
}
contract WETH9 {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint256 wad);
event Transfer(address indexed src, address indexed dst, uint256 wad);
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
receive() external payable {
deposit();
}
fallback() external payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint256 wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
emit Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint256) {
return address(this).balance;
}
function approve(address guy, uint256 wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint256 wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(
address src,
address dst,
uint256 wad
) public returns (bool) {
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint256(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
emit Transfer(src, dst, wad);
return true;
}
}
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);
}
}
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";
}
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);
}
}
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,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, hash);
}
/**
* @notice Forwards a batch commit to Voting.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(VotingInterface.Commitment[] 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,
int256 salt
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().revealVote(identifier, time, price, 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(VotingInterface.Reveal[] 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, VotingInterface.PendingRequest[] memory toRetrieve)
public
onlyRoleHolder(uint256(Roles.Voter))
returns (FixedPoint.Unsigned memory)
{
return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve);
}
function _getVotingAddress() private view returns (VotingInterface) {
return VotingInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
}
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) {
require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted");
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 {
require(address(designatedVotingContracts[msg.sender]) == address(0), "Duplicate hot key not permitted");
designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress);
}
}
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();
}
}
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;
}
}
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];
}
}
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");
}
}
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(VotingInterface.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(VotingInterface.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 (VotingInterface.Phase) {
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return
VotingInterface.Phase(
currentTime.div(data.phaseLength).mod(uint256(VotingInterface.Phase.NUM_PHASES_PLACEHOLDER))
);
}
}
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);
}
}
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;
}
}
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 (VotingInterface.Phase) {
return voteTiming.computeCurrentPhase(currentTime);
}
function wrapInit(uint256 phaseLength) public {
voteTiming.init(phaseLength);
}
}
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;
}
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);
}
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);
}
interface 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) external;
/**
* @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) external view 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) external view returns (int256);
}
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);
}
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);
}
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;
}
// 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,
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[] calldata commits) external 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
) external 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[] calldata reveals) external 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 virtual view returns (PendingRequest[] 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 virtual view 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 virtual view 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);
}
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) external 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) external override view 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) external override view 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));
}
}
contract Umip15Upgrader {
// 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;
constructor(
address _governor,
address _existingVoting,
address _newVoting,
address _finder
) public {
governor = _governor;
existingVoting = Voting(_existingVoting);
newVoting = _newVoting;
finder = Finder(_finder);
}
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 current Voting contract to migrated.
existingVoting.setMigrated(newVoting);
// Transfer back ownership of old voting contract and the finder to the governor.
existingVoting.transferOwnership(governor);
finder.transferOwnership(governor);
}
}
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);
}
}
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 { }
}
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];
}
}
}
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++;
}
}
}
}
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);
}
}
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);
}
}
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 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 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 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);
}
}
contract DepositBox is FeePayer, AdministrateeInterface, 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 virtual override view returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
}
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 disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address excessTokenBeneficiary;
}
// - Address of TokenFactory to pass into newly constructed ExpiringMultiParty contracts
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) {
address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params));
_registerContract(new address[](0), address(derivative));
emit CreatedExpiringMultiParty(address(derivative), msg.sender);
return address(derivative);
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createExpiringMultiParty params to ExpiringMultiParty constructor params.
function _convertParams(Params memory params)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
{
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.tokenFactoryAddress = tokenFactoryAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
require(params.excessTokenBeneficiary != address(0), "Token Beneficiary cannot be 0x0");
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.expirationTimestamp = params.expirationTimestamp;
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.syntheticName = params.syntheticName;
constructorParams.syntheticSymbol = params.syntheticSymbol;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPct = params.disputeBondPct;
constructorParams.sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
constructorParams.disputerDisputeRewardPct = params.disputerDisputeRewardPct;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.excessTokenBeneficiary = params.excessTokenBeneficiary;
}
}
contract PricelessPositionManager is FeePayer, AdministrateeInterface {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
/****************************************
* 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;
// The excessTokenBeneficiary of any excess tokens added to the contract.
address public excessTokenBeneficiary;
/****************************************
* 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 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
* @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 _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _syntheticName name for the token contract that will be deployed.
* @param _syntheticSymbol symbol for the token contract that will be deployed.
* @param _tokenFactoryAddress deployed UMA token factory to create the synthetic token.
* @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position.
* @param _timerAddress Contract that stores the current time in a testing environment.
* @param _excessTokenBeneficiary Beneficiary to which all excess token balances that accrue in the contract can be
* sent.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _expirationTimestamp,
uint256 _withdrawalLiveness,
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
string memory _syntheticName,
string memory _syntheticSymbol,
address _tokenFactoryAddress,
FixedPoint.Unsigned memory _minSponsorTokens,
address _timerAddress,
address _excessTokenBeneficiary
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() {
require(_expirationTimestamp > getCurrentTime(), "Invalid expiration in future");
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
expirationTimestamp = _expirationTimestamp;
withdrawalLiveness = _withdrawalLiveness;
TokenFactory tf = TokenFactory(_tokenFactoryAddress);
tokenCurrency = tf.createToken(_syntheticName, _syntheticSymbol, 18);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
excessTokenBeneficiary = _excessTokenBeneficiary;
}
/****************************************
* 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, "Pending transfer");
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp, "Request expires post-expiry");
// 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)
),
"Sponsor already has position"
);
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.transferPositionRequestPassTimestamp != 0 &&
positionData.transferPositionRequestPassTimestamp <= getCurrentTime(),
"Invalid transfer request"
);
// 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, "No pending transfer");
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), "Invalid collateral amount");
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)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the witdrawl. 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)),
"Invalid collateral amount"
);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp, "Request expires post-expiry");
// 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(),
"Invalid withdraw request"
);
// 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, "No pending withdrawal");
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`.
* @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), "Minting synthetic tokens failed");
}
/**
* @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`.
* @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), "Invalid token amount");
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.
* @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 = _getOraclePrice(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;
// The final fee for this request is paid out of the contract rather than by the caller.
_payFinalFees(address(this), _computeFinalFees());
_requestOraclePrice(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(), "Caller not Governor");
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();
_requestOraclePrice(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 Drains any excess balance of the provided ERC20 token to a pre-selected beneficiary.
* @dev This will drain down to the amount of tracked collateral and drain the full balance of any other token.
* @param token address of the ERC20 token whose excess balance should be drained.
*/
function trimExcess(IERC20 token) external fees() nonReentrant() returns (FixedPoint.Unsigned memory amount) {
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(token.balanceOf(address(this)));
if (address(token) == address(collateralCurrency)) {
// If it is the collateral currency, send only the amount that the contract is not tracking.
// Note: this could be due to rounding error or balance-changing tokens, like aTokens.
amount = balance.sub(_pfc());
} else {
// If it's not the collateral currency, send the entire balance.
amount = balance;
}
token.safeTransfer(excessTokenBeneficiary, amount.rawValue);
}
/**
* @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.
* @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 _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.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
/****************************************
* 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 virtual override view 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 {
OracleInterface oracle = _getOracle();
oracle.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) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.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));
}
// 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);
}
}
}
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 override view returns (address) {
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "Implementation not found");
return implementationAddress;
}
}
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 override view returns (bool) {
return supportedIdentifiers[identifier];
}
}
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 override view 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 override view returns (address[] memory) {
return partyMap[party].contracts;
}
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external override view 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 override view 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);
}
}
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 override payable {
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 override view 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 override view 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);
}
}
contract Voting is Testable, Ownable, OracleInterface, VotingInterface {
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;
}
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);
bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot")));
/***************************************
* EVENTS *
****************************************/
event VoteCommitted(address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price);
/**
* @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.
* @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) external override onlyRegisteredContract() {
uint256 blockTime = getCurrentTime();
require(time <= blockTime, "Can only request in past");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request");
bytes32 priceRequestId = _encodePriceRequest(identifier, time);
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
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, 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.
* @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) external override view onlyRegisteredContract() returns (bool) {
(bool _hasPrice, , ) = _getPriceOrError(identifier, time);
return _hasPrice;
}
/**
* @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.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time)
external
override
view
onlyRegisteredContract()
returns (int256)
{
(bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time);
// If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
/**
* @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(PendingRequest[] 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);
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;
}
/****************************************
* 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 hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
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) == 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);
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);
}
/**
* @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 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 salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public override onlyIfNotMigrated() {
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == 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(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// 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, 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, balance.rawValue);
}
/**
* @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 {
commitVote(identifier, time, hash);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
emit EncryptedVote(msg.sender, roundId, identifier, time, 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(Commitment[] calldata commits) external override {
for (uint256 i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].hash);
} else {
commitAndEmitEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].hash,
commits[i].encryptedVote
);
}
}
}
/**
* @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[] calldata reveals) external override {
for (uint256 i = 0; i < reveals.length; i++) {
revealVote(reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].salt);
}
}
/**
* @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 totalRewardToIssue total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Can only call from migrated");
}
uint256 blockTime = getCurrentTime();
require(roundId < voteTiming.computeCurrentRoundId(blockTime), "Invalid roundId");
Round storage round = rounds[roundId];
bool isExpired = blockTime > 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);
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, 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,
reward.rawValue
);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, 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");
}
}
/****************************************
* 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 override view returns (PendingRequest[] 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.
PendingRequest[] memory unresolved = new PendingRequest[](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] = PendingRequest({
identifier: priceRequest.identifier,
time: priceRequest.time
});
numUnresolved++;
}
}
PendingRequest[] memory pendingRequests = new PendingRequest[](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 override view 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 override view 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 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 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 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 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)
private
view
returns (
bool,
int256,
string memory
)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time);
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) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time)];
}
function _encodePriceRequest(bytes32 identifier, uint256 time) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time));
}
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);
}
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));
}
}
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);
}
}
contract MockAdministratee is AdministrateeInterface {
uint256 public timesRemargined;
uint256 public timesEmergencyShutdown;
function remargin() external override {
timesRemargined++;
}
function emergencyShutdown() external override {
timesEmergencyShutdown++;
}
}
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;
}
}
contract Liquidatable is PricelessPositionManager {
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, PreDispute, PendingDispute, 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 finderAddress;
address tokenFactoryAddress;
address timerAddress;
address excessTokenBeneficiary;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPct;
FixedPoint.Unsigned sponsorDisputeRewardPct;
FixedPoint.Unsigned disputerDisputeRewardPct;
}
// 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 disputeBondPct;
// 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 sponsorDisputeRewardPct;
// 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 disputerDisputeRewardPct;
/****************************************
* 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 withdrawalAmount,
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.finderAddress,
params.priceFeedIdentifier,
params.syntheticName,
params.syntheticSymbol,
params.tokenFactoryAddress,
params.minSponsorTokens,
params.timerAddress,
params.excessTokenBeneficiary
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1), "CR is more than 100%");
require(
params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1),
"Rewards are more than 100%"
);
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPct = params.disputeBondPct;
sponsorDisputeRewardPct = params.sponsorDisputeRewardPct;
disputerDisputeRewardPct = params.disputerDisputeRewardPct;
}
/****************************************
* 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`.
* @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);
// 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.PreDispute,
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(liquidationLiveness);
}
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 `disputeBondPct` 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(disputeBondPct).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.PendingDispute;
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,
* the sponsor, liquidator, and/or disputer can call this method to receive payments.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* Once all collateral is withdrawn, delete the liquidation data.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return amountWithdrawn the total amount of underlying returned from the liquidation.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(msg.sender == liquidation.disputer) ||
(msg.sender == liquidation.liquidator) ||
(msg.sender == liquidation.sponsor),
"Caller cannot withdraw rewards"
);
// 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 = disputerDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct);
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 can withdraw different amounts.
// Once a caller has been paid their address deleted from the struct.
// This prevents them from being paid multiple from times the same liquidation.
FixedPoint.Unsigned memory withdrawalAmount = FixedPoint.fromUnscaledUint(0);
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users can withdraw from the contract.
if (msg.sender == liquidation.disputer) {
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
FixedPoint.Unsigned memory payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
withdrawalAmount = withdrawalAmount.add(payToDisputer);
delete liquidation.disputer;
}
if (msg.sender == liquidation.sponsor) {
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
FixedPoint.Unsigned memory remainingCollateral = collateral.sub(tokenRedemptionValue);
FixedPoint.Unsigned memory payToSponsor = sponsorDisputeReward.add(remainingCollateral);
withdrawalAmount = withdrawalAmount.add(payToSponsor);
delete liquidation.sponsor;
}
if (msg.sender == liquidation.liquidator) {
// 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 (sponsorDisputePct+disputerDisputePct) >= 0 in
// the constructor when these params are set.
FixedPoint.Unsigned memory payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(
disputerDisputeReward
);
withdrawalAmount = withdrawalAmount.add(payToLiquidator);
delete liquidation.liquidator;
}
// Free up space once all collateral is withdrawn by removing the liquidation object from the array.
if (
liquidation.disputer == address(0) &&
liquidation.sponsor == address(0) &&
liquidation.liquidator == address(0)
) {
delete liquidations[sponsor][liquidationId];
}
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed && msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
withdrawalAmount = collateral.add(disputeBondAmount).add(finalFee);
delete liquidations[sponsor][liquidationId];
// 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.PreDispute && msg.sender == liquidation.liquidator) {
// Pay LIQUIDATOR: collateral + returned final fee
withdrawalAmount = collateral.add(finalFee);
delete liquidations[sponsor][liquidationId];
}
require(withdrawalAmount.isGreaterThan(0), "Invalid withdrawal amount");
// Decrease the total collateral held in liquidatable by the amount withdrawn.
amountWithdrawn = _removeCollateral(rawLiquidationCollateral, withdrawalAmount);
emit LiquidationWithdrawn(msg.sender, amountWithdrawn.rawValue, liquidation.state, settlementPrice.rawValue);
// Transfer amount withdrawn from this contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
return amountWithdrawn;
}
/**
* @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 PendingDispute state. If not, it will immediately return.
// If the liquidation is in the PendingDispute 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 == PendingDispute 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.PendingDispute) {
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 override view 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.PreDispute),
"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.PreDispute) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)),
"Liquidation not withdrawable"
);
}
}
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.
{
}
}
|
Get the resolved price or revert. 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. If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. Reset the position state as all the value has been removed after settlement.
|
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"
);
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(
exchangeRate
);
if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) {
denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral);
emit EndedDepositBox(msg.sender);
}
amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw);
emit RequestWithdrawalExecuted(
msg.sender,
amountWithdrawn.rawValue,
exchangeRate.rawValue,
depositBoxData.requestPassTimestamp
);
_resetWithdrawalRequest(depositBoxData);
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
| 7,360,293
|
pragma solidity ^0.5.11;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
library PreciseMathUtils {
using SafeMath for uint256;
// Divisor used for representing percentages
uint256 public constant PERC_DIVISOR = 10 ** 27;
/**
* @dev Returns whether an amount is a valid percentage out of PERC_DIVISOR
* @param _amount Amount that is supposed to be a percentage
*/
function validPerc(uint256 _amount) internal pure returns (bool) {
return _amount <= PERC_DIVISOR;
}
/**
* @dev Compute percentage of a value with the percentage represented by a fraction
* @param _amount Amount to take the percentage of
* @param _fracNum Numerator of fraction representing the percentage
* @param _fracDenom Denominator of fraction representing the percentage
*/
function percOf(uint256 _amount, uint256 _fracNum, uint256 _fracDenom) internal pure returns (uint256) {
return _amount.mul(percPoints(_fracNum, _fracDenom)).div(PERC_DIVISOR);
}
/**
* @dev Compute percentage of a value with the percentage represented by a fraction over PERC_DIVISOR
* @param _amount Amount to take the percentage of
* @param _fracNum Numerator of fraction representing the percentage with PERC_DIVISOR as the denominator
*/
function percOf(uint256 _amount, uint256 _fracNum) internal pure returns (uint256) {
return _amount.mul(_fracNum).div(PERC_DIVISOR);
}
/**
* @dev Compute percentage representation of a fraction
* @param _fracNum Numerator of fraction represeting the percentage
* @param _fracDenom Denominator of fraction represeting the percentage
*/
function percPoints(uint256 _fracNum, uint256 _fracDenom) internal pure returns (uint256) {
return _fracNum.mul(PERC_DIVISOR).div(_fracDenom);
}
}
|
Compute percentage of a value with the percentage represented by a fraction _amount Amount to take the percentage of _fracNum Numerator of fraction representing the percentage _fracDenom Denominator of fraction representing the percentage/
|
function percOf(uint256 _amount, uint256 _fracNum, uint256 _fracDenom) internal pure returns (uint256) {
return _amount.mul(percPoints(_fracNum, _fracDenom)).div(PERC_DIVISOR);
}
| 896,533
|
./full_match/4/0xcE533BE31A75d2b1912C9c3f8b63A22e0FE5C221/sources/DakToken.sol
|
A method for a stakeholder to remove a stake. _stake The size of the stake to be removed./
|
function removeStake(uint256 _stake) public {
stakes[msg.sender] = stakes[msg.sender].sub(_stake);
timestaking[msg.sender] = 0;
timestaked[msg.sender] = 0;
if (stakes[msg.sender] == 0) removeStakeholder(msg.sender);
_mint(msg.sender, _stake);
}
| 658,737
|
./full_match/1/0xd30fd4209BCbA750Cb9Dc5e1EFa9c4DE91AF2929/sources/SpectrolFinance.sol
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("SpectrolFinance", "SPT") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buytreasuryFundFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyMarketingFee = 0;
uint256 _selltreasuryFundFee = 2;
uint256 _sellLiquidityFee = 1;
uint256 _sellMarketingFee = 2;
uint256 totalSupply = 1_000_000_000 * 1e18;
maxTransactionAmount = 9_981_111 * 1e18;
maxWallet = 9_981_111 * 1e18;
swapTokensAtAmount = (totalSupply * 5) / 10000;
buytreasuryFundFee = _buytreasuryFundFee;
buyLiquidityFee = _buyLiquidityFee;
buyMarketingFee = _buyMarketingFee;
buyTotalFees = buytreasuryFundFee + buyLiquidityFee + buyMarketingFee;
selltreasuryFundFee = _selltreasuryFundFee;
sellLiquidityFee = _sellLiquidityFee;
sellMarketingFee = _sellMarketingFee;
sellTotalFees = selltreasuryFundFee + sellLiquidityFee + sellMarketingFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 3,141,604
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.