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/4/0x5b6329DbFf34Cc195aa8a9edcbb83d76A8C6928d/sources/Controller.sol
|
Validate that enough time has elapsed since component's last trade and component isn't WETH./
|
function _validateTradeParameters(address _component) internal view virtual {
require(rebalanceComponents.contains(_component), "Passed component not included in rebalance");
AssetTradeInfo memory componentInfo = assetInfo[_component];
require(componentInfo.exchange != uint256(ExchangeId.None), "Exchange must be specified");
require(
componentInfo.lastTradeTimestamp.add(componentInfo.coolOffPeriod) <= block.timestamp,
"Cool off period has not elapsed."
);
}
| 696,331 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Royalty.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./FineCoreInterface.sol";
/// @custom:security-contact [email protected]
contract Solids is ERC721Enumerable, ERC721Burnable, ERC721Royalty, AccessControl, Ownable {
using Counters for Counters.Counter;
using EnumerableSet for EnumerableSet.UintSet;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
FineCoreInterface coreContract;
bool public paused = false;
uint public TOKEN_LIMIT = 8888; // not including bonus
uint256 public remaining;
mapping(uint256 => uint256) public cache;
address payable public artistAddress = payable(0x70F2D7fA5fAE142E1AF7A95B4d48A9C8e417813D);
address payable public additionalPayee = payable(0x0000000000000000000000000000000000000000);
uint256 public additionalPayeePercentage = 0;
uint256 public additionalPayeeRoyaltyPercentage = 0;
uint96 public royaltyPercent = 4500;
string public _contractURI = "ipfs://QmPmtPqQff6nnyvv8LNEpSnLqeARVus8Q5SbUfWSLAw126";
string public baseURI = "ipfs://QmSBiKg2u4YvEB8rQrJisAvBxCR4L9QYFvFdibkk1kBDby";
string public artist = "FAR";
string public description = "SOLIDS is a generative architecture NFT project created by FAR. There are 8,888 + 512 unique buildings generated algorithmically, enabling utility in the Metaverse.";
string public website = "https://fine.digital";
string public license = "MIT";
event recievedFunds(address _from, uint _amount);
constructor(address coreAddress, address shopAddress) ERC721("SOLIDS", "SOLID") {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, shopAddress);
coreContract = FineCoreInterface(coreAddress);
// set deafault royalty
_setDefaultRoyalty(address(this), royaltyPercent);
remaining = TOKEN_LIMIT; // start with max tokens
}
/**
* @dev receive direct ETH transfers
* @notice for splitting royalties
*/
receive() external payable {
emit recievedFunds(msg.sender, msg.value);
}
/**
* @dev split royalties sent to contract (ONLY ETH!)
*/
function withdraw() onlyOwner external {
_splitFunds(address(this).balance);
}
/**
* @dev Split payments
*/
function _splitFunds(uint256 amount) internal {
if (amount > 0) {
uint256 partA = amount * coreContract.platformRoyalty() / 10000;
coreContract.FINE_TREASURY().transfer(partA);
uint256 partB = amount * additionalPayeeRoyaltyPercentage / 10000;
if (partB > 0) additionalPayee.transfer(partB);
artistAddress.transfer((amount - partA) - partB);
}
}
/**
* @dev lookup the URI for a token
* @param tokenId to retieve URI for
*/
function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) {
return string(abi.encodePacked(baseURI, "/", Strings.toString(tokenId), ".json"));
}
// On-chain Data
/**
* @dev Update the base URI field
* @param _uri base for all tokens
* @dev Only the admin can call this
*/
function setContractURI(string calldata _uri) onlyOwner external {
_contractURI = _uri;
}
/**
* @dev Update the base URI field
* @param _uri base for all tokens
* @dev Only the admin can call this
*/
function setBaseURI(string calldata _uri) onlyOwner external {
baseURI = _uri;
}
/**
* @dev Update the royalty percentage
* @param _percentage for royalties
* @dev Only the admin can call this
*/
function setRoyaltyPercent(uint96 _percentage) onlyOwner external {
royaltyPercent = _percentage;
}
/**
* @dev Update the additional payee sales percentage
* @param _percentage for sales
* @dev Only the admin can call this
*/
function additionalPayeePercent(uint96 _percentage) onlyOwner external {
additionalPayeePercentage = _percentage;
}
/**
* @dev Update the additional payee royalty percentage
* @param _percentage for royalty
* @dev Only the admin can call this
*/
function additionalPayeeRoyaltyPercent(uint96 _percentage) onlyOwner external {
additionalPayeeRoyaltyPercentage = _percentage;
}
/**
* @dev Update the description field
* @param _desc description of the project
* @dev Only the admin can call this
*/
function setDescription(string calldata _desc) onlyOwner external {
description = _desc;
}
/**
* @dev Update the website field
* @param _url base for all tokens
* @dev Only the admin can call this
*/
function setWebsite(string calldata _url) onlyOwner external {
website = _url;
}
/**
* @dev pause minting
* @dev Only the admin can call this
*/
function pause() onlyOwner external {
paused = true;
}
/**
* @dev unpause minting
* @dev Only the admin can call this
*/
function unpause() onlyOwner external {
paused = false;
}
/**
* @dev checkPool -maintain interface compatibility
*/
function checkPool() external view returns (uint256) {
return remaining;
}
/**
* @dev Draw a token from the remaining ids
*/
function drawIndex() internal returns (uint256 index) {
//RNG
uint randomness = coreContract.getRandomness(remaining, block.timestamp);
uint256 i = randomness % remaining;
// if there's a cache at cache[i] then use it
// otherwise use i itself
index = cache[i] == 0 ? i : cache[i];
// grab a number from the tail
cache[i] = cache[remaining - 1] == 0 ? remaining - 1 : cache[remaining - 1];
remaining = remaining - 1;
}
/**
* @dev Mint a token
* @param to address to mint the token to
* @dev Only the minter role can call this
*/
function mint(address to) external onlyRole(MINTER_ROLE) returns (uint) {
require(!paused, "minting paused");
require(remaining > 0, "all tokens minted");
uint id = drawIndex();
_safeMint(to, id);
return id;
}
/**
* @dev Mint a bonus token (for infinites AI holders)
* @param to address to mint the token to
* @dev Only the minter role can call this
*/
function mintBonus(address to, uint infiniteId) external onlyRole(MINTER_ROLE) returns (uint bonusId) {
require(!paused, "minting paused");
bonusId = 10000 + infiniteId;
require(!_exists(bonusId), "Token already minted");
_safeMint(to, bonusId);
}
// getters for interface
function contractURI() public view returns (string memory) {
return _contractURI;
}
function getArtistAddress() external view returns (address payable) {
return artistAddress;
}
function getAdditionalPayee() external view returns (address payable) {
return additionalPayee;
}
function getAdditionalPayeePercentage() external view returns (uint256) {
return additionalPayeePercentage;
}
function getTokenLimit() external view returns (uint256) {
return TOKEN_LIMIT;
}
// The following functions are overrides required by Solidity.
/**
* @dev get baseURI for all tokens
*/
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, ERC721Royalty, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function _burn(uint256 tokenId)
internal
override(ERC721, ERC721Royalty)
{
super._burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../utils/Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/ERC721Royalty.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../common/ERC2981.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev Extension of ERC721 with the ERC2981 NFT Royalty Standard, a standardized way to retrieve royalty payment
* information.
*
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
*
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
*
* _Available since v4.5._
*/
abstract contract ERC721Royalty is ERC2981, ERC721 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) {
return super.supportsInterface(interfaceId);
}
/**
* @dev See {ERC721-_burn}. This override additionally clears the royalty information for the token.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
_resetTokenRoyalty(tokenId);
}
}
// 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 (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual 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 virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual 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 revoked `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}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
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);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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 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: UNLICENSED
pragma solidity ^0.8.2;
interface FineCoreInterface {
function getProjectAddress(uint id) external view returns (address);
function getRandomness(uint256 id, uint256 seed) external view returns (uint256 randomnesss);
function getProjectID(address project) external view returns (uint);
function FINE_TREASURY() external returns (address payable);
function platformPercentage() external returns (uint256);
function platformRoyalty() external returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_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 = 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);
_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(ERC721.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(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @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 {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @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
* ====
*
* [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 Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/common/ERC2981.sol)
pragma solidity ^0.8.0;
import "../../interfaces/IERC2981.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
*
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
*
* Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
* fee is specified in basis points by default.
*
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
*
* _Available since v4.5._
*/
abstract contract ERC2981 is IERC2981, ERC165 {
struct RoyaltyInfo {
address receiver;
uint96 royaltyFraction;
}
RoyaltyInfo private _defaultRoyaltyInfo;
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @inheritdoc IERC2981
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
virtual
override
returns (address, uint256)
{
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
if (royalty.receiver == address(0)) {
royalty = _defaultRoyaltyInfo;
}
uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
return (royalty.receiver, royaltyAmount);
}
/**
* @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
* fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
* override.
*/
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/**
* @dev Sets the royalty information that all ids in this contract will default to.
*
* Requirements:
*
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: invalid receiver");
_defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Removes default royalty information.
*/
function _deleteDefaultRoyalty() internal virtual {
delete _defaultRoyaltyInfo;
}
/**
* @dev Sets the royalty information for a specific token id, overriding the global default.
*
* Requirements:
*
* - `tokenId` must be already minted.
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setTokenRoyalty(
uint256 tokenId,
address receiver,
uint96 feeNumerator
) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: Invalid parameters");
_tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Resets royalty information for the token id back to the global default.
*/
function _resetTokenRoyalty(uint256 tokenId) internal virtual {
delete _tokenRoyaltyInfo[tokenId];
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
|
Update the additional payee sales percentage _percentage for sales Only the admin can call this/
|
function additionalPayeePercent(uint96 _percentage) onlyOwner external {
additionalPayeePercentage = _percentage;
}
| 253,777 |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
// Contracts
import "./BaseEscrowDapp.sol";
// Interfaces
import "../../interfaces/escrow/IEscrow.sol";
import "../../interfaces/IBaseProxy.sol";
import "../../providers/compound/CErc20Interface.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol";
// Libraries
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol";
import "../../util/SettingsConsts.sol";
import "../../util/TellerCommon.sol";
import "../../util/NumbersLib.sol";
/*****************************************************************************************************/
/** WARNING **/
/** THIS CONTRACT IS UPGRADEABLE! **/
/** --------------------------------------------------------------------------------------------- **/
/** Do NOT change the order of or PREPEND any storage variables to this or new versions of this **/
/** contract as this will cause the the storage slots to be overwritten on the proxy contract!! **/
/** **/
/** Visit https://docs.openzeppelin.com/upgrades/2.6/proxies#upgrading-via-the-proxy-pattern for **/
/** more information. **/
/*****************************************************************************************************/
/**
* @notice This contract is used by borrowers to call Dapp functions (using delegate calls).
* @notice This contract should only be constructed using it's upgradeable Proxy contract.
* @notice In order to call a Dapp function, the Dapp must be added in the DappRegistry instance.
*
* @author [email protected]
*/
contract Escrow is IEscrow, Base, EscrowStorage, BaseEscrowDapp {
using SafeMath for uint256;
using NumbersLib for uint256;
using SafeERC20 for IERC20;
/** External Functions **/
/**
* @notice It calls a given dapp using a delegatecall function by a borrower owned the current loan id associated to this escrow contract.
* @param dappData the current dapp data to be executed.
*/
function callDapp(TellerCommon.DappData calldata dappData)
external
onlyBorrower
whenNotPaused
{
TellerCommon.Dapp memory dapp =
settings.dappRegistry().dapps(dappData.location);
require(dapp.exists, "DAPP_NOT_WHITELISTED");
require(
dapp.unsecured || loanManager.isLoanSecured(loanID),
"DAPP_UNSECURED_NOT_ALLOWED"
);
address _impl = IBaseProxy(dappData.location).implementation();
(bool success, ) = _impl.delegatecall(dappData.data);
if (!success) {
assembly {
let ptr := mload(0x40)
let size := returndatasize
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
}
/**
* @notice Calculate the value of the loan by getting the value of all tokens the Escrow owns.
* @return Escrow total value denoted in the lending token.
*/
function calculateTotalValue() public view returns (uint256) {
uint256 valueInEth;
address[] memory tokens = getTokens();
for (uint256 i = 0; i < tokens.length; i++) {
if (tokens[i] == settings.WETH_ADDRESS()) {
valueInEth = valueInEth.add(_balanceOf(tokens[i]));
} else {
valueInEth = valueInEth.add(
_valueOfIn(
tokens[i],
settings.ETH_ADDRESS(),
_balanceOf(tokens[i])
)
);
}
}
return _valueOfIn(settings.ETH_ADDRESS(), lendingToken, valueInEth);
}
/**
* @notice Repay this Escrow's loan.
* @dev If the Escrow's balance of the borrowed token is less than the amount to repay, transfer tokens from the sender's wallet.
* @dev Only the owner of the Escrow can call this. If someone else wants to make a payment, they should call the loan manager directly.
*/
function repay(uint256 amount) external onlyBorrower whenNotPaused {
IERC20 token = IERC20(lendingToken);
uint256 balance = _balanceOf(address(token));
uint256 totalOwed = loanManager.getTotalOwed(loanID);
if (balance < totalOwed && amount > balance) {
uint256 amountNeeded =
amount > totalOwed
? totalOwed.sub(balance)
: amount.sub(balance);
token.safeTransferFrom(msg.sender, address(this), amountNeeded);
}
token.safeApprove(lendingPool, amount);
loanManager.repay(amount, loanID);
}
/**
* @notice Sends the tokens owned by this escrow to the owner.
* @dev The loan must not be active.
* @dev The recipient must be the loan borrower AND the loan must be already liquidated.
*/
function claimTokens() external onlyBorrower whenNotPaused {
require(
loanManager.loans(loanID).status == TellerCommon.LoanStatus.Closed,
"LOAN_NOT_CLOSED"
);
address[] memory tokens = getTokens();
for (uint256 i = 0; i < tokens.length; i++) {
uint256 balance = _balanceOf(tokens[i]);
if (balance > 0) {
IERC20(tokens[i]).safeTransfer(msg.sender, balance);
}
}
emit TokensClaimed(msg.sender);
}
/**
* @notice Send the equivilant of tokens owned by this escrow (in collateral value) to the recipient,
* @dev The loan must not be active
* @dev The loan must be liquidated
* @dev The recipeient must be the loan manager
* @param recipient address to send the tokens to
* @param value The value of escrow held tokens, to be claimed based on collateral value
*/
function claimTokensByCollateralValue(address recipient, uint256 value)
external
whenNotPaused
{
require(
loanManager.loans(loanID).status == TellerCommon.LoanStatus.Closed,
"LOAN_NOT_CLOSED"
);
require(loanManager.loans(loanID).liquidated, "LOAN_NOT_LIQUIDATED");
require(msg.sender == address(loanManager), "CALLER_MUST_BE_LOANS");
address[] memory tokens = getTokens();
uint256 valueLeftToTransfer = value;
// cycle through tokens
for (uint256 i = 0; i < tokens.length; i++) {
if (valueLeftToTransfer == 0) {
break;
}
uint256 balance = _balanceOf(tokens[i]);
// get value of token balance in collateral value
if (balance > 0) {
uint256 valueInCollateralToken =
(tokens[i] == loanManager.collateralToken())
? balance
: _valueOfIn(
tokens[i],
loanManager.collateralToken(),
balance
);
// if <= value, transfer tokens
if (valueInCollateralToken <= valueLeftToTransfer) {
IERC20(tokens[i]).safeTransfer(
recipient,
valueInCollateralToken
);
valueLeftToTransfer = valueLeftToTransfer.sub(
valueInCollateralToken
);
} else {
IERC20(tokens[i]).safeTransfer(
recipient,
valueLeftToTransfer
);
valueLeftToTransfer = 0;
}
_tokenUpdated(tokens[i]);
}
}
emit TokensClaimed(recipient);
}
/**
* @notice It initializes this escrow instance for a given loan manager address and loan id.
* @param settingsAddress The address of the settings contract.
* @param lendingPoolAddress e
* @param aLoanID the loan ID associated to this escrow instance.
* @param lendingTokenAddress The token that the Escrow loan will be for.
* @param borrowerAddress e
*/
function initialize(
address settingsAddress,
address lendingPoolAddress,
uint256 aLoanID,
address lendingTokenAddress,
address borrowerAddress
) external {
Base._initialize(settingsAddress);
loanManager = ILoanManager(msg.sender);
lendingPool = lendingPoolAddress;
loanID = aLoanID;
lendingToken = lendingTokenAddress;
borrower = borrowerAddress;
// Initialize tokens list with the borrowed token.
tokens.add(lendingTokenAddress);
}
/** Internal Functions */
/**
* @notice Calculate a value of a token amount.
* @param baseAddress base token address.
* @param quoteAddress quote token address.
* @param baseAmount amount of base token.
* @return Value of baseAmount in quote token.
*/
function _valueOfIn(
address baseAddress,
address quoteAddress,
uint256 baseAmount
) internal view returns (uint256) {
bool success;
bytes memory returnData;
// call function to base address for function signature of underlying
(success, returnData) = baseAddress.staticcall(
abi.encodeWithSignature("exchangeRateStored()")
);
require(success, "EXCHANGE_RATE_CALL_FAIL");
if (returnData.length > 0) {
uint8 cTokenDecimals = CErc20Interface(baseAddress).decimals();
uint256 exchangeRate = abi.decode(returnData, (uint256));
uint256 diffFactor =
uint256(10)**uint256(18).diff(uint256(cTokenDecimals));
if (cTokenDecimals > uint256(18)) {
exchangeRate = exchangeRate.mul(diffFactor);
} else {
exchangeRate = exchangeRate.div(diffFactor);
}
uint8 assetDecimals;
if (baseAddress == settings.CETH_ADDRESS()) {
baseAddress = settings.ETH_ADDRESS();
assetDecimals = uint8(18);
} else {
baseAddress = CErc20Interface(baseAddress).underlying();
assetDecimals = ERC20Detailed(baseAddress).decimals();
}
baseAmount = baseAmount.mul(exchangeRate).div(
uint256(10)**assetDecimals
);
}
return
settings.chainlinkAggregator().valueFor(
baseAddress,
quoteAddress,
baseAmount
);
}
}
|
Repay this Escrow's loan. If the Escrow's balance of the borrowed token is less than the amount to repay, transfer tokens from the sender's wallet. Only the owner of the Escrow can call this. If someone else wants to make a payment, they should call the loan manager directly./
|
function repay(uint256 amount) external onlyBorrower whenNotPaused {
IERC20 token = IERC20(lendingToken);
uint256 balance = _balanceOf(address(token));
uint256 totalOwed = loanManager.getTotalOwed(loanID);
if (balance < totalOwed && amount > balance) {
uint256 amountNeeded =
amount > totalOwed
? totalOwed.sub(balance)
: amount.sub(balance);
token.safeTransferFrom(msg.sender, address(this), amountNeeded);
}
token.safeApprove(lendingPool, amount);
loanManager.repay(amount, loanID);
}
| 6,352,473 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.10;
import "ds-test/test.sol";
import "./mocks/MockCaller.sol";
import "../BaseToken.sol";
import "../Minter.sol";
import "./utils/Hevm.sol";
contract MinterTest is DSTest {
Hevm internal constant hevm = Hevm(HEVM_ADDRESS);
// contracts
BaseToken internal baseToken;
Minter internal minter;
MockCaller internal mockCaller;
string internal name = "Test Token";
string internal symbol = "TT";
address[] internal payees = [
0xaa1CF06BA699c40b2EAfb5e9bc43AC5C71EcC780,
0xC95876d9D0E954068C2B6840d226cc9Cab5Dfc1a
];
uint256[] internal shares = [75, 25];
uint256 internal privateKey = 0xBEEF;
address internal minterSigner = hevm.addr(privateKey);
function signPayload(Minter mintContract, uint256 sk, address accountToMint, uint256 maxPermitted)
internal
returns(bytes memory)
{
(uint8 v, bytes32 r, bytes32 s) = hevm.sign(
sk,
mintContract.hashTransaction(accountToMint, maxPermitted)
);
return abi.encodePacked(r, s, v);
}
function setUp() public virtual {
baseToken = new BaseToken(name, symbol);
mockCaller = new MockCaller();
minter = new Minter(address(baseToken), payees, shares);
minter.setMintSigner(minterSigner);
baseToken.grantRole(baseToken.MINTER_ROLE(), address(minter));
baseToken.setMaxSupply(50);
}
receive() external payable { }
/* ------------------------------- Constructor ------------------------------ */
function testConstructorArgs() public {
assertEq(minter.payee(0), payees[0]);
assertEq(minter.payee(1), payees[1]);
assertEq(minter.shares(payees[0]), shares[0]);
assertEq(minter.shares(payees[1]), shares[1]);
assertEq(minter.tokenContract(), address(baseToken));
}
/* ------------------------------- Permissions ------------------------------ */
function testPermission() public {
assertTrue(minter.hasRole(minter.ADMIN_ROLE(), address(this)));
}
/* ----------------------------- Reserve Tokens ----------------------------- */
function testReserveTokens() public {
minter.reserveTokens(10);
assertEq(baseToken.balanceOf(address(this)), 10);
assertEq(baseToken.totalSupply(), 10);
assertEq(baseToken.totalMinted(), 10);
}
function testFailReserveTokens() public {
mockCaller.minterReserve(minter, 10);
}
/* ---------------------------------- Mint ---------------------------------- */
function testFailMintNotActive() public {
minter.mint(1);
}
function testMintActive() public {
// Activate sale.
minter.flipSaleState();
minter.setPrice(0.08 ether);
// Mint.
minter.mint{ value: 0.16 ether }(2);
assertEq(baseToken.balanceOf(address(this)), 2);
assertEq(baseToken.totalSupply(), 2);
assertEq(baseToken.totalMinted(), 2);
}
function testFailMintIfNumTokensZero() public {
// Activate sale.
minter.flipSaleState();
minter.setPrice(0.08 ether);
// Mint.
minter.mint{ value: 0.16 ether }(0);
}
function testFailMintIfPriceSetToZero() public {
// Activate sale.
minter.flipSaleState();
minter.setPrice(0);
// Mint.
minter.mint{ value: 0.16 ether }(2);
}
function testFailMintNotEnoughEther() public {
// Activate sale.
minter.flipSaleState();
minter.setPrice(0.08 ether);
// Mint.
minter.mint{ value: 0.16 ether }(3);
}
function testRefundIfOverpay() public {
// Activate sale.
minter.flipSaleState();
minter.setPrice(0.08 ether);
uint256 cachedBalance = address(this).balance;
// Mint.
minter.mint{ value: 0.16 ether }(1);
assertEq(address(this).balance, cachedBalance - 0.08 ether);
}
function testFailSurpassTotalSupply() public {
// Activate sale.
minter.flipSaleState();
minter.setPrice(0.08 ether);
uint256 numToMint = baseToken.maxSupply() + 1;
minter.mint{ value: 0.08 ether * numToMint }(numToMint);
}
function testMintTotalSupply() public {
// Activate sale.
minter.flipSaleState();
minter.setPrice(0.08 ether);
uint256 numToMint = baseToken.maxSupply();
minter.mint{ value: 0.08 ether * numToMint }(numToMint);
assertEq(baseToken.balanceOf(address(this)), numToMint);
assertEq(baseToken.totalSupply(), numToMint);
assertEq(baseToken.totalMinted(), numToMint);
}
function testMintMaxTimesPerWallet() public {
// Activate sale.
minter.flipSaleState();
minter.setPrice(0.08 ether);
uint256 numToMint = 5;
minter.setMaxWalletPurchase(numToMint);
minter.mint{ value: 0.08 ether * numToMint }(numToMint);
assertEq(baseToken.balanceOf(address(this)), numToMint);
assertEq(baseToken.totalSupply(), numToMint);
assertEq(baseToken.totalMinted(), numToMint);
}
function testFailMintTooManyTimesPerWallet() public {
// Activate sale.
minter.flipSaleState();
minter.setPrice(0.08 ether);
uint256 numToMint = 5;
minter.setMaxWalletPurchase(numToMint);
minter.mint{ value: 0.08 ether * (numToMint + 1) }(numToMint + 1);
}
/* ------------------------------- Signed Mint ------------------------------ */
function testFailSignedMintNotActive() public {
// Setup.
minter.setPrice(0.08 ether);
minter.setMaxWalletPurchase(5);
bytes memory sig = signPayload(minter, privateKey, address(this), 5);
minter.signedMint{ value: 0.08 ether }(1, 5, sig);
}
function testFailSignedMintPriceNotSet() public {
// Setup.
minter.flipSignedMintState();
minter.setMaxWalletPurchase(5);
bytes memory sig = signPayload(minter, privateKey, address(this), 5);
minter.signedMint{ value: 0.08 ether }(1, 5, sig);
}
function testSignedMint() public {
// Setup.
minter.flipSignedMintState();
minter.setPrice(0.08 ether);
minter.setMaxWalletPurchase(5);
bytes memory sig = signPayload(minter, privateKey, address(this), 5);
minter.signedMint{ value: 0.08 ether }(1, 5, sig);
assertEq(baseToken.balanceOf(address(this)), 1);
assertEq(baseToken.totalSupply(), 1);
assertEq(baseToken.totalMinted(), 1);
}
function testSignedMintTwoPurchases() public {
// Setup.
minter.flipSignedMintState();
minter.setPrice(0.08 ether);
minter.setMaxWalletPurchase(5);
bytes memory sig = signPayload(minter, privateKey, address(this), 5);
minter.signedMint{ value: 0.08 ether }(1, 5, sig);
minter.signedMint{ value: 0.08 ether }(1, 5, sig);
assertEq(baseToken.balanceOf(address(this)), 2);
assertEq(baseToken.totalSupply(), 2);
assertEq(baseToken.totalMinted(), 2);
}
function testFailSignedMintOverMax() public {
// Setup.
minter.flipSignedMintState();
minter.setPrice(0.08 ether);
minter.setMaxWalletPurchase(5);
bytes memory sig = signPayload(minter, privateKey, address(this), 5);
minter.signedMint{ value: 0.08 ether }(3, 5, sig);
minter.signedMint{ value: 0.08 ether }(3, 5, sig);
}
function testFailSignedMintNumTokensZero() public {
// Setup.
minter.flipSignedMintState();
minter.setPrice(0.08 ether);
minter.setMaxWalletPurchase(5);
bytes memory sig = signPayload(minter, privateKey, address(this), 5);
minter.signedMint{ value: 0.08 ether }(0, 5, sig);
}
function testFailSignedMintPriceZero() public {
// Setup.
minter.flipSignedMintState();
minter.setPrice(0.08 ether);
minter.setPrice(0 ether);
minter.setMaxWalletPurchase(5);
bytes memory sig = signPayload(minter, privateKey, address(this), 5);
minter.signedMint{ value: 0.08 ether }(1, 5, sig);
}
function testFailSignedMintAboveMaxSupply() public {
// Setup.
minter.flipSignedMintState();
minter.setPrice(0.008 ether);
uint256 maxPlus1 = baseToken.maxSupply() + 1;
minter.setMaxWalletPurchase(maxPlus1);
bytes memory sig = signPayload(minter, privateKey, address(this), maxPlus1);
minter.signedMint{ value: (0.008 ether) * maxPlus1 }(maxPlus1, maxPlus1, sig);
}
function testMintMaxSupply() public {
// Setup.
minter.flipSignedMintState();
minter.setPrice(0.008 ether);
uint256 max = baseToken.maxSupply();
minter.setMaxWalletPurchase(max);
bytes memory sig = signPayload(minter, privateKey, address(this), max);
minter.signedMint{ value: (0.008 ether) * max }(max, max, sig);
}
function testMintMaxWallet() public {
// Setup.
minter.flipSignedMintState();
minter.setPrice(0.008 ether);
minter.setMaxWalletPurchase(8);
bytes memory sig = signPayload(minter, privateKey, address(this), 8);
minter.signedMint{ value: 0.008 ether * 8 }(1, 8, sig);
}
/* -------------------------------- Claiming -------------------------------- */
}
|
Activate sale. Mint.
|
function testFailMintNotEnoughEther() public {
minter.flipSaleState();
minter.setPrice(0.08 ether);
}
| 7,245,592 |
./partial_match/3/0x2e4c311BbD6e2E65Bd7b0167a3d71F9cc924B112/sources/IbETHRouter.sol
|
Remove ETH and Alpha from ibETH-Alpha Pool. 1. Remove ibETH and Alpha from the pool. 2. Unwrap ibETH to ETH. 3. Return ETH and Alpha to caller.
|
function removeLiquidityETH(
uint256 liquidity,
uint256 amountAlphaMin,
uint256 amountETHMin,
address to,
uint256 deadline
) public returns (uint256 amountAlpha, uint256 amountETH) {
TransferHelper.safeTransferFrom(lpToken, msg.sender, address(this), liquidity);
uint256 amountIbETH;
(amountAlpha, amountIbETH) = IUniswapV2Router02(router).removeLiquidity(
alpha,
ibETH,
liquidity,
amountAlphaMin,
0,
address(this),
deadline
);
TransferHelper.safeTransfer(alpha, to, amountAlpha);
IBank(ibETH).withdraw(amountIbETH);
amountETH = address(this).balance;
if (amountETH > 0) {
TransferHelper.safeTransferETH(msg.sender, address(this).balance);
}
require(amountETH >= amountETHMin, "IbETHRouter: receive less ETH than amountETHmin");
}
| 5,121,540 |
pragma solidity ^0.4.24;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
mapping (address => Airline) public airlines; // Data storage for all airlines
mapping (uint => mapping (address => uint)) public flightPassengers; // Data storage for passengers in a flight
struct Airline { // Struct for creating an airline, with info
string name;
address airlineID;
bool registered;
bool funded;
uint256 fundedAmount;
}
// Using mapping with variables to avoid arrays
uint128 private registeredAirlines = 0; // an integer that tracks the amount of registered airlines
mapping (address => mapping (address => bool)) private registerAirlineWaitlist; // mapping that stores confirmed addresses for an airline
uint64 private registersConfirmed = 0; // an integer to count the addresses that confirmed the airline to register
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event AirlineRegistered(address airlineID);
event AirlineQueued(address airlineID);
event InsuranceBought(uint amount);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor() public {
contractOwner = msg.sender;
airlines[msg.sender] = Airline('Initialized Airlines', msg.sender, true, true, 0);
registeredAirlines += 1;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational() {
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* Modifier that requires registred airlines to be the function caller
**/
modifier requireRegisteredAirline() {
require(airlines[msg.sender].registered, "Caller is not a registered airline");
_;
}
/**
* Modifier that resticts actions for airlines that didn't funded the contract
**/
modifier requireFundedAirline() {
require(airlines[msg.sender].funded, "Caller hasn't funded the contract with 10 ether");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() public view returns(bool) {
return operational;
}
/**
* Used for testing: Check if airline is registered
**/
function isAirline(address _airline) public view returns(bool) {
return airlines[_airline].registered;
}
function getPassenger(address _passengerID, uint _flightID) public view returns (uint) {
return flightPassengers[_flightID][_passengerID];
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus (bool mode) external requireContractOwner {
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*/
function registerAirline(address _airline, string _name) external requireIsOperational requireRegisteredAirline requireFundedAirline {
if (registeredAirlines < 4) {
airlines[_airline] = Airline(_name, _airline, true, false, 0);
registeredAirlines += 1;
emit AirlineRegistered(_airline);
} else {
require(!registerAirlineWaitlist[_airline][msg.sender], "Caller already approved");
registerAirlineWaitlist[_airline][msg.sender] = true;
registersConfirmed += 1;
emit AirlineQueued(_airline);
if(registersConfirmed >= registeredAirlines / 2) {
airlines[_airline] = Airline(_name, _airline, true, false, 0);
registeredAirlines += 1;
registersConfirmed = 0;
emit AirlineRegistered(_airline);
}
}
}
/**
* @dev Buy insurance for a flight
*
*/
function buy (uint _flightID) external payable requireIsOperational{
require(flightPassengers[_flightID][msg.sender] == 0, "Caller already bought the insurance");
require(msg.value > 0, "Caller didn't send any amount");
require(msg.value <= 1 ether, "Caller's amount was above the limit");
contractOwner.transfer(msg.value);
flightPassengers[_flightID][msg.sender] = msg.value;
emit InsuranceBought(msg.value);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees() external pure {
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay () external pure {
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund () public payable requireIsOperational requireRegisteredAirline {
airlines[msg.sender].fundedAmount.add(msg.value);
contractOwner.transfer(msg.value);
if(airlines[msg.sender].fundedAmount >= 10000000000000000000) {
airlines[msg.sender].funded = true;
}
}
function getFlightKey (address airline, string memory flight, uint256 timestamp) pure internal returns(bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function() external payable {
fund();
}
}
|
Transfers eligible payout funds to insuree/
|
function pay () external pure {
}
| 12,545,813 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./NFTSplitterAdmin.sol";
import "./NFTSplitterProxy.sol";
/**
* @notice This contract creates new Splitter proxies
* @dev it registers all proxy contracts in the storage of Admin contract
*/
contract NFTSplitterFactory {
address private owner;
address private settings;
address private NFTSplitterBase;
//is the app in pause state??
modifier isNotPaused(){
require (!NFTSplitterAdmin(settings).isPaused(), 'NFTSplitterFactory: Factory is paused');
_;
}
// only owner can execute the function
modifier onlyOwner(){
require (msg.sender == owner, 'NFTSplitterFactory: not contract owner');
_;
}
/**
* @dev emitted everytime a splitter proxy is created
*/
event ProxyCreated(
address indexed nft,
address indexed proxyAddress,
address indexed NFTOwner
);
constructor(address _settings) {
owner = msg.sender; // factory owner
settings = _settings; // admin contract address
NFTSplitterBase = NFTSplitterAdmin(settings).getImplementation(); //logic implementation
}
/**
* @notice function that creates a new splitter proxy contract
* @dev registers the the proxy address in admin contract and emits a ProxyCreated event
* it passes as parameter the address of the SplitterBase contract
* this function can only be executed id the app is not paused
*/
function createNFTSplitter(address _nft, uint _tokenId) public isNotPaused returns (NFTSplitterProxy prx){
prx = new NFTSplitterProxy (_nft, _tokenId, msg.sender, NFTSplitterBase, settings, "");
NFTSplitterAdmin(settings).registerProxy(_nft, _tokenId, address(prx));
emit ProxyCreated(_nft, address(prx), msg.sender);
return prx;
}
/**
* @notice returns the current address od the Splitter Base contract that contains
*/
function getNFTSplitterBase() external view returns (address) {
return NFTSplitterBase;
}
/**
* @notice returns the splitter proxy associated to a NFT-Tokenid
*/
function getProxyAddressByNFT(address _nft, uint _tokenId) external view returns (address) {
return NFTSplitterAdmin(settings).getProxyAddressByNFT(_nft, _tokenId);
}
// Function to receive Ether. msg.data must be empty
receive() external payable {}
// Fallback function is called when msg.data is not empty
fallback() external payable {}
function getBalance() public view returns (uint256) {
return address(this).balance;
}
/// @notice Withdraw any contract funds
function withdraw() public onlyOwner{
//TODO: implement withdraw and send founds to owner
}
}
|
returns the current address od the Splitter Base contract that contains/
|
function getNFTSplitterBase() external view returns (address) {
return NFTSplitterBase;
}
| 6,364,574 |
// SPDX-License-Identifier: GNU AGPLv3
/**
* @dev Implementation of the Bumo (BU) ERC20 Token.
*
* Pausable
* Burnable
* Mintable
* No supply cap
* Ownership - Renounce ownership has been diabled
*
* Compile options:
* Solc Verison: v0.7.2+commit.51b20bc0
* Enable Optimization: true
*
* License:
* GNU Affero General Public License v3.0 [GNU AGPLv3]
* Ref: https://opensource.org/licenses/AGPL-3.0
*
*/
pragma solidity 0.7.2;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
// function renounceOwnership() public virtual onlyOwner {
// emit OwnershipTransferred(_owner, address(0));
// _owner = address(0);
// }
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context, Ownable {
/**
* @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 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 onlyOwner {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused onlyOwner {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is IERC20, Pausable {
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) {
_name = name;
_symbol = symbol;
_decimals = 8;
}
/**
* @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 Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_beforeTokenTransfer();
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_beforeTokenTransfer();
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
/**
* @dev Mints `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function mint(uint256 amount) public virtual onlyOwner {
_mint(_msgSender(), amount);
}
/**
* @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();
_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();
_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();
_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 onlyOwner {
_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].
*/
/**
* @dev See {ERC20-_beforeTokenTransfer}.
* 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.
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer() internal view virtual {
require(!paused(), "ERC20Pausable: Cannot perform action while paused");
}
}
/**
* @dev Implementation of the Bumo (BU) ERC20 Token.
*
* Pausable
* Burnable
* Mintable
* No supply cap
* Ownership - Renounce ownership has been diabled
*
*/
contract TokenBumo is
ERC20("Bumo","BU")
{
/**
* @dev Call the internal Pause function
*/
function pause() external onlyOwner {
_pause();
}
/**
* @dev Call the internal Unpause function
*/
function unpause() external onlyOwner {
_unpause();
}
event Received(address, uint);
receive() external payable {
emit Received(msg.sender, msg.value);
}
/**
* @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 Tranfer out any accidental funds transferred to the contract
*
*/
function trnsferETHOut(address payable _recipient, uint256 _amount) external onlyOwner {
sendValue(_recipient, _amount);
}
/**
* @dev Tranfer out any accidental ERC20 tokens transferred to the contract
*
*/
function transferOtherERC20Out(address _tokenAddress, address _receiver, uint256 _amount) external onlyOwner {
ERC20(_tokenAddress).transfer(_receiver, _amount);
}
}
|
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();
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 2,095,321 |
./full_match/1/0x3c1164531d5857029ae5412E49999306547834d8/sources/@rmrk-team/evm-contracts/contracts/RMRK/library/RMRKLib.sol
|
Used to determine the index of the item in the array by spedifying its value. This was adapted from Cryptofin-Solidity `arrayUtils`. If the item is not found the index returned will equal `0`. A The array containing the item to be found a The value of the item to find the index of return The index of the item in the array return A boolean value specifying whether the item was found/
|
function indexOf(
uint64[] memory A,
uint64 a
) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i; i < length; ) {
if (A[i] == a) {
return (i, true);
}
unchecked {
++i;
}
}
return (0, false);
}
| 9,657,623 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./StakingPoolLib.sol";
import "../Version.sol";
import "../sweep/SweepERC20.sol";
/**
* @title StakingPool with optional fixed or floating token rewards
*
* @notice Users can deposit a stake token into the pool up to the specified pool maximum contribution.
* If the minimum criteria for the pool to go ahead are met, stake tokens are locked for an epochDuration.
* After this period expires the user can withdraw their stake token and reward tokens (if available) separately.
* The amount of rewards is determined by the pools rewardType - a floating reward ratio is updated on each deposit
* while fixed tokens rewards are calculated once per user.
*/
contract StakingPool is
PausableUpgradeable,
ReentrancyGuard,
OwnableUpgradeable,
SweepERC20,
Version
{
using SafeERC20 for IERC20;
// Magic Number fixed length rewardsAmounts to fit 3 words. Only used here.
struct User {
uint128 depositAmount;
uint128[5] rewardAmounts;
}
struct RewardOwed {
IERC20 tokens;
uint128 amount;
}
mapping(address => User) private _users;
uint32 private _rewardsAvailableTimestamp;
bool private _emergencyMode;
uint128 private _totalStakedAmount;
StakingPoolLib.Config private _stakingPoolConfig;
event WithdrawRewards(
address indexed user,
address rewardToken,
uint256 rewards
);
event WithdrawStake(address indexed user, uint256 stake);
event Deposit(address indexed user, uint256 depositAmount);
event InitializeRewards(address rewardTokens, uint256 amount);
event RewardsAvailableTimestamp(uint32 rewardsAvailableTimestamp);
event EmergencyMode(address indexed admin);
event NoRewards(address indexed user);
modifier rewardsAvailable() {
require(_isRewardsAvailable(), "StakingPool: rewards too early");
_;
}
modifier stakingPeriodComplete() {
require(_isStakingPeriodComplete(), "StakingPool: still stake period");
_;
}
modifier stakingPoolRequirementsUnmet() {
//slither-disable-next-line timestamp
require(
(_totalStakedAmount < _stakingPoolConfig.minTotalPoolStake) &&
(block.timestamp > _stakingPoolConfig.epochStartTimestamp),
"StakingPool: requirements unmet"
);
_;
}
modifier emergencyModeEnabled() {
require(_emergencyMode, "StakingPool: not emergency mode");
_;
}
function pause() external whenNotPaused onlyOwner {
_pause();
}
function unpause() external whenPaused onlyOwner {
_unpause();
}
/**
* @notice Only entry point for a user to deposit into the staking pool
*
* @param amount Amount of stake tokens to deposit
*/
function deposit(uint128 amount) external whenNotPaused nonReentrant {
StakingPoolLib.Config storage _config = _stakingPoolConfig;
require(
amount >= _config.minimumContribution,
"StakingPool: min contribution"
);
require(
_totalStakedAmount + amount <= _config.maxTotalPoolStake,
"StakingPool: oversubscribed"
);
//slither-disable-next-line timestamp
require(
block.timestamp < _config.epochStartTimestamp,
"StakingPool: too late"
);
User storage user = _users[_msgSender()];
user.depositAmount += amount;
_totalStakedAmount += amount;
emit Deposit(_msgSender(), amount);
// calculate/update rewards
if (_config.rewardType == StakingPoolLib.RewardType.FLOATING) {
_updateRewardsRatios(_config);
}
if (_config.rewardType == StakingPoolLib.RewardType.FIXED) {
_calculateFixedRewards(_config, user, amount);
}
_config.stakeToken.safeTransferFrom(
_msgSender(),
address(this),
amount
);
}
/**
* @notice Withdraw both stake and reward tokens when the stake period is complete
*/
function withdraw()
external
whenNotPaused
stakingPeriodComplete
rewardsAvailable
nonReentrant
{
User memory user = _users[_msgSender()];
require(user.depositAmount > 0, "StakingPool: not eligible");
delete _users[_msgSender()];
StakingPoolLib.Config storage _config = _stakingPoolConfig;
//slither-disable-next-line reentrancy-events
_transferStake(user.depositAmount, _config.stakeToken);
_withdrawRewards(_config, user);
}
/**
* @notice Withdraw only stake tokens after staking period is complete. Reward tokens may not be available yet.
*/
function withdrawStake()
external
stakingPeriodComplete
nonReentrant
whenNotPaused
{
_withdrawStake();
}
/**
* @notice Withdraw only reward tokens. Stake must have already been withdrawn.
*/
function withdrawRewards()
external
stakingPeriodComplete
rewardsAvailable
whenNotPaused
{
StakingPoolLib.Config memory _config = _stakingPoolConfig;
User memory user = _users[_msgSender()];
require(user.depositAmount == 0, "StakingPool: withdraw stake");
delete _users[_msgSender()];
bool noRewards = true;
for (uint256 i = 0; i < user.rewardAmounts.length; i++) {
if (user.rewardAmounts[i] > 0) {
noRewards = false;
//slither-disable-next-line calls-loop
_transferRewards(
user.rewardAmounts[i],
_config.rewardTokens[i].tokens
);
}
}
if (noRewards) {
emit NoRewards(_msgSender());
}
}
/**
* @notice Withdraw stake tokens when minimum pool conditions to begin are not met
*/
function earlyWithdraw()
external
stakingPoolRequirementsUnmet
whenNotPaused
{
_withdrawWithoutRewards();
}
/**
* @notice Withdraw stake tokens when admin has enabled emergency mode
*/
function emergencyWithdraw() external emergencyModeEnabled {
_withdrawStake();
}
function sweepERC20Tokens(address tokens, uint256 amount)
external
whenNotPaused
onlyOwner
{
_sweepERC20Tokens(tokens, amount);
}
function initialize(
StakingPoolLib.Config calldata info,
bool paused,
uint32 rewardsTimestamp,
address beneficiary
) external virtual initializer {
__Context_init_unchained();
__Pausable_init();
__Ownable_init();
__TokenSweep_init(beneficiary);
//slither-disable-next-line timestamp
require(
info.epochStartTimestamp >= block.timestamp,
"StakingPool: start >= now"
);
_enforceUniqueRewardTokens(info.rewardTokens);
require(
address(info.stakeToken) != address(0),
"StakingPool: stake token defined"
);
//slither-disable-next-line timestamp
require(
rewardsTimestamp > info.epochStartTimestamp + info.epochDuration,
"StakingPool: init rewards"
);
require(info.treasury != address(0), "StakePool: treasury address 0");
require(info.maxTotalPoolStake > 0, "StakePool: maxTotalPoolStake > 0");
require(info.epochDuration > 0, "StakePool: epochDuration > 0");
require(info.minimumContribution > 0, "StakePool: minimumContribution");
if (paused) {
_pause();
}
_rewardsAvailableTimestamp = rewardsTimestamp;
emit RewardsAvailableTimestamp(rewardsTimestamp);
_stakingPoolConfig = info;
}
function initializeRewardTokens(
address benefactor,
StakingPoolLib.Reward[] calldata rewards
) external onlyOwner {
_initializeRewardTokens(benefactor, rewards);
}
function enableEmergencyMode() external onlyOwner {
_emergencyMode = true;
emit EmergencyMode(_msgSender());
}
function adminEmergencyRewardSweep()
external
emergencyModeEnabled
onlyOwner
{
_adminEmergencyRewardSweep();
}
function setRewardsAvailableTimestamp(uint32 timestamp) external onlyOwner {
_setRewardsAvailableTimestamp(timestamp);
}
function updateTokenSweepBeneficiary(address newBeneficiary)
external
whenNotPaused
onlyOwner
{
_setTokenSweepBeneficiary(newBeneficiary);
}
function currentExpectedRewards(address user)
external
view
returns (uint256[] memory)
{
User memory _user = _users[user];
StakingPoolLib.Config memory _config = _stakingPoolConfig;
uint256[] memory rewards = new uint256[](_config.rewardTokens.length);
for (uint256 i = 0; i < _config.rewardTokens.length; i++) {
rewards[i] = _calculateRewardAmount(_config, _user, i);
}
return rewards;
}
function stakingPoolData()
external
view
returns (StakingPoolLib.Config memory)
{
return _stakingPoolConfig;
}
function rewardsAvailableTimestamp() external view returns (uint32) {
return _rewardsAvailableTimestamp;
}
function getUser(address activeUser) external view returns (User memory) {
return _users[activeUser];
}
function emergencyMode() external view returns (bool) {
return _emergencyMode;
}
function totalStakedAmount() external view returns (uint128) {
return _totalStakedAmount;
}
function isRedeemable() external view returns (bool) {
//slither-disable-next-line timestamp
return _isRewardsAvailable() && _isStakingPeriodComplete();
}
function isRewardsAvailable() external view returns (bool) {
return _isRewardsAvailable();
}
function isStakingPeriodComplete() external view returns (bool) {
return _isStakingPeriodComplete();
}
/**
* @notice Returns the final amount of reward due for a user
*
* @param user address to calculate rewards for
*/
function currentRewards(address user)
external
view
returns (RewardOwed[] memory)
{
User memory _user = _users[user];
StakingPoolLib.Config memory _config = _stakingPoolConfig;
RewardOwed[] memory rewards = new RewardOwed[](
_config.rewardTokens.length
);
for (uint256 i = 0; i < _config.rewardTokens.length; i++) {
if (_config.rewardType == StakingPoolLib.RewardType.FLOATING) {
rewards[i] = RewardOwed({
amount: _calculateFloatingReward(
_config.rewardTokens[i].ratio,
_user.depositAmount
),
tokens: _config.rewardTokens[i].tokens
});
}
if (_config.rewardType == StakingPoolLib.RewardType.FIXED) {
rewards[i] = RewardOwed({
amount: _user.rewardAmounts[i],
tokens: _config.rewardTokens[i].tokens
});
}
}
return rewards;
}
function _initializeRewardTokens(
address benefactor,
StakingPoolLib.Reward[] calldata _rewardTokens
) internal {
for (uint256 i = 0; i < _rewardTokens.length; i++) {
emit InitializeRewards(
address(_rewardTokens[i].tokens),
_rewardTokens[i].maxAmount
);
require(
_rewardTokens[i].tokens.allowance(benefactor, address(this)) >=
_rewardTokens[i].maxAmount,
"StakingPool: invalid allowance"
);
_rewardTokens[i].tokens.safeTransferFrom(
benefactor,
address(this),
_rewardTokens[i].maxAmount
);
}
}
function _withdrawWithoutRewards() internal {
User memory user = _users[_msgSender()];
require(user.depositAmount > 0, "StakingPool: not eligible");
delete _users[_msgSender()];
StakingPoolLib.Config memory _config = _stakingPoolConfig;
_transferStake(uint256((user.depositAmount)), _config.stakeToken);
}
function _setRewardsAvailableTimestamp(uint32 timestamp) internal {
require(!_isStakingPeriodComplete(), "StakePool: already finalized");
//slither-disable-next-line timestamp
require(timestamp > block.timestamp, "StakePool: future rewards");
_rewardsAvailableTimestamp = timestamp;
emit RewardsAvailableTimestamp(timestamp);
}
function _transferStake(uint256 amount, IERC20 stakeToken) internal {
emit WithdrawStake(_msgSender(), amount);
_transferToken(amount, stakeToken);
}
function _transferRewards(uint256 amount, IERC20 rewardsToken) internal {
emit WithdrawRewards(_msgSender(), address(rewardsToken), amount);
_transferToken(amount, rewardsToken);
}
function _adminEmergencyRewardSweep() internal {
StakingPoolLib.Reward[] memory rewards = _stakingPoolConfig
.rewardTokens;
address treasury = _stakingPoolConfig.treasury;
for (uint256 i = 0; i < rewards.length; i++) {
rewards[i].tokens.safeTransfer(
treasury,
rewards[i].tokens.balanceOf(address(this))
);
}
}
function _withdrawStake() internal {
User storage user = _users[_msgSender()];
require(user.depositAmount > 0, "StakingPool: not eligible");
uint128 currentDepositBalance = user.depositAmount;
user.depositAmount = 0;
StakingPoolLib.Config storage _config = _stakingPoolConfig;
// set users floating reward if applicable
if (_config.rewardType == StakingPoolLib.RewardType.FLOATING) {
for (uint256 i = 0; i < _config.rewardTokens.length; i++) {
user.rewardAmounts[i] = _calculateFloatingReward(
_config.rewardTokens[i].ratio,
currentDepositBalance
);
}
}
_transferStake(currentDepositBalance, _config.stakeToken);
}
function _isRewardsAvailable() internal view returns (bool) {
//slither-disable-next-line timestamp
return block.timestamp >= _rewardsAvailableTimestamp;
}
function _isStakingPeriodComplete() internal view returns (bool) {
//slither-disable-next-line timestamp
return
block.timestamp >=
(_stakingPoolConfig.epochStartTimestamp +
_stakingPoolConfig.epochDuration);
}
function _calculateRewardAmount(
StakingPoolLib.Config memory _config,
User memory _user,
uint256 rewardIndex
) internal pure returns (uint256) {
if (_config.rewardType == StakingPoolLib.RewardType.FIXED) {
return _user.rewardAmounts[rewardIndex];
}
if (_config.rewardType == StakingPoolLib.RewardType.FLOATING) {
if (_user.depositAmount == 0) {
// user has already withdrawn stake
return _user.rewardAmounts[rewardIndex];
}
// user has not withdrawn stake yet
return
_calculateFloatingReward(
_config.rewardTokens[rewardIndex].ratio,
_user.depositAmount
);
}
return 0;
}
function _calculateFloatingReward(
uint256 rewardAmountRatio,
uint128 depositAmount
) internal pure returns (uint128) {
return uint128((rewardAmountRatio * depositAmount) / 1 ether);
}
function _computeFloatingRewardsPerShare(
uint256 availableTokenRewards,
uint256 total
) internal pure returns (uint256) {
return (availableTokenRewards * 1 ether) / total;
}
function _transferToken(uint256 amount, IERC20 token) private {
//slither-disable-next-line calls-loop
token.safeTransfer(_msgSender(), amount);
}
/**
* @notice Updates the global reward ratios for each reward token in a floating reward pool
*/
function _updateRewardsRatios(StakingPoolLib.Config storage _config)
private
{
for (uint256 i = 0; i < _config.rewardTokens.length; i++) {
_config.rewardTokens[i].ratio = _computeFloatingRewardsPerShare(
_config.rewardTokens[i].maxAmount,
_totalStakedAmount
);
}
}
/**
* @notice Calculates and sets the users reward amount for a fixed reward pool
*/
function _calculateFixedRewards(
StakingPoolLib.Config memory _config,
User storage user,
uint256 amount
) private {
for (uint256 i = 0; i < _config.rewardTokens.length; i++) {
user.rewardAmounts[i] += uint128(
(amount * _config.rewardTokens[i].ratio)
);
}
}
function _withdrawRewards(
StakingPoolLib.Config memory _config,
User memory user
) private {
bool noRewards = true;
// calculate the rewardAmounts due to the user
for (uint256 i = 0; i < _config.rewardTokens.length; i++) {
uint256 amount = _calculateRewardAmount(_config, user, i);
if (amount > 0) {
noRewards = false;
//slither-disable-next-line calls-loop
_transferRewards(amount, _config.rewardTokens[i].tokens);
}
}
if (noRewards) {
emit NoRewards(_msgSender());
}
}
/**
* @notice Enforces that each of the reward tokens are unique
*/
function _enforceUniqueRewardTokens(
StakingPoolLib.Reward[] calldata rewardPools
) private pure {
for (uint256 i = 0; i < rewardPools.length; i++) {
// Ensure no later entries contain the same tokens address
uint256 next = i + 1;
if (next < rewardPools.length) {
for (uint256 j = next; j < rewardPools.length; j++) {
if (rewardPools[i].tokens == rewardPools[j].tokens) {
revert("Rewards: tokens must be unique");
}
}
}
}
}
}
|
user has already withdrawn stake
|
function _calculateRewardAmount(
StakingPoolLib.Config memory _config,
User memory _user,
uint256 rewardIndex
) internal pure returns (uint256) {
if (_config.rewardType == StakingPoolLib.RewardType.FIXED) {
return _user.rewardAmounts[rewardIndex];
}
if (_config.rewardType == StakingPoolLib.RewardType.FLOATING) {
if (_user.depositAmount == 0) {
return _user.rewardAmounts[rewardIndex];
}
_calculateFloatingReward(
_config.rewardTokens[rewardIndex].ratio,
_user.depositAmount
);
}
return 0;
}
| 5,534,238 |
//Address: 0x3f45d2d5feb6b4b000d2d3b84442eeddf54a735a
//Contract name: LiquidPledging
//Balance: 0 Ether
//Verification Date: 12/20/2017
//Transacion Count: 9
// CODE STARTS HERE
//File: contracts/ILiquidPledgingPlugin.sol
pragma solidity ^0.4.11;
/*
Copyright 2017, Jordi Baylina
Contributors: Adrià Massanet <[email protected]>, RJ Ewing, Griff
Green, Arthur Lunn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @dev `ILiquidPledgingPlugin` is the basic interface for any
/// liquid pledging plugin
contract ILiquidPledgingPlugin {
/// @notice Plugins are used (much like web hooks) to initiate an action
/// upon any donation, delegation, or transfer; this is an optional feature
/// and allows for extreme customization of the contract. This function
/// implements any action that should be initiated before a transfer.
/// @param pledgeManager The admin or current manager of the pledge
/// @param pledgeFrom This is the Id from which value will be transfered.
/// @param pledgeTo This is the Id that value will be transfered to.
/// @param context The situation that is triggering the plugin:
/// 0 -> Plugin for the owner transferring pledge to another party
/// 1 -> Plugin for the first delegate transferring pledge to another party
/// 2 -> Plugin for the second delegate transferring pledge to another party
/// ...
/// 255 -> Plugin for the intendedProject transferring pledge to another party
///
/// 256 -> Plugin for the owner receiving pledge to another party
/// 257 -> Plugin for the first delegate receiving pledge to another party
/// 258 -> Plugin for the second delegate receiving pledge to another party
/// ...
/// 511 -> Plugin for the intendedProject receiving pledge to another party
/// @param amount The amount of value that will be transfered.
function beforeTransfer(
uint64 pledgeManager,
uint64 pledgeFrom,
uint64 pledgeTo,
uint64 context,
uint amount ) returns (uint maxAllowed);
/// @notice Plugins are used (much like web hooks) to initiate an action
/// upon any donation, delegation, or transfer; this is an optional feature
/// and allows for extreme customization of the contract. This function
/// implements any action that should be initiated after a transfer.
/// @param pledgeManager The admin or current manager of the pledge
/// @param pledgeFrom This is the Id from which value will be transfered.
/// @param pledgeTo This is the Id that value will be transfered to.
/// @param context The situation that is triggering the plugin:
/// 0 -> Plugin for the owner transferring pledge to another party
/// 1 -> Plugin for the first delegate transferring pledge to another party
/// 2 -> Plugin for the second delegate transferring pledge to another party
/// ...
/// 255 -> Plugin for the intendedProject transferring pledge to another party
///
/// 256 -> Plugin for the owner receiving pledge to another party
/// 257 -> Plugin for the first delegate receiving pledge to another party
/// 258 -> Plugin for the second delegate receiving pledge to another party
/// ...
/// 511 -> Plugin for the intendedProject receiving pledge to another party
/// @param amount The amount of value that will be transfered.
function afterTransfer(
uint64 pledgeManager,
uint64 pledgeFrom,
uint64 pledgeTo,
uint64 context,
uint amount
);
}
//File: node_modules/giveth-common-contracts/contracts/Owned.sol
pragma solidity ^0.4.15;
/// @title Owned
/// @author Adrià Massanet <[email protected]>
/// @notice The Owned contract has an owner address, and provides basic
/// authorization control functions, this simplifies & the implementation of
/// user permissions; this contract has three work flows for a change in
/// ownership, the first requires the new owner to validate that they have the
/// ability to accept ownership, the second allows the ownership to be
/// directly transfered without requiring acceptance, and the third allows for
/// the ownership to be removed to allow for decentralization
contract Owned {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed by, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
event OwnershipRemoved();
/// @dev The constructor sets the `msg.sender` as the`owner` of the contract
function Owned() public {
owner = msg.sender;
}
/// @dev `owner` is the only address that can call a function with this
/// modifier
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
/// @dev In this 1st option for ownership transfer `proposeOwnership()` must
/// be called first by the current `owner` then `acceptOwnership()` must be
/// called by the `newOwnerCandidate`
/// @notice `onlyOwner` Proposes to transfer control of the contract to a
/// new owner
/// @param _newOwnerCandidate The address being proposed as the new owner
function proposeOwnership(address _newOwnerCandidate) public onlyOwner {
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
/// @notice Can only be called by the `newOwnerCandidate`, accepts the
/// transfer of ownership
function acceptOwnership() public {
require(msg.sender == newOwnerCandidate);
address oldOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
/// @dev In this 2nd option for ownership transfer `changeOwnership()` can
/// be called and it will immediately assign ownership to the `newOwner`
/// @notice `owner` can step down and assign some other address to this role
/// @param _newOwner The address of the new owner
function changeOwnership(address _newOwner) public onlyOwner {
require(_newOwner != 0x0);
address oldOwner = owner;
owner = _newOwner;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
/// @dev In this 3rd option for ownership transfer `removeOwnership()` can
/// be called and it will immediately assign ownership to the 0x0 address;
/// it requires a 0xdece be input as a parameter to prevent accidental use
/// @notice Decentralizes the contract, this operation cannot be undone
/// @param _dac `0xdac` has to be entered for this function to work
function removeOwnership(address _dac) public onlyOwner {
require(_dac == 0xdac);
owner = 0x0;
newOwnerCandidate = 0x0;
OwnershipRemoved();
}
}
//File: node_modules/giveth-common-contracts/contracts/ERC20.sol
pragma solidity ^0.4.15;
/**
* @title ERC20
* @dev A standard interface for tokens.
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract ERC20 {
/// @dev Returns the total token supply
function totalSupply() public constant returns (uint256 supply);
/// @dev Returns the account balance of the account with address _owner
function balanceOf(address _owner) public constant returns (uint256 balance);
/// @dev Transfers _value number of tokens to address _to
function transfer(address _to, uint256 _value) public returns (bool success);
/// @dev Transfers _value number of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @dev Allows _spender to withdraw from the msg.sender's account up to the _value amount
function approve(address _spender, uint256 _value) public returns (bool success);
/// @dev Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
//File: node_modules/giveth-common-contracts/contracts/Escapable.sol
pragma solidity ^0.4.15;
/*
Copyright 2016, Jordi Baylina
Contributor: Adrià Massanet <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @dev `Escapable` is a base level contract built off of the `Owned`
/// contract; it creates an escape hatch function that can be called in an
/// emergency that will allow designated addresses to send any ether or tokens
/// held in the contract to an `escapeHatchDestination` as long as they were
/// not blacklisted
contract Escapable is Owned {
address public escapeHatchCaller;
address public escapeHatchDestination;
mapping (address=>bool) private escapeBlacklist; // Token contract addresses
/// @notice The Constructor assigns the `escapeHatchDestination` and the
/// `escapeHatchCaller`
/// @param _escapeHatchCaller The address of a trusted account or contract
/// to call `escapeHatch()` to send the ether in this contract to the
/// `escapeHatchDestination` it would be ideal that `escapeHatchCaller`
/// cannot move funds out of `escapeHatchDestination`
/// @param _escapeHatchDestination The address of a safe location (usu a
/// Multisig) to send the ether held in this contract; if a neutral address
/// is required, the WHG Multisig is an option:
/// 0x8Ff920020c8AD673661c8117f2855C384758C572
function Escapable(address _escapeHatchCaller, address _escapeHatchDestination) public {
escapeHatchCaller = _escapeHatchCaller;
escapeHatchDestination = _escapeHatchDestination;
}
/// @dev The addresses preassigned as `escapeHatchCaller` or `owner`
/// are the only addresses that can call a function with this modifier
modifier onlyEscapeHatchCallerOrOwner {
require ((msg.sender == escapeHatchCaller)||(msg.sender == owner));
_;
}
/// @notice Creates the blacklist of tokens that are not able to be taken
/// out of the contract; can only be done at the deployment, and the logic
/// to add to the blacklist will be in the constructor of a child contract
/// @param _token the token contract address that is to be blacklisted
function blacklistEscapeToken(address _token) internal {
escapeBlacklist[_token] = true;
EscapeHatchBlackistedToken(_token);
}
/// @notice Checks to see if `_token` is in the blacklist of tokens
/// @param _token the token address being queried
/// @return False if `_token` is in the blacklist and can't be taken out of
/// the contract via the `escapeHatch()`
function isTokenEscapable(address _token) constant public returns (bool) {
return !escapeBlacklist[_token];
}
/// @notice The `escapeHatch()` should only be called as a last resort if a
/// security issue is uncovered or something unexpected happened
/// @param _token to transfer, use 0x0 for ether
function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner {
require(escapeBlacklist[_token]==false);
uint256 balance;
/// @dev Logic for ether
if (_token == 0x0) {
balance = this.balance;
escapeHatchDestination.transfer(balance);
EscapeHatchCalled(_token, balance);
return;
}
/// @dev Logic for tokens
ERC20 token = ERC20(_token);
balance = token.balanceOf(this);
require(token.transfer(escapeHatchDestination, balance));
EscapeHatchCalled(_token, balance);
}
/// @notice Changes the address assigned to call `escapeHatch()`
/// @param _newEscapeHatchCaller The address of a trusted account or
/// contract to call `escapeHatch()` to send the value in this contract to
/// the `escapeHatchDestination`; it would be ideal that `escapeHatchCaller`
/// cannot move funds out of `escapeHatchDestination`
function changeHatchEscapeCaller(address _newEscapeHatchCaller) public onlyEscapeHatchCallerOrOwner {
escapeHatchCaller = _newEscapeHatchCaller;
}
event EscapeHatchBlackistedToken(address token);
event EscapeHatchCalled(address token, uint amount);
}
//File: contracts/LiquidPledgingBase.sol
pragma solidity ^0.4.11;
/*
Copyright 2017, Jordi Baylina
Contributors: Adrià Massanet <[email protected]>, RJ Ewing, Griff
Green, Arthur Lunn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @dev This is an interface for `LPVault` which serves as a secure storage for
/// the ETH that backs the Pledges, only after `LiquidPledging` authorizes
/// payments can Pledges be converted for ETH
interface LPVault {
function authorizePayment(bytes32 _ref, address _dest, uint _amount);
function () payable;
}
/// @dev `LiquidPledgingBase` is the base level contract used to carry out
/// liquidPledging's most basic functions, mostly handling and searching the
/// data structures
contract LiquidPledgingBase is Escapable {
// Limits inserted to prevent large loops that could prevent canceling
uint constant MAX_DELEGATES = 10;
uint constant MAX_SUBPROJECT_LEVEL = 20;
uint constant MAX_INTERPROJECT_LEVEL = 20;
enum PledgeAdminType { Giver, Delegate, Project }
enum PledgeState { Pledged, Paying, Paid }
/// @dev This struct defines the details of a `PledgeAdmin` which are
/// commonly referenced by their index in the `admins` array
/// and can own pledges and act as delegates
struct PledgeAdmin {
PledgeAdminType adminType; // Giver, Delegate or Project
address addr; // Account or contract address for admin
string name;
string url; // Can be IPFS hash
uint64 commitTime; // In seconds, used for Givers' & Delegates' vetos
uint64 parentProject; // Only for projects
bool canceled; //Always false except for canceled projects
/// @dev if the plugin is 0x0 then nothing happens, if its an address
// than that smart contract is called when appropriate
ILiquidPledgingPlugin plugin;
}
struct Pledge {
uint amount;
uint64 owner; // PledgeAdmin
uint64[] delegationChain; // List of delegates in order of authority
uint64 intendedProject; // Used when delegates are sending to projects
uint64 commitTime; // When the intendedProject will become the owner
uint64 oldPledge; // Points to the id that this Pledge was derived from
PledgeState pledgeState; // Pledged, Paying, Paid
}
Pledge[] pledges;
PledgeAdmin[] admins; //The list of pledgeAdmins 0 means there is no admin
LPVault public vault;
/// @dev this mapping allows you to search for a specific pledge's
/// index number by the hash of that pledge
mapping (bytes32 => uint64) hPledge2idx;
mapping (bytes32 => bool) pluginWhitelist;
bool public usePluginWhitelist = true;
/////////////
// Modifiers
/////////////
/// @dev The `vault`is the only addresses that can call a function with this
/// modifier
modifier onlyVault() {
require(msg.sender == address(vault));
_;
}
///////////////
// Constructor
///////////////
/// @notice The Constructor creates `LiquidPledgingBase` on the blockchain
/// @param _vault The vault where the ETH backing the pledges is stored
function LiquidPledgingBase(
address _vault,
address _escapeHatchCaller,
address _escapeHatchDestination
) Escapable(_escapeHatchCaller, _escapeHatchDestination) public {
admins.length = 1; // we reserve the 0 admin
pledges.length = 1; // we reserve the 0 pledge
vault = LPVault(_vault); // Assigns the specified vault
}
/////////////////////////
// PledgeAdmin functions
/////////////////////////
/// @notice Creates a Giver Admin with the `msg.sender` as the Admin address
/// @param name The name used to identify the Giver
/// @param url The link to the Giver's profile often an IPFS hash
/// @param commitTime The length of time in seconds the Giver has to
/// veto when the Giver's delegates Pledge funds to a project
/// @param plugin This is Giver's liquid pledge plugin allowing for
/// extended functionality
/// @return idGiver The id number used to reference this Admin
function addGiver(
string name,
string url,
uint64 commitTime,
ILiquidPledgingPlugin plugin
) returns (uint64 idGiver) {
require(isValidPlugin(plugin)); // Plugin check
idGiver = uint64(admins.length);
admins.push(PledgeAdmin(
PledgeAdminType.Giver,
msg.sender,
name,
url,
commitTime,
0,
false,
plugin));
GiverAdded(idGiver);
}
event GiverAdded(uint64 indexed idGiver);
/// @notice Updates a Giver's info to change the address, name, url, or
/// commitTime, it cannot be used to change a plugin, and it must be called
/// by the current address of the Giver
/// @param idGiver This is the Admin id number used to specify the Giver
/// @param newAddr The new address that represents this Giver
/// @param newName The new name used to identify the Giver
/// @param newUrl The new link to the Giver's profile often an IPFS hash
/// @param newCommitTime Sets the length of time in seconds the Giver has to
/// veto when the Giver's delegates Pledge funds to a project
function updateGiver(
uint64 idGiver,
address newAddr,
string newName,
string newUrl,
uint64 newCommitTime)
{
PledgeAdmin storage giver = findAdmin(idGiver);
require(giver.adminType == PledgeAdminType.Giver); // Must be a Giver
require(giver.addr == msg.sender); // Current addr had to send this tx
giver.addr = newAddr;
giver.name = newName;
giver.url = newUrl;
giver.commitTime = newCommitTime;
GiverUpdated(idGiver);
}
event GiverUpdated(uint64 indexed idGiver);
/// @notice Creates a Delegate Admin with the `msg.sender` as the Admin addr
/// @param name The name used to identify the Delegate
/// @param url The link to the Delegate's profile often an IPFS hash
/// @param commitTime Sets the length of time in seconds that this delegate
/// can be vetoed. Whenever this delegate is in a delegate chain the time
/// allowed to veto any event must be greater than or equal to this time.
/// @param plugin This is Delegate's liquid pledge plugin allowing for
/// extended functionality
/// @return idxDelegate The id number used to reference this Delegate within
/// the admins array
function addDelegate(
string name,
string url,
uint64 commitTime,
ILiquidPledgingPlugin plugin
) returns (uint64 idDelegate) {
require(isValidPlugin(plugin)); // Plugin check
idDelegate = uint64(admins.length);
admins.push(PledgeAdmin(
PledgeAdminType.Delegate,
msg.sender,
name,
url,
commitTime,
0,
false,
plugin));
DelegateAdded(idDelegate);
}
event DelegateAdded(uint64 indexed idDelegate);
/// @notice Updates a Delegate's info to change the address, name, url, or
/// commitTime, it cannot be used to change a plugin, and it must be called
/// by the current address of the Delegate
/// @param idDelegate The Admin id number used to specify the Delegate
/// @param newAddr The new address that represents this Delegate
/// @param newName The new name used to identify the Delegate
/// @param newUrl The new link to the Delegate's profile often an IPFS hash
/// @param newCommitTime Sets the length of time in seconds that this
/// delegate can be vetoed. Whenever this delegate is in a delegate chain
/// the time allowed to veto any event must be greater than or equal to
/// this time.
function updateDelegate(
uint64 idDelegate,
address newAddr,
string newName,
string newUrl,
uint64 newCommitTime) {
PledgeAdmin storage delegate = findAdmin(idDelegate);
require(delegate.adminType == PledgeAdminType.Delegate);
require(delegate.addr == msg.sender);// Current addr had to send this tx
delegate.addr = newAddr;
delegate.name = newName;
delegate.url = newUrl;
delegate.commitTime = newCommitTime;
DelegateUpdated(idDelegate);
}
event DelegateUpdated(uint64 indexed idDelegate);
/// @notice Creates a Project Admin with the `msg.sender` as the Admin addr
/// @param name The name used to identify the Project
/// @param url The link to the Project's profile often an IPFS hash
/// @param projectAdmin The address for the trusted project manager
/// @param parentProject The Admin id number for the parent project or 0 if
/// there is no parentProject
/// @param commitTime Sets the length of time in seconds the Project has to
/// veto when the Project delegates to another Delegate and they pledge
/// those funds to a project
/// @param plugin This is Project's liquid pledge plugin allowing for
/// extended functionality
/// @return idProject The id number used to reference this Admin
function addProject(
string name,
string url,
address projectAdmin,
uint64 parentProject,
uint64 commitTime,
ILiquidPledgingPlugin plugin
) returns (uint64 idProject) {
require(isValidPlugin(plugin));
if (parentProject != 0) {
PledgeAdmin storage pa = findAdmin(parentProject);
require(pa.adminType == PledgeAdminType.Project);
require(getProjectLevel(pa) < MAX_SUBPROJECT_LEVEL);
}
idProject = uint64(admins.length);
admins.push(PledgeAdmin(
PledgeAdminType.Project,
projectAdmin,
name,
url,
commitTime,
parentProject,
false,
plugin));
ProjectAdded(idProject);
}
event ProjectAdded(uint64 indexed idProject);
/// @notice Updates a Project's info to change the address, name, url, or
/// commitTime, it cannot be used to change a plugin or a parentProject,
/// and it must be called by the current address of the Project
/// @param idProject The Admin id number used to specify the Project
/// @param newAddr The new address that represents this Project
/// @param newName The new name used to identify the Project
/// @param newUrl The new link to the Project's profile often an IPFS hash
/// @param newCommitTime Sets the length of time in seconds the Project has
/// to veto when the Project delegates to a Delegate and they pledge those
/// funds to a project
function updateProject(
uint64 idProject,
address newAddr,
string newName,
string newUrl,
uint64 newCommitTime)
{
PledgeAdmin storage project = findAdmin(idProject);
require(project.adminType == PledgeAdminType.Project);
require(project.addr == msg.sender);
project.addr = newAddr;
project.name = newName;
project.url = newUrl;
project.commitTime = newCommitTime;
ProjectUpdated(idProject);
}
event ProjectUpdated(uint64 indexed idAdmin);
//////////
// Public constant functions
//////////
/// @notice A constant getter that returns the total number of pledges
/// @return The total number of Pledges in the system
function numberOfPledges() constant returns (uint) {
return pledges.length - 1;
}
/// @notice A getter that returns the details of the specified pledge
/// @param idPledge the id number of the pledge being queried
/// @return the amount, owner, the number of delegates (but not the actual
/// delegates, the intendedProject (if any), the current commit time and
/// the previous pledge this pledge was derived from
function getPledge(uint64 idPledge) constant returns(
uint amount,
uint64 owner,
uint64 nDelegates,
uint64 intendedProject,
uint64 commitTime,
uint64 oldPledge,
PledgeState pledgeState
) {
Pledge storage p = findPledge(idPledge);
amount = p.amount;
owner = p.owner;
nDelegates = uint64(p.delegationChain.length);
intendedProject = p.intendedProject;
commitTime = p.commitTime;
oldPledge = p.oldPledge;
pledgeState = p.pledgeState;
}
/// @notice Getter to find Delegate w/ the Pledge ID & the Delegate index
/// @param idPledge The id number representing the pledge being queried
/// @param idxDelegate The index number for the delegate in this Pledge
function getPledgeDelegate(uint64 idPledge, uint idxDelegate) constant returns(
uint64 idDelegate,
address addr,
string name
) {
Pledge storage p = findPledge(idPledge);
idDelegate = p.delegationChain[idxDelegate - 1];
PledgeAdmin storage delegate = findAdmin(idDelegate);
addr = delegate.addr;
name = delegate.name;
}
/// @notice A constant getter used to check how many total Admins exist
/// @return The total number of admins (Givers, Delegates and Projects) .
function numberOfPledgeAdmins() constant returns(uint) {
return admins.length - 1;
}
/// @notice A constant getter to check the details of a specified Admin
/// @return addr Account or contract address for admin
/// @return name Name of the pledgeAdmin
/// @return url The link to the Project's profile often an IPFS hash
/// @return commitTime The length of time in seconds the Admin has to veto
/// when the Admin delegates to a Delegate and that Delegate pledges those
/// funds to a project
/// @return parentProject The Admin id number for the parent project or 0
/// if there is no parentProject
/// @return canceled 0 for Delegates & Givers, true if a Project has been
/// canceled
/// @return plugin This is Project's liquidPledging plugin allowing for
/// extended functionality
function getPledgeAdmin(uint64 idAdmin) constant returns (
PledgeAdminType adminType,
address addr,
string name,
string url,
uint64 commitTime,
uint64 parentProject,
bool canceled,
address plugin)
{
PledgeAdmin storage m = findAdmin(idAdmin);
adminType = m.adminType;
addr = m.addr;
name = m.name;
url = m.url;
commitTime = m.commitTime;
parentProject = m.parentProject;
canceled = m.canceled;
plugin = address(m.plugin);
}
////////
// Private methods
///////
/// @notice This creates a Pledge with an initial amount of 0 if one is not
/// created already; otherwise it finds the pledge with the specified
/// attributes; all pledges technically exist, if the pledge hasn't been
/// created in this system yet it simply isn't in the hash array
/// hPledge2idx[] yet
/// @param owner The owner of the pledge being looked up
/// @param delegationChain The list of delegates in order of authority
/// @param intendedProject The project this pledge will Fund after the
/// commitTime has passed
/// @param commitTime The length of time in seconds the Giver has to
/// veto when the Giver's delegates Pledge funds to a project
/// @param oldPledge This value is used to store the pledge the current
/// pledge was came from, and in the case a Project is canceled, the Pledge
/// will revert back to it's previous state
/// @param state The pledge state: Pledged, Paying, or state
/// @return The hPledge2idx index number
function findOrCreatePledge(
uint64 owner,
uint64[] delegationChain,
uint64 intendedProject,
uint64 commitTime,
uint64 oldPledge,
PledgeState state
) internal returns (uint64)
{
bytes32 hPledge = sha3(
owner, delegationChain, intendedProject, commitTime, oldPledge, state);
uint64 idx = hPledge2idx[hPledge];
if (idx > 0) return idx;
idx = uint64(pledges.length);
hPledge2idx[hPledge] = idx;
pledges.push(Pledge(
0, owner, delegationChain, intendedProject, commitTime, oldPledge, state));
return idx;
}
/// @notice A getter to look up a Admin's details
/// @param idAdmin The id for the Admin to lookup
/// @return The PledgeAdmin struct for the specified Admin
function findAdmin(uint64 idAdmin) internal returns (PledgeAdmin storage) {
require(idAdmin < admins.length);
return admins[idAdmin];
}
/// @notice A getter to look up a Pledge's details
/// @param idPledge The id for the Pledge to lookup
/// @return The PledgeA struct for the specified Pledge
function findPledge(uint64 idPledge) internal returns (Pledge storage) {
require(idPledge < pledges.length);
return pledges[idPledge];
}
// a constant for when a delegate is requested that is not in the system
uint64 constant NOTFOUND = 0xFFFFFFFFFFFFFFFF;
/// @notice A getter that searches the delegationChain for the level of
/// authority a specific delegate has within a Pledge
/// @param p The Pledge that will be searched
/// @param idDelegate The specified delegate that's searched for
/// @return If the delegate chain contains the delegate with the
/// `admins` array index `idDelegate` this returns that delegates
/// corresponding index in the delegationChain. Otherwise it returns
/// the NOTFOUND constant
function getDelegateIdx(Pledge p, uint64 idDelegate) internal returns(uint64) {
for (uint i=0; i < p.delegationChain.length; i++) {
if (p.delegationChain[i] == idDelegate) return uint64(i);
}
return NOTFOUND;
}
/// @notice A getter to find how many old "parent" pledges a specific Pledge
/// had using a self-referential loop
/// @param p The Pledge being queried
/// @return The number of old "parent" pledges a specific Pledge had
function getPledgeLevel(Pledge p) internal returns(uint) {
if (p.oldPledge == 0) return 0;
Pledge storage oldN = findPledge(p.oldPledge);
return getPledgeLevel(oldN) + 1; // a loop lookup
}
/// @notice A getter to find the longest commitTime out of the owner and all
/// the delegates for a specified pledge
/// @param p The Pledge being queried
/// @return The maximum commitTime out of the owner and all the delegates
function maxCommitTime(Pledge p) internal returns(uint commitTime) {
PledgeAdmin storage m = findAdmin(p.owner);
commitTime = m.commitTime; // start with the owner's commitTime
for (uint i=0; i<p.delegationChain.length; i++) {
m = findAdmin(p.delegationChain[i]);
// If a delegate's commitTime is longer, make it the new commitTime
if (m.commitTime > commitTime) commitTime = m.commitTime;
}
}
/// @notice A getter to find the level of authority a specific Project has
/// using a self-referential loop
/// @param m The Project being queried
/// @return The level of authority a specific Project has
function getProjectLevel(PledgeAdmin m) internal returns(uint) {
assert(m.adminType == PledgeAdminType.Project);
if (m.parentProject == 0) return(1);
PledgeAdmin storage parentNM = findAdmin(m.parentProject);
return getProjectLevel(parentNM) + 1;
}
/// @notice A getter to find if a specified Project has been canceled
/// @param projectId The Admin id number used to specify the Project
/// @return True if the Project has been canceled
function isProjectCanceled(uint64 projectId) constant returns (bool) {
PledgeAdmin storage m = findAdmin(projectId);
if (m.adminType == PledgeAdminType.Giver) return false;
assert(m.adminType == PledgeAdminType.Project);
if (m.canceled) return true;
if (m.parentProject == 0) return false;
return isProjectCanceled(m.parentProject);
}
/// @notice A getter to find the oldest pledge that hasn't been canceled
/// @param idPledge The starting place to lookup the pledges
/// @return The oldest idPledge that hasn't been canceled (DUH!)
function getOldestPledgeNotCanceled(uint64 idPledge
) internal constant returns(uint64) {
if (idPledge == 0) return 0;
Pledge storage p = findPledge(idPledge);
PledgeAdmin storage admin = findAdmin(p.owner);
if (admin.adminType == PledgeAdminType.Giver) return idPledge;
assert(admin.adminType == PledgeAdminType.Project);
if (!isProjectCanceled(p.owner)) return idPledge;
return getOldestPledgeNotCanceled(p.oldPledge);
}
/// @notice A check to see if the msg.sender is the owner or the
/// plugin contract for a specific Admin
/// @param m The Admin being checked
function checkAdminOwner(PledgeAdmin m) internal constant {
require((msg.sender == m.addr) || (msg.sender == address(m.plugin)));
}
///////////////////////////
// Plugin Whitelist Methods
///////////////////////////
function addValidPlugin(bytes32 contractHash) external onlyOwner {
pluginWhitelist[contractHash] = true;
}
function removeValidPlugin(bytes32 contractHash) external onlyOwner {
pluginWhitelist[contractHash] = false;
}
function useWhitelist(bool useWhitelist) external onlyOwner {
usePluginWhitelist = useWhitelist;
}
function isValidPlugin(address addr) public returns(bool) {
if (!usePluginWhitelist || addr == 0x0) return true;
bytes32 contractHash = getCodeHash(addr);
return pluginWhitelist[contractHash];
}
function getCodeHash(address addr) public returns(bytes32) {
bytes memory o_code;
assembly {
// retrieve the size of the code, this needs assembly
let size := extcodesize(addr)
// allocate output byte array - this could also be done without assembly
// by using o_code = new bytes(size)
o_code := mload(0x40)
// new "memory end" including padding
mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f))))
// store length in memory
mstore(o_code, size)
// actually retrieve the code, this needs assembly
extcodecopy(addr, add(o_code, 0x20), 0, size)
}
return keccak256(o_code);
}
}
//File: contracts/LiquidPledging.sol
pragma solidity ^0.4.11;
/*
Copyright 2017, Jordi Baylina
Contributors: Adrià Massanet <[email protected]>, RJ Ewing, Griff
Green, Arthur Lunn
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @dev `LiquidPleding` allows for liquid pledging through the use of
/// internal id structures and delegate chaining. All basic operations for
/// handling liquid pledging are supplied as well as plugin features
/// to allow for expanded functionality.
contract LiquidPledging is LiquidPledgingBase {
//////
// Constructor
//////
/// @notice Basic constructor for LiquidPleding, also calls the
/// LiquidPledgingBase contract
/// @dev This constructor also calls the constructor
/// for `LiquidPledgingBase`
/// @param _vault The vault where ETH backing this pledge is stored
function LiquidPledging(
address _vault,
address _escapeHatchCaller,
address _escapeHatchDestination
) LiquidPledgingBase(_vault, _escapeHatchCaller, _escapeHatchDestination) {
}
/// @notice This is how value enters the system and how pledges are created;
/// the ether is sent to the vault, an pledge for the Giver is created (or
/// found), the amount of ETH donated in wei is added to the `amount` in
/// the Giver's Pledge, and an LP transfer is done to the idReceiver for
/// the full amount
/// @param idGiver The id of the Giver donating; if 0, a new id is created
/// @param idReceiver The Admin receiving the donation; can be any Admin:
/// the Giver themselves, another Giver, a Delegate or a Project
function donate(uint64 idGiver, uint64 idReceiver) payable {
if (idGiver == 0) {
// default to a 3 day (259200 seconds) commitTime
idGiver = addGiver("", "", 259200, ILiquidPledgingPlugin(0x0));
}
PledgeAdmin storage sender = findAdmin(idGiver);
checkAdminOwner(sender);
require(sender.adminType == PledgeAdminType.Giver);
uint amount = msg.value;
require(amount > 0);
vault.transfer(amount); // Sends the `msg.value` (in wei) to the `vault`
uint64 idPledge = findOrCreatePledge(
idGiver,
new uint64[](0), // Creates empty array for delegationChain
0,
0,
0,
PledgeState.Pledged
);
Pledge storage nTo = findPledge(idPledge);
nTo.amount += amount;
Transfer(0, idPledge, amount); // An event
transfer(idGiver, idPledge, amount, idReceiver); // LP accounting
}
/// @notice Transfers amounts between pledges for internal accounting
/// @param idSender Id of the Admin that is transferring the amount from
/// Pledge to Pledge; this admin must have permissions to move the value
/// @param idPledge Id of the pledge that's moving the value
/// @param amount Quantity of ETH (in wei) that this pledge is transferring
/// the authority to withdraw from the vault
/// @param idReceiver Destination of the `amount`, can be a Giver/Project sending
/// to a Giver, a Delegate or a Project; a Delegate sending to another
/// Delegate, or a Delegate pre-commiting it to a Project
function transfer(
uint64 idSender,
uint64 idPledge,
uint amount,
uint64 idReceiver
){
idPledge = normalizePledge(idPledge);
Pledge storage p = findPledge(idPledge);
PledgeAdmin storage receiver = findAdmin(idReceiver);
PledgeAdmin storage sender = findAdmin(idSender);
checkAdminOwner(sender);
require(p.pledgeState == PledgeState.Pledged);
// If the sender is the owner of the Pledge
if (p.owner == idSender) {
if (receiver.adminType == PledgeAdminType.Giver) {
transferOwnershipToGiver(idPledge, amount, idReceiver);
} else if (receiver.adminType == PledgeAdminType.Project) {
transferOwnershipToProject(idPledge, amount, idReceiver);
} else if (receiver.adminType == PledgeAdminType.Delegate) {
uint recieverDIdx = getDelegateIdx(p, idReceiver);
if (p.intendedProject > 0 && recieverDIdx != NOTFOUND) {
// if there is an intendedProject and the receiver is in the delegationChain,
// then we want to preserve the delegationChain as this is a veto of the
// intendedProject by the owner
if (recieverDIdx == p.delegationChain.length - 1) {
uint64 toPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged);
doTransfer(idPledge, toPledge, amount);
} else {
undelegate(idPledge, amount, p.delegationChain.length - receiverDIdx - 1);
}
} else {
// owner is not vetoing an intendedProject and is transferring the pledge to a delegate,
// so we want to reset the delegationChain
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length
);
appendDelegate(idPledge, amount, idReceiver);
}
} else {
// This should never be reached as the reciever.adminType
// should always be either a Giver, Project, or Delegate
assert(false);
}
return;
}
// If the sender is a Delegate
uint senderDIdx = getDelegateIdx(p, idSender);
if (senderDIdx != NOTFOUND) {
// And the receiver is another Giver
if (receiver.adminType == PledgeAdminType.Giver) {
// Only transfer to the Giver who owns the pldege
assert(p.owner == idReceiver);
undelegate(idPledge, amount, p.delegationChain.length);
return;
}
// And the receiver is another Delegate
if (receiver.adminType == PledgeAdminType.Delegate) {
uint receiverDIdx = getDelegateIdx(p, idReceiver);
// And not in the delegationChain
if (receiverDIdx == NOTFOUND) {
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length - senderDIdx - 1
);
appendDelegate(idPledge, amount, idReceiver);
// And part of the delegationChain and is after the sender, then
// all of the other delegates after the sender are removed and
// the receiver is appended at the end of the delegationChain
} else if (receiverDIdx > senderDIdx) {
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length - senderDIdx - 1
);
appendDelegate(idPledge, amount, idReceiver);
// And is already part of the delegate chain but is before the
// sender, then the sender and all of the other delegates after
// the RECEIVER are removed from the delegationChain
} else if (receiverDIdx <= senderDIdx) {//TODO Check for Game Theory issues (from Arthur) this allows the sender to sort of go komakosi and remove himself and the delegates between himself and the receiver... should this authority be allowed?
undelegate(
idPledge,
amount,
p.delegationChain.length - receiverDIdx - 1
);
}
return;
}
// And the receiver is a Project, all the delegates after the sender
// are removed and the amount is pre-committed to the project
if (receiver.adminType == PledgeAdminType.Project) {
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length - senderDIdx - 1
);
proposeAssignProject(idPledge, amount, idReceiver);
return;
}
}
assert(false); // When the sender is not an owner or a delegate
}
/// @notice Authorizes a payment be made from the `vault` can be used by the
/// Giver to veto a pre-committed donation from a Delegate to an
/// intendedProject
/// @param idPledge Id of the pledge that is to be redeemed into ether
/// @param amount Quantity of ether (in wei) to be authorized
function withdraw(uint64 idPledge, uint amount) {
idPledge = normalizePledge(idPledge); // Updates pledge info
Pledge storage p = findPledge(idPledge);
require(p.pledgeState == PledgeState.Pledged);
PledgeAdmin storage owner = findAdmin(p.owner);
checkAdminOwner(owner);
uint64 idNewPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Paying
);
doTransfer(idPledge, idNewPledge, amount);
vault.authorizePayment(bytes32(idNewPledge), owner.addr, amount);
}
/// @notice `onlyVault` Confirms a withdraw request changing the PledgeState
/// from Paying to Paid
/// @param idPledge Id of the pledge that is to be withdrawn
/// @param amount Quantity of ether (in wei) to be withdrawn
function confirmPayment(uint64 idPledge, uint amount) onlyVault {
Pledge storage p = findPledge(idPledge);
require(p.pledgeState == PledgeState.Paying);
uint64 idNewPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Paid
);
doTransfer(idPledge, idNewPledge, amount);
}
/// @notice `onlyVault` Cancels a withdraw request, changing the PledgeState
/// from Paying back to Pledged
/// @param idPledge Id of the pledge that's withdraw is to be canceled
/// @param amount Quantity of ether (in wei) to be canceled
function cancelPayment(uint64 idPledge, uint amount) onlyVault {
Pledge storage p = findPledge(idPledge);
require(p.pledgeState == PledgeState.Paying); //TODO change to revert????????????????????????????
// When a payment is canceled, never is assigned to a project.
uint64 oldPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
oldPledge = normalizePledge(oldPledge);
doTransfer(idPledge, oldPledge, amount);
}
/// @notice Changes the `project.canceled` flag to `true`; cannot be undone
/// @param idProject Id of the project that is to be canceled
function cancelProject(uint64 idProject) {
PledgeAdmin storage project = findAdmin(idProject);
checkAdminOwner(project);
project.canceled = true;
CancelProject(idProject);
}
/// @notice Transfers `amount` in `idPledge` back to the `oldPledge` that
/// that sent it there in the first place, a Ctrl-z
/// @param idPledge Id of the pledge that is to be canceled
/// @param amount Quantity of ether (in wei) to be transfered to the
/// `oldPledge`
function cancelPledge(uint64 idPledge, uint amount) {
idPledge = normalizePledge(idPledge);
Pledge storage p = findPledge(idPledge);
require(p.oldPledge != 0);
PledgeAdmin storage m = findAdmin(p.owner);
checkAdminOwner(m);
uint64 oldPledge = getOldestPledgeNotCanceled(p.oldPledge);
doTransfer(idPledge, oldPledge, amount);
}
////////
// Multi pledge methods
////////
// @dev This set of functions makes moving a lot of pledges around much more
// efficient (saves gas) than calling these functions in series
/// @dev Bitmask used for dividing pledge amounts in Multi pledge methods
uint constant D64 = 0x10000000000000000;
/// @notice Transfers multiple amounts within multiple Pledges in an
/// efficient single call
/// @param idSender Id of the Admin that is transferring the amounts from
/// all the Pledges; this admin must have permissions to move the value
/// @param pledgesAmounts An array of Pledge amounts and the idPledges with
/// which the amounts are associated; these are extrapolated using the D64
/// bitmask
/// @param idReceiver Destination of the `pledesAmounts`, can be a Giver or
/// Project sending to a Giver, a Delegate or a Project; a Delegate sending
/// to another Delegate, or a Delegate pre-commiting it to a Project
function mTransfer(
uint64 idSender,
uint[] pledgesAmounts,
uint64 idReceiver
) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
transfer(idSender, idPledge, amount, idReceiver);
}
}
/// @notice Authorizes multiple amounts within multiple Pledges to be
/// withdrawn from the `vault` in an efficient single call
/// @param pledgesAmounts An array of Pledge amounts and the idPledges with
/// which the amounts are associated; these are extrapolated using the D64
/// bitmask
function mWithdraw(uint[] pledgesAmounts) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
withdraw(idPledge, amount);
}
}
/// @notice `mConfirmPayment` allows for multiple pledges to be confirmed
/// efficiently
/// @param pledgesAmounts An array of pledge amounts and IDs which are extrapolated
/// using the D64 bitmask
function mConfirmPayment(uint[] pledgesAmounts) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
confirmPayment(idPledge, amount);
}
}
/// @notice `mCancelPayment` allows for multiple pledges to be canceled
/// efficiently
/// @param pledgesAmounts An array of pledge amounts and IDs which are extrapolated
/// using the D64 bitmask
function mCancelPayment(uint[] pledgesAmounts) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
cancelPayment(idPledge, amount);
}
}
/// @notice `mNormalizePledge` allows for multiple pledges to be
/// normalized efficiently
/// @param pledges An array of pledge IDs
function mNormalizePledge(uint64[] pledges) {
for (uint i = 0; i < pledges.length; i++ ) {
normalizePledge( pledges[i] );
}
}
////////
// Private methods
///////
/// @notice `transferOwnershipToProject` allows for the transfer of
/// ownership to the project, but it can also be called by a project
/// to un-delegate everyone by setting one's own id for the idReceiver
/// @param idPledge Id of the pledge to be transfered.
/// @param amount Quantity of value that's being transfered
/// @param idReceiver The new owner of the project (or self to un-delegate)
function transferOwnershipToProject(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
Pledge storage p = findPledge(idPledge);
// Ensure that the pledge is not already at max pledge depth
// and the project has not been canceled
require(getPledgeLevel(p) < MAX_INTERPROJECT_LEVEL);
require(!isProjectCanceled(idReceiver));
uint64 oldPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
uint64 toPledge = findOrCreatePledge(
idReceiver, // Set the new owner
new uint64[](0), // clear the delegation chain
0,
0,
oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
/// @notice `transferOwnershipToGiver` allows for the transfer of
/// value back to the Giver, value is placed in a pledged state
/// without being attached to a project, delegation chain, or time line.
/// @param idPledge Id of the pledge to be transfered.
/// @param amount Quantity of value that's being transfered
/// @param idReceiver The new owner of the pledge
function transferOwnershipToGiver(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
uint64 toPledge = findOrCreatePledge(
idReceiver,
new uint64[](0),
0,
0,
0,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
/// @notice `appendDelegate` allows for a delegate to be added onto the
/// end of the delegate chain for a given Pledge.
/// @param idPledge Id of the pledge thats delegate chain will be modified.
/// @param amount Quantity of value that's being chained.
/// @param idReceiver The delegate to be added at the end of the chain
function appendDelegate(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
Pledge storage p = findPledge(idPledge);
require(p.delegationChain.length < MAX_DELEGATES);
uint64[] memory newDelegationChain = new uint64[](
p.delegationChain.length + 1
);
for (uint i = 0; i<p.delegationChain.length; i++) {
newDelegationChain[i] = p.delegationChain[i];
}
// Make the last item in the array the idReceiver
newDelegationChain[p.delegationChain.length] = idReceiver;
uint64 toPledge = findOrCreatePledge(
p.owner,
newDelegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
/// @notice `appendDelegate` allows for a delegate to be added onto the
/// end of the delegate chain for a given Pledge.
/// @param idPledge Id of the pledge thats delegate chain will be modified.
/// @param amount Quantity of value that's shifted from delegates.
/// @param q Number (or depth) of delegates to remove
/// @return toPledge The id for the pledge being adjusted or created
function undelegate(
uint64 idPledge,
uint amount,
uint q
) internal returns (uint64)
{
Pledge storage p = findPledge(idPledge);
uint64[] memory newDelegationChain = new uint64[](
p.delegationChain.length - q
);
for (uint i=0; i<p.delegationChain.length - q; i++) {
newDelegationChain[i] = p.delegationChain[i];
}
uint64 toPledge = findOrCreatePledge(
p.owner,
newDelegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
return toPledge;
}
/// @notice `proposeAssignProject` proposes the assignment of a pledge
/// to a specific project.
/// @dev This function should potentially be named more specifically.
/// @param idPledge Id of the pledge that will be assigned.
/// @param amount Quantity of value this pledge leader would be assigned.
/// @param idReceiver The project this pledge will potentially
/// be assigned to.
function proposeAssignProject(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
Pledge storage p = findPledge(idPledge);
require(getPledgeLevel(p) < MAX_INTERPROJECT_LEVEL);
require(!isProjectCanceled(idReceiver));
uint64 toPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
idReceiver,
uint64(getTime() + maxCommitTime(p)),
p.oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
/// @notice `doTransfer` is designed to allow for pledge amounts to be
/// shifted around internally.
/// @param from This is the Id from which value will be transfered.
/// @param to This is the Id that value will be transfered to.
/// @param _amount The amount of value that will be transfered.
function doTransfer(uint64 from, uint64 to, uint _amount) internal {
uint amount = callPlugins(true, from, to, _amount);
if (from == to) {
return;
}
if (amount == 0) {
return;
}
Pledge storage nFrom = findPledge(from);
Pledge storage nTo = findPledge(to);
require(nFrom.amount >= amount);
nFrom.amount -= amount;
nTo.amount += amount;
Transfer(from, to, amount);
callPlugins(false, from, to, amount);
}
/// @notice Only affects pledges with the Pledged PledgeState for 2 things:
/// #1: Checks if the pledge should be committed. This means that
/// if the pledge has an intendedProject and it is past the
/// commitTime, it changes the owner to be the proposed project
/// (The UI will have to read the commit time and manually do what
/// this function does to the pledge for the end user
/// at the expiration of the commitTime)
///
/// #2: Checks to make sure that if there has been a cancellation in the
/// chain of projects, the pledge's owner has been changed
/// appropriately.
///
/// This function can be called by anybody at anytime on any pledge.
/// In general it can be called to force the calls of the affected
/// plugins, which also need to be predicted by the UI
/// @param idPledge This is the id of the pledge that will be normalized
/// @return The normalized Pledge!
function normalizePledge(uint64 idPledge) returns(uint64) {
Pledge storage p = findPledge(idPledge);
// Check to make sure this pledge hasn't already been used
// or is in the process of being used
if (p.pledgeState != PledgeState.Pledged) {
return idPledge;
}
// First send to a project if it's proposed and committed
if ((p.intendedProject > 0) && ( getTime() > p.commitTime)) {
uint64 oldPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
uint64 toPledge = findOrCreatePledge(
p.intendedProject,
new uint64[](0),
0,
0,
oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, p.amount);
idPledge = toPledge;
p = findPledge(idPledge);
}
toPledge = getOldestPledgeNotCanceled(idPledge);
if (toPledge != idPledge) {
doTransfer(idPledge, toPledge, p.amount);
}
return toPledge;
}
/////////////
// Plugins
/////////////
/// @notice `callPlugin` is used to trigger the general functions in the
/// plugin for any actions needed before and after a transfer happens.
/// Specifically what this does in relation to the plugin is something
/// that largely depends on the functions of that plugin. This function
/// is generally called in pairs, once before, and once after a transfer.
/// @param before This toggle determines whether the plugin call is occurring
/// before or after a transfer.
/// @param adminId This should be the Id of the *trusted* individual
/// who has control over this plugin.
/// @param fromPledge This is the Id from which value is being transfered.
/// @param toPledge This is the Id that value is being transfered to.
/// @param context The situation that is triggering the plugin. See plugin
/// for a full description of contexts.
/// @param amount The amount of value that is being transfered.
function callPlugin(
bool before,
uint64 adminId,
uint64 fromPledge,
uint64 toPledge,
uint64 context,
uint amount
) internal returns (uint allowedAmount) {
uint newAmount;
allowedAmount = amount;
PledgeAdmin storage admin = findAdmin(adminId);
// Checks admin has a plugin assigned and a non-zero amount is requested
if ((address(admin.plugin) != 0) && (allowedAmount > 0)) {
// There are two seperate functions called in the plugin.
// One is called before the transfer and one after
if (before) {
newAmount = admin.plugin.beforeTransfer(
adminId,
fromPledge,
toPledge,
context,
amount
);
require(newAmount <= allowedAmount);
allowedAmount = newAmount;
} else {
admin.plugin.afterTransfer(
adminId,
fromPledge,
toPledge,
context,
amount
);
}
}
}
/// @notice `callPluginsPledge` is used to apply plugin calls to
/// the delegate chain and the intended project if there is one.
/// It does so in either a transferring or receiving context based
/// on the `idPledge` and `fromPledge` parameters.
/// @param before This toggle determines whether the plugin call is occuring
/// before or after a transfer.
/// @param idPledge This is the Id of the pledge on which this plugin
/// is being called.
/// @param fromPledge This is the Id from which value is being transfered.
/// @param toPledge This is the Id that value is being transfered to.
/// @param amount The amount of value that is being transfered.
function callPluginsPledge(
bool before,
uint64 idPledge,
uint64 fromPledge,
uint64 toPledge,
uint amount
) internal returns (uint allowedAmount) {
// Determine if callPlugin is being applied in a receiving
// or transferring context
uint64 offset = idPledge == fromPledge ? 0 : 256;
allowedAmount = amount;
Pledge storage p = findPledge(idPledge);
// Always call the plugin on the owner
allowedAmount = callPlugin(
before,
p.owner,
fromPledge,
toPledge,
offset,
allowedAmount
);
// Apply call plugin to all delegates
for (uint64 i=0; i<p.delegationChain.length; i++) {
allowedAmount = callPlugin(
before,
p.delegationChain[i],
fromPledge,
toPledge,
offset + i+1,
allowedAmount
);
}
// If there is an intended project also call the plugin in
// either a transferring or receiving context based on offset
// on the intended project
if (p.intendedProject > 0) {
allowedAmount = callPlugin(
before,
p.intendedProject,
fromPledge,
toPledge,
offset + 255,
allowedAmount
);
}
}
/// @notice `callPlugins` calls `callPluginsPledge` once for the transfer
/// context and once for the receiving context. The aggregated
/// allowed amount is then returned.
/// @param before This toggle determines whether the plugin call is occurring
/// before or after a transfer.
/// @param fromPledge This is the Id from which value is being transferred.
/// @param toPledge This is the Id that value is being transferred to.
/// @param amount The amount of value that is being transferred.
function callPlugins(
bool before,
uint64 fromPledge,
uint64 toPledge,
uint amount
) internal returns (uint allowedAmount) {
allowedAmount = amount;
// Call the pledges plugins in the transfer context
allowedAmount = callPluginsPledge(
before,
fromPledge,
fromPledge,
toPledge,
allowedAmount
);
// Call the pledges plugins in the receive context
allowedAmount = callPluginsPledge(
before,
toPledge,
fromPledge,
toPledge,
allowedAmount
);
}
/////////////
// Test functions
/////////////
/// @notice Basic helper function to return the current time
function getTime() internal returns (uint) {
return now;
}
// Event Delcerations
event Transfer(uint64 indexed from, uint64 indexed to, uint amount);
event CancelProject(uint64 indexed idProject);
}
|
A getter to find if a specified Project has been canceled projectId The Admin id number used to specify the Project return True if the Project has been canceled
|
function isProjectCanceled(uint64 projectId) constant returns (bool) {
PledgeAdmin storage m = findAdmin(projectId);
if (m.adminType == PledgeAdminType.Giver) return false;
assert(m.adminType == PledgeAdminType.Project);
if (m.canceled) return true;
if (m.parentProject == 0) return false;
return isProjectCanceled(m.parentProject);
}
| 12,923,160 |
./partial_match/137/0xD1178fC23853c2d469fddf5303F1bB026FbD3DB9/sources/WildcardSteward_matic_v1.sol
|
Required interface of an ERC721 compliant contract./
|
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
}
| 3,527,149 |
//Address: 0x7f1d1c0a0c3a5ff6f5523b939b769b9f88509122
//Contract name: PeerLicensing
//Balance: 0.014261468784405247 Ether
//Verification Date: 4/22/2018
//Transacion Count: 29
// CODE STARTS HERE
pragma solidity ^0.4.23;/*
_ _____ ___ _ _ __
` __ ___ ___ _ _ ,'
`. __ ____ /__ ,'
`. __ __ / ,'
`.__ _ /_,'
`. _ /,'
`./'
,/`.
,'/ __`.
,'_/_ _ _`.
,'__/_ ___ _ `.
,'_ /___ __ _ __ `.
'-.._/____ _ __ _`.
Decentralized Securities Licensing
*/contract PeerLicensing {
// scaleFactor is used to convert Ether into tokens and vice-versa: they're of different
// orders of magnitude, hence the need to bridge between the two.
uint256 constant scaleFactor = 0x10000000000000000; // 2^64
// CRR = 50%
// CRR is Cash Reserve Ratio (in this case Crypto Reserve Ratio).
// For more on this: check out https://en.wikipedia.org/wiki/Reserve_requirement
uint256 constant trickTax = 3;//divides flux'd fee and for every pass up
int constant crr_n = 1; // CRR numerator
int constant crr_d = 2; // CRR denominator
int constant price_coeff = 0x299DC11F94E57CEB1;
// Array between each address and their number of tokens.
//mapping(address => uint256) public tokenBalance;
mapping(address => uint256) public holdings_BULL;
mapping(address => uint256) public holdings_BEAR;
//cut down by a percentage when you sell out.
mapping(address => uint256) public avgFactor_ethSpent;
//Particle Coloring
//this will change at the same rate in either market
/*mapping(address => uint256) public souleculeEdgeR0;
mapping(address => uint256) public souleculeEdgeG0;
mapping(address => uint256) public souleculeEdgeB0;
mapping(address => uint256) public souleculeEdgeR1;
mapping(address => uint256) public souleculeEdgeG1;
mapping(address => uint256) public souleculeEdgeB1;
//this should change slower in a bull market. faster in a bear market
mapping(address => uint256) public souleculeCoreR0;
mapping(address => uint256) public souleculeCoreG0;
mapping(address => uint256) public souleculeCoreB0;
mapping(address => uint256) public souleculeCoreR1;
mapping(address => uint256) public souleculeCoreG1;
mapping(address => uint256) public souleculeCoreB1;*/
// Array between each address and how much Ether has been paid out to it.
// Note that this is scaled by the scaleFactor variable.
mapping(address => address) public reff;
mapping(address => uint256) public tricklePocket;
mapping(address => uint256) public trickling;
mapping(address => int256) public payouts;
// Variable tracking how many tokens are in existence overall.
uint256 public totalBondSupply_BULL;
uint256 public totalBondSupply_BEAR;
// Aggregate sum of all payouts.
// Note that this is scaled by the scaleFactor variable.
int256 totalPayouts;
uint256 public tricklingSum;
uint256 public stakingRequirement = 1e18;
address public lastGateway;
//flux fee ratio score keepers
uint256 public withdrawSum;
uint256 public investSum;
// Variable tracking how much Ether each token is currently worth.
// Note that this is scaled by the scaleFactor variable.
uint256 earningsPerBond_BULL;
uint256 earningsPerBond_BEAR;
function PeerLicensing() public {
}
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
bool token
);
event onTokenSell(
address indexed customerAddress,
uint256 totalTokensAtTheTime,//maybe it'd be cool to see what % people are selling from their total bank
uint256 tokensBurned,
uint256 ethereumEarned,
bool token,
uint256 resolved
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted,
bool token
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// The following functions are used by the front-end for display purposes.
// Returns the number of tokens currently held by _owner.
function holdingsOf(address _owner) public constant returns (uint256 balance) {
return holdings_BULL[_owner] + holdings_BEAR[_owner];
}
function holdingsOf_BULL(address _owner) public constant returns (uint256 balance) {
return holdings_BULL[_owner];
}
function holdingsOf_BEAR(address _owner) public constant returns (uint256 balance) {
return holdings_BEAR[_owner];
}
// Withdraws all dividends held by the caller sending the transaction, updates
// the requisite global variables, and transfers Ether back to the caller.
function withdraw() public {
trickleUp();
// Retrieve the dividends associated with the address the request came from.
var balance = dividends(msg.sender);
var pocketBalance = tricklePocket[msg.sender];
tricklePocket[msg.sender] = 0;
tricklingSum = sub(tricklingSum,pocketBalance);
uint256 out =add(balance, pocketBalance);
// Update the payouts array, incrementing the request address by `balance`.
payouts[msg.sender] += (int256) (balance * scaleFactor);
// Increase the total amount that's been paid out to maintain invariance.
totalPayouts += (int256) (balance * scaleFactor);
// Send the dividends to the address that requested the withdraw.
withdrawSum = add(withdrawSum,out);
msg.sender.transfer(out);
onWithdraw(msg.sender, out);
}
function withdrawOld(address to) public {
trickleUp();
// Retrieve the dividends associated with the address the request came from.
var balance = dividends(msg.sender);
var pocketBalance = tricklePocket[msg.sender];
tricklePocket[msg.sender] = 0;
tricklingSum = sub(tricklingSum,pocketBalance);//gotta preserve that things for dynamic calculation
uint256 out =add(balance, pocketBalance);
// Update the payouts array, incrementing the request address by `balance`.
payouts[msg.sender] += (int256) (balance * scaleFactor);
// Increase the total amount that's been paid out to maintain invariance.
totalPayouts += (int256) (balance * scaleFactor);
// Send the dividends to the address that requested the withdraw.
withdrawSum = add(withdrawSum,out);
to.transfer(out);
onWithdraw(to,out);
}
function fullCycleSellBonds(uint256 balance) internal {
// Send the cashed out stake to the address that requested the withdraw.
withdrawSum = add(withdrawSum,balance );
msg.sender.transfer(balance);
emit onWithdraw(msg.sender, balance);
}
// Sells your tokens for Ether. This Ether is assigned to the callers entry
// in the tokenBalance array, and therefore is shown as a dividend. A second
// call to withdraw() must be made to invoke the transfer of Ether back to your address.
function sellBonds(uint256 _amount, bool bondType) public {
uint256 bondBalance;
if(bondType){
bondBalance = holdings_BULL[msg.sender];
}else{
bondBalance = holdings_BEAR[msg.sender];
}
if(_amount <= bondBalance && _amount > 0){
sell(_amount,bondType);
}else{
if(_amount > bondBalance ){
sell(bondBalance,bondType);
}else{
revert();
}
}
}
// The slam-the-button escape hatch. Sells the callers tokens for Ether, then immediately
// invokes the withdraw() function, sending the resulting Ether to the callers address.
function getMeOutOfHere() public {
sellBonds( holdings_BULL[msg.sender] ,true);
sellBonds( holdings_BEAR[msg.sender] ,false);
withdraw();
}
function reffUp(address _reff) internal{
address sender = msg.sender;
if (_reff == 0x0000000000000000000000000000000000000000)
_reff = lastGateway;
if( add(holdings_BEAR[_reff],holdings_BULL[_reff]) >= stakingRequirement ) {
//good to go. good gateway
}else{
if(lastGateway == 0x0000000000000000000000000000000000000000){
lastGateway = sender;//first buyer ever
_reff = sender;//first buyer is their own gateway/masternode
}
else
_reff = lastGateway;//the lucky last player gets to be the gate way.
}
reff[sender] = _reff;
}
// Gatekeeper function to check if the amount of Ether being sent isn't either
// too small or too large. If it passes, goes direct to buy().
/*function rgbLimit(uint256 _rgb)internal pure returns(uint256){
if(_rgb > 255)
return 255;
else
return _rgb;
}*/
//BONUS
/*function edgePigmentR() internal returns (uint256 x)
{return 255 * souleculeEdgeR1[msg.sender] / (souleculeEdgeR0[msg.sender]+souleculeEdgeR1[msg.sender]);}
function edgePigmentG() internal returns (uint256 x)
{return 255 * souleculeEdgeG1[msg.sender] / (souleculeEdgeG0[msg.sender]+souleculeEdgeG1[msg.sender]);}
function edgePigmentB() internal returns (uint256 x)
{return 255 * souleculeEdgeB1[msg.sender] / (souleculeEdgeB0[msg.sender]+souleculeEdgeB1[msg.sender]);}*/
function fund(address _reff,bool bondType) payable public {
// Don't allow for funding if the amount of Ether sent is less than 1 szabo.
reffUp(_reff);
if (msg.value > 0.000001 ether) {
investSum = add(investSum,msg.value);
buy(bondType/*,edgePigmentR(),edgePigmentG(),edgePigmentB()*/);
lastGateway = msg.sender;
} else {
revert();
}
}
// Function that returns the (dynamic) price of buying a finney worth of tokens.
function buyPrice() public constant returns (uint) {
return getTokensForEther(1 finney);
}
// Function that returns the (dynamic) price of selling a single token.
function sellPrice() public constant returns (uint) {
var eth = getEtherForTokens(1 finney);
var fee = fluxFeed(eth, false);
return eth - fee;
}
function fluxFeed(uint256 _eth, bool slim_reinvest) public constant returns (uint256 amount) {
if (withdrawSum == 0){
return 0;
}else{
if(slim_reinvest){
return div( mul(_eth , withdrawSum), mul(investSum,3) );//discount for supporting the Pyramid
}else{
return div( mul(_eth , withdrawSum), investSum);// amount * withdrawSum / investSum
}
}
//gotta multiply and stuff in that order in order to get a high precision taxed amount.
// because grouping (withdrawSum / investSum) can't return a precise decimal.
//so instead we expand the value by multiplying then shrink it. by the denominator
/*
100eth IN & 100eth OUT = 100% tax fee (returning 1) !!!
100eth IN & 50eth OUT = 50% tax fee (returning 2)
100eth IN & 33eth OUT = 33% tax fee (returning 3)
100eth IN & 25eth OUT = 25% tax fee (returning 4)
100eth IN & 10eth OUT = 10% tax fee (returning 10)
!!! keep in mind there is no fee if there are no holders. So if 100% of the eth has left the contract that means there can't possibly be holders to tax you
*/
}
// Calculate the current dividends associated with the caller address. This is the net result
// of multiplying the number of tokens held by their current value in Ether and subtracting the
// Ether that has already been paid out.
function dividends(address _owner) public constant returns (uint256 amount) {
return (uint256) ((int256)(earningsPerBond_BULL * holdings_BULL[_owner] + earningsPerBond_BEAR * holdings_BEAR[_owner]) - payouts[_owner]) / scaleFactor;
}
function cashWallet(address _owner) public constant returns (uint256 amount) {
return tricklePocket[_owner] + dividends(_owner);
}
// Internal balance function, used to calculate the dynamic reserve value.
function balance() internal constant returns (uint256 amount){
// msg.value is the amount of Ether sent by the transaction.
return sub(sub(investSum,withdrawSum) ,add( msg.value , tricklingSum));
}
function trickleUp() internal{
uint256 tricks = trickling[ msg.sender ];
if(tricks > 0){
trickling[ msg.sender ] = 0;
uint256 passUp = div(tricks,trickTax);
uint256 reward = sub(tricks,passUp);//trickling[]
address reffo = reff[msg.sender];
if( holdingsOf(reffo) < stakingRequirement){
trickling[ reffo ] = add(trickling[ reffo ],passUp);
tricklePocket[ reffo ] = add(tricklePocket[ reffo ],reward);
}else{//basically. if your referral guy bailed out then he can't get the rewards, instead give it to the new guy that was baited in by this feature
trickling[ lastGateway ] = add(trickling[ lastGateway ],passUp);
tricklePocket[ lastGateway ] = add(tricklePocket[ lastGateway ],reward);
}/**/
}
}
function buy(bool bondType/*, uint256 soulR,uint256 soulG,uint256 soulB*/) internal {
// Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it.
if (msg.value < 0.000001 ether || msg.value > 1000000 ether)
revert();
// msg.sender is the address of the caller.
var sender = msg.sender;
// 10% of the total Ether sent is used to pay existing holders.
uint256 fee = 0;
uint256 trickle = 0;
if(holdings_BULL[sender] != totalBondSupply_BULL){
fee = fluxFeed(msg.value,false);
trickle = div(fee, trickTax);
fee = sub(fee , trickle);
trickling[sender] = add(trickling[sender],trickle);
}
var numEther = sub(msg.value , add(fee , trickle));// The amount of Ether used to purchase new tokens for the caller.
var numTokens = getTokensForEther(numEther);// The number of tokens which can be purchased for numEther.
// The buyer fee, scaled by the scaleFactor variable.
var buyerFee = fee * scaleFactor;
if (totalBondSupply_BULL > 0){// because ...
// Compute the bonus co-efficient for all existing holders and the buyer.
// The buyer receives part of the distribution for each token bought in the
// same way they would have if they bought each token individually.
uint256 bonusCoEff;
if(bondType){
bonusCoEff = (scaleFactor - (reserve() + numEther) * numTokens * scaleFactor / ( totalBondSupply_BULL + totalBondSupply_BEAR + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n);
}else{
bonusCoEff = scaleFactor;
}
// The total reward to be distributed amongst the masses is the fee (in Ether)
// multiplied by the bonus co-efficient.
var holderReward = fee * bonusCoEff;
buyerFee -= holderReward;
// The Ether value per token is increased proportionally.
earningsPerBond_BULL = add(earningsPerBond_BULL,div(holderReward , totalBondSupply_BULL));
}
//resolve reward tracking stuff
avgFactor_ethSpent[msg.sender] = add(avgFactor_ethSpent[msg.sender], numEther);
int256 payoutDiff;
if(bondType){
// Add the numTokens which were just created to the total supply. We're a crypto central bank!
totalBondSupply_BULL = add(totalBondSupply_BULL, numTokens);
// Assign the tokens to the balance of the buyer.
holdings_BULL[sender] = add(holdings_BULL[sender], numTokens);
// Update the payout array so that the buyer cannot claim dividends on previous purchases.
// Also include the fee paid for entering the scheme.
// First we compute how much was just paid out to the buyer...
payoutDiff = (int256) ((earningsPerBond_BULL * numTokens) - buyerFee);
}else{
totalBondSupply_BEAR = add(totalBondSupply_BEAR, numTokens);
holdings_BEAR[sender] = add(holdings_BEAR[sender], numTokens);
payoutDiff = (int256) ((earningsPerBond_BEAR * numTokens) - buyerFee);
}
// Then we update the payouts array for the buyer with this amount...
payouts[sender] = payouts[sender]+payoutDiff;
// And then we finally add it to the variable tracking the total amount spent to maintain invariance.
totalPayouts = totalPayouts+payoutDiff;
tricklingSum = add(tricklingSum,trickle);//add to trickle's Sum after reserve calculations
trickleUp();
if(bondType){
emit onTokenPurchase(sender,numEther,numTokens, reff[sender],true);
}else{
emit onTokenPurchase(sender,numEther,numTokens, reff[sender],false);
}
//#COLORBONUS
/*
souleculeCoreR1[msg.sender] += soulR * numTokens/255;
souleculeCoreG1[msg.sender] += soulG * numTokens/255;
souleculeCoreB1[msg.sender] += soulB * numTokens/255;
souleculeCoreR0[msg.sender] += numTokens-(soulR * numTokens/255);
souleculeCoreG0[msg.sender] += numTokens-(soulG * numTokens/255);
souleculeCoreB0[msg.sender] += numTokens-(soulB * numTokens/255);
souleculeEdgeR1[msg.sender] += soulR * numEther/255;
souleculeEdgeG1[msg.sender] += soulG * numEther/255;
souleculeEdgeB1[msg.sender] += soulB * numEther/255;
souleculeEdgeR0[msg.sender] += numTokens-(soulR * numEther/255);
souleculeEdgeG0[msg.sender] += numTokens-(soulG * numEther/255);
souleculeEdgeB0[msg.sender] += numTokens-(soulB * numEther/255);*/
}
// Sell function that takes tokens and converts them into Ether. Also comes with a 10% fee
// to discouraging dumping, and means that if someone near the top sells, the fee distributed
// will be *significant*.
function sell(uint256 amount,bool bondType) internal {
var numEthersBeforeFee = getEtherForTokens(amount);
// x% of the resulting Ether is used to pay remaining holders.
uint256 fee = 0;
uint256 trickle = 0;
if(totalBondSupply_BEAR != holdings_BEAR[msg.sender]){
fee = fluxFeed(numEthersBeforeFee, true);
trickle = div(fee, trickTax);
fee = sub(fee , trickle);
trickling[msg.sender] = add(trickling[msg.sender],trickle);
tricklingSum = add(tricklingSum , trickle);
}
// Net Ether for the seller after the fee has been subtracted.
var numEthers = sub(numEthersBeforeFee , add(fee , trickle));
//How much you bought it for divided by how much you're getting back.
//This means that if you get dumped on, you can get more resolve tokens if you sell out.
uint256 resolved = mint(
calcResolve(msg.sender,amount,numEthers),
msg.sender
);
//#COLORBONUS
/*
souleculeCoreR1[msg.sender] = mul( souleculeCoreR1[msg.sender] ,sub(holdingsOf(msg.sender), amount) ) / holdingsOf(msg.sender);
souleculeCoreG1[msg.sender] = mul( souleculeCoreG1[msg.sender] ,sub(holdingsOf(msg.sender), amount) ) / holdingsOf(msg.sender);
souleculeCoreB1[msg.sender] = mul( souleculeCoreB1[msg.sender] ,sub(holdingsOf(msg.sender), amount) ) / holdingsOf(msg.sender);
souleculeCoreR0[msg.sender] = mul( souleculeCoreR0[msg.sender] ,sub(holdingsOf(msg.sender), amount) ) / holdingsOf(msg.sender);
souleculeCoreG0[msg.sender] = mul( souleculeCoreG0[msg.sender] ,sub(holdingsOf(msg.sender), amount) ) / holdingsOf(msg.sender);
souleculeCoreB0[msg.sender] = mul( souleculeCoreB0[msg.sender] ,sub(holdingsOf(msg.sender), amount) ) / holdingsOf(msg.sender);
souleculeEdgeR1[msg.sender] -= edgePigmentR() * amount/255;
souleculeEdgeG1[msg.sender] -= edgePigmentG() * amount/255;
souleculeEdgeB1[msg.sender] -= edgePigmentB() * amount/255;
souleculeEdgeR0[msg.sender] -= amount-(edgePigmentR() * amount/255);
souleculeEdgeG0[msg.sender] -= amount-(edgePigmentG() * amount/255);
souleculeEdgeB0[msg.sender] -= amount-(edgePigmentB() * amount/255);*/
// *Remove* the numTokens which were just sold from the total supply. We're /definitely/ a crypto central bank.
int256 payoutDiff;
if(bondType){
totalBondSupply_BULL = sub(totalBondSupply_BULL, amount);
avgFactor_ethSpent[msg.sender] = mul( avgFactor_ethSpent[msg.sender] ,sub(holdings_BULL[msg.sender], amount) ) / holdings_BULL[msg.sender];
// Remove the tokens from the balance of the buyer.
holdings_BULL[msg.sender] = sub(holdings_BULL[msg.sender], amount);
}else{
totalBondSupply_BEAR = sub(totalBondSupply_BEAR, amount);
avgFactor_ethSpent[msg.sender] = mul( avgFactor_ethSpent[msg.sender] ,sub(holdings_BEAR[msg.sender], amount) ) / holdings_BEAR[msg.sender];
// Remove the tokens from the balance of the buyer.
holdings_BEAR[msg.sender] = sub(holdings_BEAR[msg.sender], amount);
}
fullCycleSellBonds(numEthers);
// Check that we have tokens in existence (this is a bit of an irrelevant check since we're
// selling tokens, but it guards against division by zero).
if (totalBondSupply_BEAR > 0) {
// Scale the Ether taken as the selling fee by the scaleFactor variable.
var etherFee = mul(fee , scaleFactor);
// Fee is distributed to all remaining token holders.
// rewardPerShare is the amount gained per token thanks to this sell.
var rewardPerShare = div(etherFee , totalBondSupply_BEAR);
// The Ether value per token is increased proportionally.
earningsPerBond_BEAR = add(earningsPerBond_BEAR, rewardPerShare);
}
trickleUp();
emit onTokenSell(msg.sender,add(add(holdings_BULL[msg.sender],holdings_BEAR[msg.sender]),amount),amount,numEthers,bondType,resolved);
}
// Converts the Ether accrued as dividends back into Staking tokens without having to
// withdraw it first. Saves on gas and potential price spike loss.
function reinvest(bool bondType/*, uint256 soulR,uint256 soulG,uint256 soulB*/) internal {
// Retrieve the dividends associated with the address the request came from.
var balance = dividends(msg.sender);
balance = add(balance,tricklePocket[msg.sender]);
tricklingSum = sub(tricklingSum,tricklePocket[msg.sender]);
tricklePocket[msg.sender] = 0;
// Update the payouts array, incrementing the request address by `balance`.
// Since this is essentially a shortcut to withdrawing and reinvesting, this step still holds.
payouts[msg.sender] += (int256) (balance * scaleFactor);
// Increase the total amount that's been paid out to maintain invariance.
totalPayouts += (int256) (balance * scaleFactor);
// Assign balance to a new variable.
uint value_ = (uint) (balance);
// If your dividends are worth less than 1 szabo, or more than a million Ether
// (in which case, why are you even here), abort.
if (value_ < 0.000001 ether || value_ > 1000000 ether)
revert();
// msg.sender is the address of the caller.
//var sender = msg.sender;
uint256 fee = 0;
uint256 trickle = 0;
if(holdings_BULL[msg.sender] != totalBondSupply_BULL){
fee = fluxFeed(value_, true ); // reinvestment fees are lower than regular ones.
trickle = div(fee, trickTax);
fee = sub(fee , trickle);
trickling[msg.sender] += trickle;
}
var res = sub(reserve() , balance);
// The amount of Ether used to purchase new tokens for the caller.
var numEther = value_ - fee;
// The number of tokens which can be purchased for numEther.
var numTokens = calculateDividendTokens(numEther, balance);
// The buyer fee, scaled by the scaleFactor variable.
var buyerFee = fee * scaleFactor;
// Check that we have tokens in existence (this should always be true), or
// else you're gonna have a bad time.
if (totalBondSupply_BULL > 0) {
uint256 bonusCoEff;
if(bondType){
// Compute the bonus co-efficient for all existing holders and the buyer.
// The buyer receives part of the distribution for each token bought in the
// same way they would have if they bought each token individually.
bonusCoEff = (scaleFactor - (res + numEther ) * numTokens * scaleFactor / (totalBondSupply_BULL + totalBondSupply_BEAR + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n);
}else{
bonusCoEff = scaleFactor;
}
// The total reward to be distributed amongst the masses is the fee (in Ether)
// multiplied by the bonus co-efficient.
buyerFee -= fee * bonusCoEff;
// Fee is distributed to all existing token holders before the new tokens are purchased.
// rewardPerShare is the amount gained per token thanks to this buy-in.
// The Ether value per token is increased proportionally.
earningsPerBond_BULL += fee * bonusCoEff / totalBondSupply_BULL;
}
//resolve reward tracking stuff
avgFactor_ethSpent[msg.sender] = add(avgFactor_ethSpent[msg.sender], numEther);
int256 payoutDiff;
if(bondType){
// Add the numTokens which were just created to the total supply. We're a crypto central bank!
totalBondSupply_BULL = add(totalBondSupply_BULL, numTokens);
// Assign the tokens to the balance of the buyer.
holdings_BULL[msg.sender] = add(holdings_BULL[msg.sender], numTokens);
// Update the payout array so that the buyer cannot claim dividends on previous purchases.
// Also include the fee paid for entering the scheme.
// First we compute how much was just paid out to the buyer...
payoutDiff = (int256) ((earningsPerBond_BULL * numTokens) - buyerFee);
}else{
totalBondSupply_BEAR = add(totalBondSupply_BEAR, numTokens);
holdings_BEAR[msg.sender] = add(holdings_BEAR[msg.sender], numTokens);
payoutDiff = (int256) ((earningsPerBond_BEAR * numTokens) - buyerFee);
}
/*var averageCostPerToken = div(numTokens , numEther);
var newTokenSum = add(holdings_BULL[sender], numTokens);
var totalSpentBefore = mul(averageBuyInPrice[sender], holdingsOf(sender) );*/
//averageBuyInPrice[sender] = div( totalSpentBefore + mul( averageCostPerToken , numTokens), newTokenSum ) ;
// Then we update the payouts array for the buyer with this amount...
payouts[msg.sender] += payoutDiff;
// And then we finally add it to the variable tracking the total amount spent to maintain invariance.
totalPayouts += payoutDiff;
tricklingSum += trickle;//add to trickle's Sum after reserve calculations
trickleUp();
if(bondType){
emit onReinvestment(msg.sender,numEther,numTokens,true);
}else{
emit onReinvestment(msg.sender,numEther,numTokens,false);
}
//#COLORBONUS
/*
souleculeCoreR1[msg.sender] += soulR * numTokens/255;
souleculeCoreG1[msg.sender] += soulG * numTokens/255;
souleculeCoreB1[msg.sender] += soulB * numTokens/255;
souleculeCoreR0[msg.sender] += numTokens-(soulR * numTokens/255);
souleculeCoreG0[msg.sender] += numTokens-(soulG * numTokens/255);
souleculeCoreB0[msg.sender] += numTokens-(soulB * numTokens/255);
souleculeEdgeR1[msg.sender] += soulR * numEther/255;
souleculeEdgeG1[msg.sender] += soulG * numEther/255;
souleculeEdgeB1[msg.sender] += soulB * numEther/255;
souleculeEdgeR0[msg.sender] += numTokens-(soulR * numEther/255);
souleculeEdgeG0[msg.sender] += numTokens-(soulG * numEther/255);
souleculeEdgeB0[msg.sender] += numTokens-(soulB * numEther/255);*/
}
// Dynamic value of Ether in reserve, according to the CRR requirement.
function reserve() internal constant returns (uint256 amount){
return sub(balance(),
((uint256) ((int256) (earningsPerBond_BULL * totalBondSupply_BULL + earningsPerBond_BEAR * totalBondSupply_BEAR) - totalPayouts ) / scaleFactor)
);
}
// Calculates the number of tokens that can be bought for a given amount of Ether, according to the
// dynamic reserve and totalSupply values (derived from the buy and sell prices).
function getTokensForEther(uint256 ethervalue) public constant returns (uint256 tokens) {
return sub(fixedExp(fixedLog(reserve() + ethervalue)*crr_n/crr_d + price_coeff), totalBondSupply_BULL + totalBondSupply_BEAR);
}
// Semantically similar to getTokensForEther, but subtracts the callers balance from the amount of Ether returned for conversion.
function calculateDividendTokens(uint256 ethervalue, uint256 subvalue) public constant returns (uint256 tokens) {
return sub(fixedExp(fixedLog(reserve() - subvalue + ethervalue)*crr_n/crr_d + price_coeff), totalBondSupply_BULL + totalBondSupply_BEAR);
}
// Converts a number tokens into an Ether value.
function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) {
// How much reserve Ether do we have left in the contract?
var reserveAmount = reserve();
// If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault.
if (tokens == (totalBondSupply_BULL + totalBondSupply_BEAR) )
return reserveAmount;
// If there would be excess Ether left after the transaction this is called within, return the Ether
// corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found
// at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator
// and denominator altered to 1 and 2 respectively.
return sub(reserveAmount, fixedExp((fixedLog(totalBondSupply_BULL + totalBondSupply_BEAR - tokens) - price_coeff) * crr_d/crr_n));
}
// You don't care about these, but if you really do they're hex values for
// co-efficients used to simulate approximations of the log and exp functions.
int256 constant one = 0x10000000000000000;
uint256 constant sqrt2 = 0x16a09e667f3bcc908;
uint256 constant sqrtdot5 = 0x0b504f333f9de6484;
int256 constant ln2 = 0x0b17217f7d1cf79ac;
int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8;
int256 constant c1 = 0x1ffffffffff9dac9b;
int256 constant c3 = 0x0aaaaaaac16877908;
int256 constant c5 = 0x0666664e5e9fa0c99;
int256 constant c7 = 0x049254026a7630acf;
int256 constant c9 = 0x038bd75ed37753d68;
int256 constant c11 = 0x03284a0c14610924f;
// The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11
// approximates the function log(1+x)-log(1-x)
// Hence R(s) = log((1+s)/(1-s)) = log(a)
function fixedLog(uint256 a) internal pure returns (int256 log) {
int32 scale = 0;
while (a > sqrt2) {
a /= 2;
scale++;
}
while (a <= sqrtdot5) {
a *= 2;
scale--;
}
int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one);
var z = (s*s) / one;
return scale * ln2 +
(s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one))
/one))/one))/one))/one))/one);
}
int256 constant c2 = 0x02aaaaaaaaa015db0;
int256 constant c4 = -0x000b60b60808399d1;
int256 constant c6 = 0x0000455956bccdd06;
int256 constant c8 = -0x000001b893ad04b3a;
// The polynomial R = 2 + c2*x^2 + c4*x^4 + ...
// approximates the function x*(exp(x)+1)/(exp(x)-1)
// Hence exp(x) = (R(x)+x)/(R(x)-x)
function fixedExp(int256 a) internal pure returns (uint256 exp) {
int256 scale = (a + (ln2_64dot5)) / ln2 - 64;
a -= scale*ln2;
int256 z = (a*a) / one;
int256 R = ((int256)(2) * one) +
(z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one);
exp = (uint256) (((R + a) * one) / (R - a));
if (scale >= 0)
exp <<= scale;
else
exp >>= -scale;
return exp;
}
// The below are safemath implementations of the four arithmetic operators
// designed to explicitly prevent over- and under-flows of integer values.
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function () payable public {
if (msg.value > 0) {
fund(lastGateway,true);
} else {
withdrawOld(msg.sender);
}
}
uint256 public totalSupply;
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
string public name = "0xBabylon";
uint8 public decimals = 12;
string public symbol = "PoWHr";
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Resolved(address indexed _owner, uint256 amount);
event Burned(address indexed _owner, uint256 amount);
function mint(uint256 amount,address _account) internal returns (uint minted){
totalSupply += amount;
balances[_account] += amount;
Resolved(_account,amount);
return amount;
}
function burn(uint256 _value) public returns (uint256 amount) {
require(balances[msg.sender] >= _value);
totalSupply -= _value;
balances[msg.sender] -= _value;
Resolved(msg.sender,_value);
return _value;
}
function calcResolve(address _owner,uint256 amount,uint256 _eth) public constant returns (uint256 calculatedResolveTokens) {
return div(div(div(mul(mul(amount,amount),avgFactor_ethSpent[_owner]),holdings_BULL[_owner]+holdings_BEAR[_owner]),_eth),1000000);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function resolveSupply(address _owner) public view returns (uint256 balance) {
return totalSupply;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
|
Converts a number tokens into an Ether value. How much reserve Ether do we have left in the contract? If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault. If there would be excess Ether left after the transaction this is called within, return the Ether corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found at https:test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator and denominator altered to 1 and 2 respectively.
|
function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) {
var reserveAmount = reserve();
if (tokens == (totalBondSupply_BULL + totalBondSupply_BEAR) )
return reserveAmount;
return sub(reserveAmount, fixedExp((fixedLog(totalBondSupply_BULL + totalBondSupply_BEAR - tokens) - price_coeff) * crr_d/crr_n));
}
| 905,656 |
./full_match/137/0x1e3fCa63502a7AaA6841788301Eae4AC67CF691D/sources/scripts/Learning_Projects/CheeseTouch.sol
|
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, "CheeseTouch: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
| 4,755,550 |
./full_match/1/0x18d9244DC85306DBc0AAE16cF8FAE9aEFAee7530/sources/ForbitswapRouter.sol
|
SWAP requires the initial amount to have already been sent to the first pair
|
function _swap(
uint256[] memory amounts,
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = ForbitswapLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < path.length - 2 ? ForbitswapLibrary.pairFor(factory, output, path[i + 2]) : _to;
IForbitswapPair(ForbitswapLibrary.pairFor(factory, input, output)).swap(
amount0Out,
amount1Out,
to,
new bytes(0)
);
}
}
| 9,783,515 |
pragma solidity ^0.4.21;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title 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 Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
Transfer(burner, address(0), _value);
}
}
contract StandardToken is ERC20, BurnableToken {
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 available for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will recieve the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract SUCoin is MintableToken {
string public constant name = "SU Coin";
string public constant symbol = "SUCoin";
uint32 public constant decimals = 18;
}
contract SUTokenContract is Ownable {
using SafeMath for uint;
SUCoin public token = new SUCoin();
bool ifInit = false;
uint public tokenDec = 1000000000000000000; //18
address manager;
//uint public lastPeriod;
mapping (address => mapping (uint => bool)) idMap;
//mapping (address => mapping (bytes32 => bool)) hashMap;
//mapping(uint => bool) idMap;
mapping(bytes32 => bool) hashMap;
mapping (uint => uint) mintInPeriod;
uint public mintLimit = tokenDec.mul(10000);
uint public period = 30 * 1 days; // 30 дней
uint public startTime = now;
function SUTokenContract(){
owner = msg.sender;
manager = msg.sender;
}
function initMinting() onlyOwner returns (bool) {
require(!ifInit);
require(token.mint(0x8f89FE2362C769B472F0e9496F5Ca86850BeE8D4, tokenDec.mul(50000)));
require(token.mint(address(this), tokenDec.mul(50000)));
ifInit = true;
return true;
}
// Данная функция на тестовый период. Позволяет передать токен на новый контракт
function transferTokenOwnership(address _newOwner) onlyOwner {
token.transferOwnership(_newOwner);
}
function mint(address _to, uint _value) onlyOwner {
uint currPeriod = now.sub(startTime).div(period);
require(mintLimit>= _value.add(mintInPeriod[currPeriod]));
require(token.mint(_to, _value));
mintInPeriod[currPeriod] = mintInPeriod[currPeriod].add(_value);
}
function burn(uint256 _value) onlyOwner {
token.burn(_value);
}
function tokenTotalSupply() constant returns (uint256) {
return token.totalSupply();
}
//Баланс токенов на данном контракте
function tokenContractBalance() constant returns (uint256) {
return token.balanceOf(address(this));
}
function tokentBalance(address _address) constant returns (uint256) {
return token.balanceOf(_address);
}
function transferToken(address _to, uint _value) onlyOwner returns (bool) {
return token.transfer(_to, _value);
}
function allowance( address _spender) constant returns (uint256 remaining) {
return token.allowance(address(this),_spender);
}
function allowanceAdd( address _spender, uint _value ) onlyOwner returns (bool) {
uint currAllowance = allowance( _spender);
require(token.approve( _spender, 0));
require(token.approve( _spender, currAllowance.add(_value)));
return true;
}
function allowanceSub( address _spender, uint _value ) onlyOwner returns (bool) {
uint currAllowance = allowance( _spender);
require(currAllowance>=_value);
require(token.approve( _spender, 0));
require(token.approve( _spender, currAllowance.sub(_value)));
return true;
}
function allowanceSubId( address _spender, uint _value, uint _id) onlyOwner returns (bool) {
uint currAllowance = allowance( _spender);
require(currAllowance>=_value);
require(token.approve( _spender, 0));
require(token.approve( _spender, currAllowance.sub(_value)));
idMap[_spender][_id] = true;
return true;
}
function storeId(address _address, uint _id) onlyOwner {
idMap[_address][_id] = true;
}
function storeHash(bytes32 _hash) onlyOwner {
hashMap[_hash] = true;
}
function idVerification(address _address, uint _id) constant returns (bool) {
return idMap[_address][_id];
}
function hashVerification(bytes32 _hash) constant returns (bool) {
return hashMap[_hash];
}
function mintInPeriodCount(uint _period) constant returns (uint) {
return mintInPeriod[_period];
}
function mintInCurrPeriodCount() constant returns (uint) {
uint currPeriod = now.sub(startTime).div(period);
return mintInPeriod[currPeriod];
}
}
|
Баланс токенов на данном контракте
|
function tokenContractBalance() constant returns (uint256) {
return token.balanceOf(address(this));
}
| 7,963,638 |
./partial_match/3/0x2C02cD8a2645D97977E7ffE74Ed21a943ba465E0/sources/pool.sol
|
net-withdraw amount;/ sum total collateral in USDT count collateral at issue time
|
function NWA() public view returns (uint) {
uint totalCollateral;
for (uint i = 0;i< _options.length;i++) {
totalCollateral = totalCollateral.add(_options[i].totalSupply() * _options[i].strikePrice());
}
if (minCollateral <= usdtsToIssue) {
return 0;
}
}
| 5,241,300 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
/* solhint-disable not-rely-on-time */
import { console } from "hardhat/console.sol";
/// @notice Errors library.
library Errors {
string internal constant _BodyEmpty = "Message body can't be empty";
string internal constant _NotOwner = "Caller isn't the owner";
string internal constant _DoesNotExist = "Message doesn't exist";
}
/// @title Messages
/// @author Philipp Muens
/// @notice Contract which stores messages.
contract Messages {
/// @notice Structure which stores a message's details.
struct Message {
uint256 id;
string body;
address owner;
uint256 createdAt;
uint256 updatedAt;
bool isEntity;
}
/// @notice Counter for the next message id.
uint256 public nextId;
/// @notice Maps a message's id to its struct.
mapping(uint256 => Message) public messages;
/// @notice Emitted when a message is created.
/// @param id The message's id.
/// @param owner The message's owner.
/// @param body The message's body.
/// @param createdAt The time when the message was created.
event CreateMessage(uint256 indexed id, address indexed owner, string body, uint256 createdAt);
/// @notice Emitted when a message is updated.
/// @param id The message's id.
/// @param owner The message's owner.
/// @param body The message's body.
/// @param updatedAt The time when the message was updated.
event UpdateMessage(uint256 indexed id, address indexed owner, string body, uint256 updatedAt);
/// @notice Emitted when a message is removed.
/// @param id The message's id.
/// @param owner The message's owner.
/// @param body The message's body.
/// @param removedAt The time when the message was removed.
event RemoveMessage(uint256 indexed id, address indexed owner, string body, uint256 removedAt);
/// @notice Checks if the caller is the owner of the message.
/// @dev Throws when the caller is not the owner of the message.
/// @param id The message's id.
modifier onlyOwner(uint256 id) {
require(msg.sender == messages[id].owner, Errors._NotOwner);
_;
}
/// @notice Checks if a message with the given id exists.
/// @dev Throws when the message doesn't exist.
/// @param id The message's id.
modifier messageExists(uint256 id) {
require(messages[id].isEntity, Errors._DoesNotExist);
_;
}
/// @notice Creates a new message.
/// @dev Logs debugging information.
/// Emits an event.
/// The owner of the new message is the caller.
/// Throws when the body is empty.
/// @param body The message's body.
/// @return The message's id.
function createMessage(string calldata body) external returns (uint256) {
require(bytes(body).length > 0, Errors._BodyEmpty);
uint256 id = nextId;
nextId++;
Message memory message = Message({
id: id,
body: body,
owner: msg.sender,
createdAt: block.timestamp,
updatedAt: block.timestamp,
isEntity: true
});
messages[id] = message;
emit CreateMessage(id, msg.sender, body, block.timestamp);
console.log("%s created a new message with id %s.", msg.sender, id);
return id;
}
/// @notice Updates an existing message.
/// @dev Logs debugging information.
/// Emits an event.
/// Throws when the message doesn't exist.
/// Throws when the caller is not the owner.
/// Throws when the body is empty.
/// @param id The message's id.
/// @param body The message's body.
/// @return A boolean which indicates whether the update was successful.
function updateMessage(uint256 id, string calldata body) external messageExists(id) onlyOwner(id) returns (bool) {
require(bytes(body).length > 0, Errors._BodyEmpty);
messages[id].body = body;
messages[id].updatedAt = block.timestamp;
emit UpdateMessage(id, msg.sender, body, block.timestamp);
console.log("%s updated the message with id %s.", msg.sender, id);
return true;
}
/// @notice Removes an existing message.
/// @dev Logs debugging information.
/// Emits an event.
/// Throws when the message doesn't exist.
/// Throws when the caller is not the owner.
/// @param id The message's id.
/// @return A boolean which indicates whether the removal was successful.
function removeMessage(uint256 id) external messageExists(id) onlyOwner(id) returns (bool) {
string memory body = messages[id].body;
delete messages[id];
emit RemoveMessage(id, msg.sender, body, block.timestamp);
console.log("%s removed the message with id %s.", msg.sender, id);
return true;
}
/// @notice Returns the message with the corresponding id.
/// @dev Logs debugging information.
/// Throws when the message doesn't exists.
/// @param id The message's id.
/// @return The message's struct fields.
function getMessage(uint256 id)
external
view
messageExists(id)
returns (
uint256,
string memory,
address,
uint256,
uint256,
bool
)
{
console.log("Loading message with id %s.", id);
return (
messages[id].id,
messages[id].body,
messages[id].owner,
messages[id].createdAt,
messages[id].updatedAt,
messages[id].isEntity
);
}
}
|
Returns the message with the corresponding id. Logs debugging information. Throws when the message doesn't exists. id The message's id. return The message's struct fields.
|
function getMessage(uint256 id)
external
view
messageExists(id)
returns (
uint256,
string memory,
address,
uint256,
uint256,
bool
)
{
console.log("Loading message with id %s.", id);
return (
messages[id].id,
messages[id].body,
messages[id].owner,
messages[id].createdAt,
messages[id].updatedAt,
messages[id].isEntity
);
}
| 12,844,889 |
./full_match/42/0xe3A431745a39502E7272329119BE93Ce1e0eac8d/sources/contracts/AaveNFTAuction.sol
|
This private function, only called once in "InitializeShards," initiates auctions for all shards./
|
function setupAuctions(uint256 _startTimestamp, uint256 _duration, uint256 _startPrice) private {
uint256 _endTimestamp = _startTimestamp.add(_duration);
for (uint256 i = 0; i < totalShards; i++) {
auctions[i] = Auction(_startTimestamp, _endTimestamp, _startPrice, 0, 0, address(0), i);
}
}
| 9,576,954 |
./partial_match/1/0x8408BaCcc231a6BbA766ed15571403468b32bFA5/sources/NowPass.sol
|
Sets the state of whether the collection metadata is revealed
|
function setRevealed(bool _state) public onlyOwner
{
require(revealed == false, "Cannot be unrevealed");
revealed = _state;
}
| 9,340,479 |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
// Sources flattened with hardhat v2.6.7 https://hardhat.org
// File contracts/Math/SafeMath.sol
/**
* @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 contracts/FXS/IFxs.sol
interface IFxs {
function DEFAULT_ADMIN_ROLE() external view returns(bytes32);
function FRAXStablecoinAdd() external view returns(address);
function FXS_DAO_min() external view returns(uint256);
function allowance(address owner, address spender) external view returns(uint256);
function approve(address spender, uint256 amount) external returns(bool);
function balanceOf(address account) external view returns(uint256);
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
function checkpoints(address, uint32) external view returns(uint32 fromBlock, uint96 votes);
function decimals() external view returns(uint8);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns(bool);
function genesis_supply() external view returns(uint256);
function getCurrentVotes(address account) external view returns(uint96);
function getPriorVotes(address account, uint256 blockNumber) external view returns(uint96);
function getRoleAdmin(bytes32 role) external view returns(bytes32);
function getRoleMember(bytes32 role, uint256 index) external view returns(address);
function getRoleMemberCount(bytes32 role) external view returns(uint256);
function grantRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account) external view returns(bool);
function increaseAllowance(address spender, uint256 addedValue) external returns(bool);
function mint(address to, uint256 amount) external;
function name() external view returns(string memory);
function numCheckpoints(address) external view returns(uint32);
function oracle_address() external view returns(address);
function owner_address() external view returns(address);
function pool_burn_from(address b_address, uint256 b_amount) external;
function pool_mint(address m_address, uint256 m_amount) external;
function renounceRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function setFRAXAddress(address frax_contract_address) external;
function setFXSMinDAO(uint256 min_FXS) external;
function setOracle(address new_oracle) external;
function setOwner(address _owner_address) external;
function setTimelock(address new_timelock) external;
function symbol() external view returns(string memory);
function timelock_address() external view returns(address);
function toggleVotes() external;
function totalSupply() external view returns(uint256);
function trackingVotes() external view returns(bool);
function transfer(address recipient, uint256 amount) external returns(bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns(bool);
}
// File contracts/Common/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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 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;
}
}
// File contracts/ERC20/IERC20.sol
/**
* @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 contracts/Utils/Address.sol
/**
* @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 contracts/ERC20/ERC20.sol
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {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) 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.approve(address spender, uint256 amount)
*/
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 the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for `accounts`'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal 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 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 virtual {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
/**
* @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:using-hooks.adoc[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File contracts/Frax/IFrax.sol
interface IFrax {
function COLLATERAL_RATIO_PAUSER() external view returns (bytes32);
function DEFAULT_ADMIN_ADDRESS() external view returns (address);
function DEFAULT_ADMIN_ROLE() external view returns (bytes32);
function addPool(address pool_address ) external;
function allowance(address owner, address spender ) external view returns (uint256);
function approve(address spender, uint256 amount ) external returns (bool);
function balanceOf(address account ) external view returns (uint256);
function burn(uint256 amount ) external;
function burnFrom(address account, uint256 amount ) external;
function collateral_ratio_paused() external view returns (bool);
function controller_address() external view returns (address);
function creator_address() external view returns (address);
function decimals() external view returns (uint8);
function decreaseAllowance(address spender, uint256 subtractedValue ) external returns (bool);
function eth_usd_consumer_address() external view returns (address);
function eth_usd_price() external view returns (uint256);
function frax_eth_oracle_address() external view returns (address);
function frax_info() external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256);
function frax_pools(address ) external view returns (bool);
function frax_pools_array(uint256 ) external view returns (address);
function frax_price() external view returns (uint256);
function frax_step() external view returns (uint256);
function fxs_address() external view returns (address);
function fxs_eth_oracle_address() external view returns (address);
function fxs_price() external view returns (uint256);
function genesis_supply() external view returns (uint256);
function getRoleAdmin(bytes32 role ) external view returns (bytes32);
function getRoleMember(bytes32 role, uint256 index ) external view returns (address);
function getRoleMemberCount(bytes32 role ) external view returns (uint256);
function globalCollateralValue() external view returns (uint256);
function global_collateral_ratio() external view returns (uint256);
function grantRole(bytes32 role, address account ) external;
function hasRole(bytes32 role, address account ) external view returns (bool);
function increaseAllowance(address spender, uint256 addedValue ) external returns (bool);
function last_call_time() external view returns (uint256);
function minting_fee() external view returns (uint256);
function name() external view returns (string memory);
function owner_address() external view returns (address);
function pool_burn_from(address b_address, uint256 b_amount ) external;
function pool_mint(address m_address, uint256 m_amount ) external;
function price_band() external view returns (uint256);
function price_target() external view returns (uint256);
function redemption_fee() external view returns (uint256);
function refreshCollateralRatio() external;
function refresh_cooldown() external view returns (uint256);
function removePool(address pool_address ) external;
function renounceRole(bytes32 role, address account ) external;
function revokeRole(bytes32 role, address account ) external;
function setController(address _controller_address ) external;
function setETHUSDOracle(address _eth_usd_consumer_address ) external;
function setFRAXEthOracle(address _frax_oracle_addr, address _weth_address ) external;
function setFXSAddress(address _fxs_address ) external;
function setFXSEthOracle(address _fxs_oracle_addr, address _weth_address ) external;
function setFraxStep(uint256 _new_step ) external;
function setMintingFee(uint256 min_fee ) external;
function setOwner(address _owner_address ) external;
function setPriceBand(uint256 _price_band ) external;
function setPriceTarget(uint256 _new_price_target ) external;
function setRedemptionFee(uint256 red_fee ) external;
function setRefreshCooldown(uint256 _new_cooldown ) external;
function setTimelock(address new_timelock ) external;
function symbol() external view returns (string memory);
function timelock_address() external view returns (address);
function toggleCollateralRatio() external;
function totalSupply() external view returns (uint256);
function transfer(address recipient, uint256 amount ) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount ) external returns (bool);
function weth_address() external view returns (address);
}
// File contracts/Frax/IFraxAMOMinter.sol
// MAY need to be updated
interface IFraxAMOMinter {
function FRAX() external view returns(address);
function FXS() external view returns(address);
function acceptOwnership() external;
function addAMO(address amo_address, bool sync_too) external;
function allAMOAddresses() external view returns(address[] memory);
function allAMOsLength() external view returns(uint256);
function amos(address) external view returns(bool);
function amos_array(uint256) external view returns(address);
function burnFraxFromAMO(uint256 frax_amount) external;
function burnFxsFromAMO(uint256 fxs_amount) external;
function col_idx() external view returns(uint256);
function collatDollarBalance() external view returns(uint256);
function collatDollarBalanceStored() external view returns(uint256);
function collat_borrow_cap() external view returns(int256);
function collat_borrowed_balances(address) external view returns(int256);
function collat_borrowed_sum() external view returns(int256);
function collateral_address() external view returns(address);
function collateral_token() external view returns(address);
function correction_offsets_amos(address, uint256) external view returns(int256);
function custodian_address() external view returns(address);
function dollarBalances() external view returns(uint256 frax_val_e18, uint256 collat_val_e18);
// function execute(address _to, uint256 _value, bytes _data) external returns(bool, bytes);
function fraxDollarBalanceStored() external view returns(uint256);
function fraxTrackedAMO(address amo_address) external view returns(int256);
function fraxTrackedGlobal() external view returns(int256);
function frax_mint_balances(address) external view returns(int256);
function frax_mint_cap() external view returns(int256);
function frax_mint_sum() external view returns(int256);
function fxs_mint_balances(address) external view returns(int256);
function fxs_mint_cap() external view returns(int256);
function fxs_mint_sum() external view returns(int256);
function giveCollatToAMO(address destination_amo, uint256 collat_amount) external;
function min_cr() external view returns(uint256);
function mintFraxForAMO(address destination_amo, uint256 frax_amount) external;
function mintFxsForAMO(address destination_amo, uint256 fxs_amount) external;
function missing_decimals() external view returns(uint256);
function nominateNewOwner(address _owner) external;
function nominatedOwner() external view returns(address);
function oldPoolCollectAndGive(address destination_amo) external;
function oldPoolRedeem(uint256 frax_amount) external;
function old_pool() external view returns(address);
function owner() external view returns(address);
function pool() external view returns(address);
function receiveCollatFromAMO(uint256 usdc_amount) external;
function recoverERC20(address tokenAddress, uint256 tokenAmount) external;
function removeAMO(address amo_address, bool sync_too) external;
function setAMOCorrectionOffsets(address amo_address, int256 frax_e18_correction, int256 collat_e18_correction) external;
function setCollatBorrowCap(uint256 _collat_borrow_cap) external;
function setCustodian(address _custodian_address) external;
function setFraxMintCap(uint256 _frax_mint_cap) external;
function setFraxPool(address _pool_address) external;
function setFxsMintCap(uint256 _fxs_mint_cap) external;
function setMinimumCollateralRatio(uint256 _min_cr) external;
function setTimelock(address new_timelock) external;
function syncDollarBalances() external;
function timelock_address() external view returns(address);
}
// File contracts/Uniswap/TransferHelper.sol
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File contracts/Staking/Owned.sol
// https://docs.synthetix.io/contracts/Owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor (address _owner) public {
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 {
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// File contracts/Oracle/AggregatorV3Interface.sol
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File contracts/Frax/Pools/FraxPoolV3.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ============================ FraxPoolV3 ============================
// ====================================================================
// Allows multiple stablecoins (fixed amount at initialization) as collateral
// LUSD, sUSD, USDP, Wrapped UST, and FEI initially
// For this pool, the goal is to accept crypto-backed / overcollateralized stablecoins to limit
// government / regulatory risk (e.g. USDC blacklisting until holders KYC)
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Dennis: github.com/denett
// Hameed
contract FraxPoolV3 is Owned {
using SafeMath for uint256;
// SafeMath automatically included in Solidity >= 8.0.0
/* ========== STATE VARIABLES ========== */
// Core
address public timelock_address;
address public custodian_address; // Custodian is an EOA (or msig) with pausing privileges only, in case of an emergency
IFrax private FRAX = IFrax(0x853d955aCEf822Db058eb8505911ED77F175b99e);
IFxs private FXS = IFxs(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0);
mapping(address => bool) public amo_minter_addresses; // minter address -> is it enabled
AggregatorV3Interface public priceFeedFRAXUSD = AggregatorV3Interface(0xB9E1E3A9feFf48998E45Fa90847ed4D467E8BcfD);
AggregatorV3Interface public priceFeedFXSUSD = AggregatorV3Interface(0x6Ebc52C8C1089be9eB3945C4350B68B8E4C2233f);
uint256 private chainlink_frax_usd_decimals;
uint256 private chainlink_fxs_usd_decimals;
// Collateral
address[] public collateral_addresses;
string[] public collateral_symbols;
uint256[] public missing_decimals; // Number of decimals needed to get to E18. collateral index -> missing_decimals
uint256[] public pool_ceilings; // Total across all collaterals. Accounts for missing_decimals
uint256[] public collateral_prices; // Stores price of the collateral, if price is paused
mapping(address => uint256) public collateralAddrToIdx; // collateral addr -> collateral index
mapping(address => bool) public enabled_collaterals; // collateral address -> is it enabled
// Redeem related
mapping (address => uint256) public redeemFXSBalances;
mapping (address => mapping(uint256 => uint256)) public redeemCollateralBalances; // Address -> collateral index -> balance
uint256[] public unclaimedPoolCollateral; // collateral index -> balance
uint256 public unclaimedPoolFXS;
mapping (address => uint256) public lastRedeemed; // Collateral independent
uint256 public redemption_delay = 2; // Number of blocks to wait before being able to collectRedemption()
uint256 public redeem_price_threshold = 990000; // $0.99
uint256 public mint_price_threshold = 1010000; // $1.01
// Buyback related
mapping(uint256 => uint256) public bbkHourlyCum; // Epoch hour -> Collat out in that hour (E18)
uint256 public bbkMaxColE18OutPerHour = 1000e18;
// Recollat related
mapping(uint256 => uint256) public rctHourlyCum; // Epoch hour -> FXS out in that hour
uint256 public rctMaxFxsOutPerHour = 1000e18;
// Fees and rates
// getters are in collateral_information()
uint256[] private minting_fee;
uint256[] private redemption_fee;
uint256[] private buyback_fee;
uint256[] private recollat_fee;
uint256 public bonus_rate; // Bonus rate on FXS minted during recollateralize(); 6 decimals of precision, set to 0.75% on genesis
// Constants for various precisions
uint256 private constant PRICE_PRECISION = 1e6;
// Pause variables
// getters are in collateral_information()
bool[] private mintPaused; // Collateral-specific
bool[] private redeemPaused; // Collateral-specific
bool[] private recollateralizePaused; // Collateral-specific
bool[] private buyBackPaused; // Collateral-specific
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock");
_;
}
modifier onlyByOwnGovCust() {
require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd");
_;
}
modifier onlyAMOMinters() {
require(amo_minter_addresses[msg.sender], "Not an AMO Minter");
_;
}
modifier collateralEnabled(uint256 col_idx) {
require(enabled_collaterals[collateral_addresses[col_idx]], "Collateral disabled");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor (
address _pool_manager_address,
address _custodian_address,
address _timelock_address,
address[] memory _collateral_addresses,
uint256[] memory _pool_ceilings,
uint256[] memory _initial_fees
) Owned(_pool_manager_address){
// Core
timelock_address = _timelock_address;
custodian_address = _custodian_address;
// Fill collateral info
collateral_addresses = _collateral_addresses;
for (uint256 i = 0; i < _collateral_addresses.length; i++){
// For fast collateral address -> collateral idx lookups later
collateralAddrToIdx[_collateral_addresses[i]] = i;
// Set all of the collaterals initially to disabled
enabled_collaterals[_collateral_addresses[i]] = false;
// Add in the missing decimals
missing_decimals.push(uint256(18).sub(ERC20(_collateral_addresses[i]).decimals()));
// Add in the collateral symbols
collateral_symbols.push(ERC20(_collateral_addresses[i]).symbol());
// Initialize unclaimed pool collateral
unclaimedPoolCollateral.push(0);
// Initialize paused prices to $1 as a backup
collateral_prices.push(PRICE_PRECISION);
// Handle the fees
minting_fee.push(_initial_fees[0]);
redemption_fee.push(_initial_fees[1]);
buyback_fee.push(_initial_fees[2]);
recollat_fee.push(_initial_fees[3]);
// Handle the pauses
mintPaused.push(false);
redeemPaused.push(false);
recollateralizePaused.push(false);
buyBackPaused.push(false);
}
// Pool ceiling
pool_ceilings = _pool_ceilings;
// Set the decimals
chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals();
chainlink_fxs_usd_decimals = priceFeedFXSUSD.decimals();
}
/* ========== STRUCTS ========== */
struct CollateralInformation {
uint256 index;
string symbol;
address col_addr;
bool is_enabled;
uint256 missing_decs;
uint256 price;
uint256 pool_ceiling;
bool mint_paused;
bool redeem_paused;
bool recollat_paused;
bool buyback_paused;
uint256 minting_fee;
uint256 redemption_fee;
uint256 buyback_fee;
uint256 recollat_fee;
}
/* ========== VIEWS ========== */
// Helpful for UIs
function collateral_information(address collat_address) external view returns (CollateralInformation memory return_data){
require(enabled_collaterals[collat_address], "Invalid collateral");
// Get the index
uint256 idx = collateralAddrToIdx[collat_address];
return_data = CollateralInformation(
idx, // [0]
collateral_symbols[idx], // [1]
collat_address, // [2]
enabled_collaterals[collat_address], // [3]
missing_decimals[idx], // [4]
collateral_prices[idx], // [5]
pool_ceilings[idx], // [6]
mintPaused[idx], // [7]
redeemPaused[idx], // [8]
recollateralizePaused[idx], // [9]
buyBackPaused[idx], // [10]
minting_fee[idx], // [11]
redemption_fee[idx], // [12]
buyback_fee[idx], // [13]
recollat_fee[idx] // [14]
);
}
function allCollaterals() external view returns (address[] memory) {
return collateral_addresses;
}
function getFRAXPrice() public view returns (uint256) {
( , int price, , , ) = priceFeedFRAXUSD.latestRoundData();
return uint256(price).mul(PRICE_PRECISION).div(10 ** chainlink_frax_usd_decimals);
}
function getFXSPrice() public view returns (uint256) {
( , int price, , , ) = priceFeedFXSUSD.latestRoundData();
return uint256(price).mul(PRICE_PRECISION).div(10 ** chainlink_fxs_usd_decimals);
}
// Returns the FRAX value in collateral tokens
function getFRAXInCollateral(uint256 col_idx, uint256 frax_amount) public view returns (uint256) {
return frax_amount.mul(PRICE_PRECISION).div(10 ** missing_decimals[col_idx]).div(collateral_prices[col_idx]);
}
// Used by some functions.
function freeCollatBalance(uint256 col_idx) public view returns (uint256) {
return ERC20(collateral_addresses[col_idx]).balanceOf(address(this)).sub(unclaimedPoolCollateral[col_idx]);
}
// Returns dollar value of collateral held in this Frax pool, in E18
function collatDollarBalance() external view returns (uint256 balance_tally) {
balance_tally = 0;
// Test 1
for (uint256 i = 0; i < collateral_addresses.length; i++){
balance_tally += freeCollatBalance(i).mul(10 ** missing_decimals[i]).mul(collateral_prices[i]).div(PRICE_PRECISION);
}
}
function comboCalcBbkRct(uint256 cur, uint256 max, uint256 theo) internal pure returns (uint256) {
if (cur >= max) {
// If the hourly limit has already been reached, return 0;
return 0;
}
else {
// Get the available amount
uint256 available = max.sub(cur);
if (theo >= available) {
// If the the theoretical is more than the available, return the available
return available;
}
else {
// Otherwise, return the theoretical amount
return theo;
}
}
}
// Returns the value of excess collateral (in E18) held globally, compared to what is needed to maintain the global collateral ratio
// Also has throttling to avoid dumps during large price movements
function buybackAvailableCollat() public view returns (uint256) {
uint256 total_supply = FRAX.totalSupply();
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 global_collat_value = FRAX.globalCollateralValue();
if (global_collateral_ratio > PRICE_PRECISION) global_collateral_ratio = PRICE_PRECISION; // Handles an overcollateralized contract with CR > 1
uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(PRICE_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio
if (global_collat_value > required_collat_dollar_value_d18) {
// Get the theoretical buyback amount
uint256 theoretical_bbk_amt = global_collat_value.sub(required_collat_dollar_value_d18);
// See how much has collateral has been issued this hour
uint256 current_hr_bbk = bbkHourlyCum[curEpochHr()];
// Account for the throttling
return comboCalcBbkRct(current_hr_bbk, bbkMaxColE18OutPerHour, theoretical_bbk_amt);
}
else return 0;
}
// Returns the missing amount of collateral (in E18) needed to maintain the collateral ratio
function recollatTheoColAvailableE18() public view returns (uint256) {
uint256 frax_total_supply = FRAX.totalSupply();
uint256 effective_collateral_ratio = FRAX.globalCollateralValue().mul(PRICE_PRECISION).div(frax_total_supply); // Returns it in 1e6
uint256 desired_collat_e24 = (FRAX.global_collateral_ratio()).mul(frax_total_supply);
uint256 effective_collat_e24 = effective_collateral_ratio.mul(frax_total_supply);
// Return 0 if already overcollateralized
// Otherwise, return the deficiency
if (effective_collat_e24 >= desired_collat_e24) return 0;
else {
return (desired_collat_e24.sub(effective_collat_e24)).div(PRICE_PRECISION);
}
}
// Returns the value of FXS available to be used for recollats
// Also has throttling to avoid dumps during large price movements
function recollatAvailableFxs() public view returns (uint256) {
uint256 fxs_price = getFXSPrice();
// Get the amount of collateral theoretically available
uint256 recollat_theo_available_e18 = recollatTheoColAvailableE18();
// Get the amount of FXS theoretically outputtable
uint256 fxs_theo_out = recollat_theo_available_e18.mul(PRICE_PRECISION).div(fxs_price);
// See how much FXS has been issued this hour
uint256 current_hr_rct = rctHourlyCum[curEpochHr()];
// Account for the throttling
return comboCalcBbkRct(current_hr_rct, rctMaxFxsOutPerHour, fxs_theo_out);
}
// Returns the current epoch hour
function curEpochHr() public view returns (uint256) {
return (block.timestamp / 3600); // Truncation desired
}
/* ========== PUBLIC FUNCTIONS ========== */
function mintFrax(
uint256 col_idx,
uint256 frax_amt,
uint256 frax_out_min,
bool one_to_one_override
) external collateralEnabled(col_idx) returns (
uint256 total_frax_mint,
uint256 collat_needed,
uint256 fxs_needed
) {
require(mintPaused[col_idx] == false, "Minting is paused");
// Prevent unneccessary mints
require(getFRAXPrice() >= mint_price_threshold, "Frax price too low");
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
if (one_to_one_override || global_collateral_ratio >= PRICE_PRECISION) {
// 1-to-1, overcollateralized, or user selects override
collat_needed = getFRAXInCollateral(col_idx, frax_amt);
fxs_needed = 0;
} else if (global_collateral_ratio == 0) {
// Algorithmic
collat_needed = 0;
fxs_needed = frax_amt.mul(PRICE_PRECISION).div(getFXSPrice());
} else {
// Fractional
uint256 frax_for_collat = frax_amt.mul(global_collateral_ratio).div(PRICE_PRECISION);
uint256 frax_for_fxs = frax_amt.sub(frax_for_collat);
collat_needed = getFRAXInCollateral(col_idx, frax_for_collat);
fxs_needed = frax_for_fxs.mul(PRICE_PRECISION).div(getFXSPrice());
}
// Subtract the minting fee
total_frax_mint = (frax_amt.mul(PRICE_PRECISION.sub(minting_fee[col_idx]))).div(PRICE_PRECISION);
// Checks
require((frax_out_min <= total_frax_mint), "FRAX slippage");
require(freeCollatBalance(col_idx).add(collat_needed) <= pool_ceilings[col_idx], "Pool ceiling");
// Take the FXS and collateral first
FXS.pool_burn_from(msg.sender, fxs_needed);
TransferHelper.safeTransferFrom(collateral_addresses[col_idx], msg.sender, address(this), collat_needed);
// Mint the FRAX
FRAX.pool_mint(msg.sender, total_frax_mint);
}
function redeemFrax(
uint256 col_idx,
uint256 frax_amount,
uint256 fxs_out_min,
uint256 col_out_min
) external collateralEnabled(col_idx) returns (
uint256 collat_out,
uint256 fxs_out
) {
require(redeemPaused[col_idx] == false, "Redeeming is paused");
// Prevent unneccessary redemptions that could adversely affect the FXS price
require(getFRAXPrice() <= redeem_price_threshold, "Frax price too high");
uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
uint256 frax_after_fee = (frax_amount.mul(PRICE_PRECISION.sub(redemption_fee[col_idx]))).div(PRICE_PRECISION);
// Assumes $1 FRAX in all cases
if(global_collateral_ratio >= PRICE_PRECISION) {
// 1-to-1 or overcollateralized
collat_out = frax_after_fee
.mul(collateral_prices[col_idx])
.div(10 ** (6 + missing_decimals[col_idx])); // PRICE_PRECISION + missing decimals
fxs_out = 0;
} else if (global_collateral_ratio == 0) {
// Algorithmic
fxs_out = frax_after_fee
.mul(PRICE_PRECISION)
.div(getFXSPrice());
collat_out = 0;
} else {
// Fractional
collat_out = frax_after_fee
.mul(global_collateral_ratio)
.mul(collateral_prices[col_idx])
.div(10 ** (12 + missing_decimals[col_idx])); // PRICE_PRECISION ^2 + missing decimals
fxs_out = frax_after_fee
.mul(PRICE_PRECISION.sub(global_collateral_ratio))
.div(getFXSPrice()); // PRICE_PRECISIONS CANCEL OUT
}
// Checks
require(collat_out <= (ERC20(collateral_addresses[col_idx])).balanceOf(address(this)).sub(unclaimedPoolCollateral[col_idx]), "Insufficient pool collateral");
require(collat_out >= col_out_min, "Collateral slippage");
require(fxs_out >= fxs_out_min, "FXS slippage");
// Account for the redeem delay
redeemCollateralBalances[msg.sender][col_idx] = redeemCollateralBalances[msg.sender][col_idx].add(collat_out);
unclaimedPoolCollateral[col_idx] = unclaimedPoolCollateral[col_idx].add(collat_out);
redeemFXSBalances[msg.sender] = redeemFXSBalances[msg.sender].add(fxs_out);
unclaimedPoolFXS = unclaimedPoolFXS.add(fxs_out);
lastRedeemed[msg.sender] = block.number;
FRAX.pool_burn_from(msg.sender, frax_amount);
FXS.pool_mint(address(this), fxs_out);
}
// After a redemption happens, transfer the newly minted FXS and owed collateral from this pool
// contract to the user. Redemption is split into two functions to prevent flash loans from being able
// to take out FRAX/collateral from the system, use an AMM to trade the new price, and then mint back into the system.
function collectRedemption(uint256 col_idx) external returns (uint256 fxs_amount, uint256 collateral_amount) {
require(redeemPaused[col_idx] == false, "Redeeming is paused");
require((lastRedeemed[msg.sender].add(redemption_delay)) <= block.number, "Too soon");
bool sendFXS = false;
bool sendCollateral = false;
// Use Checks-Effects-Interactions pattern
if(redeemFXSBalances[msg.sender] > 0){
fxs_amount = redeemFXSBalances[msg.sender];
redeemFXSBalances[msg.sender] = 0;
unclaimedPoolFXS = unclaimedPoolFXS.sub(fxs_amount);
sendFXS = true;
}
if(redeemCollateralBalances[msg.sender][col_idx] > 0){
collateral_amount = redeemCollateralBalances[msg.sender][col_idx];
redeemCollateralBalances[msg.sender][col_idx] = 0;
unclaimedPoolCollateral[col_idx] = unclaimedPoolCollateral[col_idx].sub(collateral_amount);
sendCollateral = true;
}
// Send out the tokens
if(sendFXS){
TransferHelper.safeTransfer(address(FXS), msg.sender, fxs_amount);
}
if(sendCollateral){
TransferHelper.safeTransfer(collateral_addresses[col_idx], msg.sender, collateral_amount);
}
}
// Function can be called by an FXS holder to have the protocol buy back FXS with excess collateral value from a desired collateral pool
// This can also happen if the collateral ratio > 1
function buyBackFxs(uint256 col_idx, uint256 fxs_amount, uint256 col_out_min) external collateralEnabled(col_idx) returns (uint256 col_out) {
require(buyBackPaused[col_idx] == false, "Buyback is paused");
uint256 fxs_price = getFXSPrice();
uint256 available_excess_collat_dv = buybackAvailableCollat();
// If the total collateral value is higher than the amount required at the current collateral ratio then buy back up to the possible FXS with the desired collateral
require(available_excess_collat_dv > 0, "Insuf Collat Avail For BBK");
// Make sure not to take more than is available
uint256 fxs_dollar_value_d18 = fxs_amount.mul(fxs_price).div(PRICE_PRECISION);
require(fxs_dollar_value_d18 <= available_excess_collat_dv, "Insuf Collat Avail For BBK");
// Get the equivalent amount of collateral based on the market value of FXS provided
uint256 collateral_equivalent_d18 = fxs_dollar_value_d18.mul(PRICE_PRECISION).div(collateral_prices[col_idx]);
col_out = collateral_equivalent_d18.div(10 ** missing_decimals[col_idx]); // In its natural decimals()
// Subtract the buyback fee
col_out = (col_out.mul(PRICE_PRECISION.sub(buyback_fee[col_idx]))).div(PRICE_PRECISION);
// Check for slippage
require(col_out >= col_out_min, "Collateral slippage");
// Take in and burn the FXS, then send out the collateral
FXS.pool_burn_from(msg.sender, fxs_amount);
TransferHelper.safeTransfer(collateral_addresses[col_idx], msg.sender, col_out);
// Increment the outbound collateral, in E18, for that hour
// Used for buyback throttling
bbkHourlyCum[curEpochHr()] += collateral_equivalent_d18;
}
// When the protocol is recollateralizing, we need to give a discount of FXS to hit the new CR target
// Thus, if the target collateral ratio is higher than the actual value of collateral, minters get FXS for adding collateral
// This function simply rewards anyone that sends collateral to a pool with the same amount of FXS + the bonus rate
// Anyone can call this function to recollateralize the protocol and take the extra FXS value from the bonus rate as an arb opportunity
function recollateralize(uint256 col_idx, uint256 collateral_amount, uint256 fxs_out_min) external collateralEnabled(col_idx) returns (uint256 fxs_out) {
require(recollateralizePaused[col_idx] == false, "Recollat is paused");
uint256 collateral_amount_d18 = collateral_amount * (10 ** missing_decimals[col_idx]);
uint256 fxs_price = getFXSPrice();
// Get the amount of FXS actually available (accounts for throttling)
uint256 fxs_actually_available = recollatAvailableFxs();
// Calculated the attempted amount of FXS
fxs_out = collateral_amount_d18.mul(PRICE_PRECISION.add(bonus_rate).sub(recollat_fee[col_idx])).div(fxs_price);
// Make sure there is FXS available
require(fxs_out <= fxs_actually_available, "Insuf FXS Avail For RCT");
// Check slippage
require(fxs_out >= fxs_out_min, "FXS slippage");
// Don't take in more collateral than the pool ceiling for this token allows
require(freeCollatBalance(col_idx).add(collateral_amount) <= pool_ceilings[col_idx], "Pool ceiling");
// Take in the collateral and pay out the FXS
TransferHelper.safeTransferFrom(collateral_addresses[col_idx], msg.sender, address(this), collateral_amount);
FXS.pool_mint(msg.sender, fxs_out);
// Increment the outbound FXS, in E18
// Used for recollat throttling
rctHourlyCum[curEpochHr()] += fxs_out;
}
// Bypasses the gassy mint->redeem cycle for AMOs to borrow collateral
function amoMinterBorrow(uint256 collateral_amount) external onlyAMOMinters {
// Checks the col_idx of the minter as an additional safety check
uint256 minter_col_idx = IFraxAMOMinter(msg.sender).col_idx();
// Transfer
TransferHelper.safeTransfer(collateral_addresses[minter_col_idx], msg.sender, collateral_amount);
}
/* ========== RESTRICTED FUNCTIONS, CUSTODIAN CAN CALL TOO ========== */
function toggleMRBR(uint256 col_idx, uint8 tog_idx) external onlyByOwnGovCust {
if (tog_idx == 0) mintPaused[col_idx] = !mintPaused[col_idx];
else if (tog_idx == 1) redeemPaused[col_idx] = !redeemPaused[col_idx];
else if (tog_idx == 2) buyBackPaused[col_idx] = !buyBackPaused[col_idx];
else if (tog_idx == 3) recollateralizePaused[col_idx] = !recollateralizePaused[col_idx];
emit MRBRToggled(col_idx, tog_idx);
}
/* ========== RESTRICTED FUNCTIONS, GOVERNANCE ONLY ========== */
// Add an AMO Minter
function addAMOMinter(address amo_minter_addr) external onlyByOwnGov {
require(amo_minter_addr != address(0), "Zero address detected");
// Make sure the AMO Minter has collatDollarBalance()
uint256 collat_val_e18 = IFraxAMOMinter(amo_minter_addr).collatDollarBalance();
require(collat_val_e18 >= 0, "Invalid AMO");
amo_minter_addresses[amo_minter_addr] = true;
emit AMOMinterAdded(amo_minter_addr);
}
// Remove an AMO Minter
function removeAMOMinter(address amo_minter_addr) external onlyByOwnGov {
amo_minter_addresses[amo_minter_addr] = false;
emit AMOMinterRemoved(amo_minter_addr);
}
function setCollateralPrice(uint256 col_idx, uint256 _new_price) external onlyByOwnGov {
collateral_prices[col_idx] = _new_price;
emit CollateralPriceSet(col_idx, _new_price);
}
// Could also be called toggleCollateral
function toggleCollateral(uint256 col_idx) external onlyByOwnGov {
address col_address = collateral_addresses[col_idx];
enabled_collaterals[col_address] = !enabled_collaterals[col_address];
emit CollateralToggled(col_idx, enabled_collaterals[col_address]);
}
function setPoolCeiling(uint256 col_idx, uint256 new_ceiling) external onlyByOwnGov {
pool_ceilings[col_idx] = new_ceiling;
emit PoolCeilingSet(col_idx, new_ceiling);
}
function setFees(uint256 col_idx, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee) external onlyByOwnGov {
minting_fee[col_idx] = new_mint_fee;
redemption_fee[col_idx] = new_redeem_fee;
buyback_fee[col_idx] = new_buyback_fee;
recollat_fee[col_idx] = new_recollat_fee;
emit FeesSet(col_idx, new_mint_fee, new_redeem_fee, new_buyback_fee, new_recollat_fee);
}
function setPoolParameters(uint256 new_bonus_rate, uint256 new_redemption_delay) external onlyByOwnGov {
bonus_rate = new_bonus_rate;
redemption_delay = new_redemption_delay;
emit PoolParametersSet(new_bonus_rate, new_redemption_delay);
}
function setPriceThresholds(uint256 new_mint_price_threshold, uint256 new_redeem_price_threshold) external onlyByOwnGov {
mint_price_threshold = new_mint_price_threshold;
redeem_price_threshold = new_redeem_price_threshold;
emit PriceThresholdsSet(new_mint_price_threshold, new_redeem_price_threshold);
}
function setBbkRctPerHour(uint256 _bbkMaxColE18OutPerHour, uint256 _rctMaxFxsOutPerHour) external onlyByOwnGov {
bbkMaxColE18OutPerHour = _bbkMaxColE18OutPerHour;
rctMaxFxsOutPerHour = _rctMaxFxsOutPerHour;
emit BbkRctPerHourSet(_bbkMaxColE18OutPerHour, _rctMaxFxsOutPerHour);
}
// Set the Chainlink oracles
function setOracles(address _frax_usd_chainlink_addr, address _fxs_usd_chainlink_addr) external onlyByOwnGov {
// Set the instances
priceFeedFRAXUSD = AggregatorV3Interface(_frax_usd_chainlink_addr);
priceFeedFXSUSD = AggregatorV3Interface(_fxs_usd_chainlink_addr);
// Set the decimals
chainlink_frax_usd_decimals = priceFeedFRAXUSD.decimals();
chainlink_fxs_usd_decimals = priceFeedFXSUSD.decimals();
emit OraclesSet(_frax_usd_chainlink_addr, _fxs_usd_chainlink_addr);
}
function setCustodian(address new_custodian) external onlyByOwnGov {
custodian_address = new_custodian;
emit CustodianSet(new_custodian);
}
function setTimelock(address new_timelock) external onlyByOwnGov {
timelock_address = new_timelock;
emit TimelockSet(new_timelock);
}
/* ========== EVENTS ========== */
event CollateralToggled(uint256 col_idx, bool new_state);
event PoolCeilingSet(uint256 col_idx, uint256 new_ceiling);
event FeesSet(uint256 col_idx, uint256 new_mint_fee, uint256 new_redeem_fee, uint256 new_buyback_fee, uint256 new_recollat_fee);
event PoolParametersSet(uint256 new_bonus_rate, uint256 new_redemption_delay);
event PriceThresholdsSet(uint256 new_bonus_rate, uint256 new_redemption_delay);
event BbkRctPerHourSet(uint256 bbkMaxColE18OutPerHour, uint256 rctMaxFxsOutPerHour);
event AMOMinterAdded(address amo_minter_addr);
event AMOMinterRemoved(address amo_minter_addr);
event OraclesSet(address frax_usd_chainlink_addr, address fxs_usd_chainlink_addr);
event CustodianSet(address new_custodian);
event TimelockSet(address new_timelock);
event MRBRToggled(uint256 col_idx, uint8 tog_idx);
event CollateralPriceSet(uint256 col_idx, uint256 new_price);
}
// File contracts/Uniswap/Interfaces/IUniswapV2Factory.sol
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;
}
// File contracts/Uniswap/Interfaces/IUniswapV2Pair.sol
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;
}
// File contracts/Math/Babylonian.sol
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
// File contracts/Math/FixedPoint.sol
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint _x;
}
uint8 private constant RESOLUTION = 112;
uint private constant Q112 = uint(1) << RESOLUTION;
uint private constant Q224 = Q112 << RESOLUTION;
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
require(x != 0, 'FixedPoint: DIV_BY_ZERO');
return uq112x112(self._x / uint224(x));
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
uint z;
require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
return uq144x112(z);
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// equivalent to encode(numerator).div(denominator)
function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// take the reciprocal of a UQ112x112
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56));
}
}
// File contracts/Uniswap/UniswapV2OracleLibrary.sol
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
// File contracts/Uniswap/UniswapV2Library.sol
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// Less efficient than the CREATE2 method below
function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = IUniswapV2Factory(factory).getPair(token0, token1);
}
// calculates the CREATE2 address for a pair without making any external calls
function pairForCreate2(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint160(bytes20(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))))); // this matches the CREATE2 in UniswapV2Factory.createPair
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i = 0; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// File contracts/Oracle/UniswapPairOracle.sol
// Fixed window oracle that recomputes the average price for the entire period once every period
// Note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period
contract UniswapPairOracle is Owned {
using FixedPoint for *;
address timelock_address;
uint public PERIOD = 3600; // 1 hour TWAP (time-weighted average price)
uint public CONSULT_LENIENCY = 120; // Used for being able to consult past the period end
bool public ALLOW_STALE_CONSULTS = false; // If false, consult() will fail if the TWAP is stale
IUniswapV2Pair public immutable pair;
address public immutable token0;
address public immutable token1;
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint32 public blockTimestampLast;
FixedPoint.uq112x112 public price0Average;
FixedPoint.uq112x112 public price1Average;
modifier onlyByOwnGov() {
require(msg.sender == owner || msg.sender == timelock_address, "You are not an owner or the governance timelock");
_;
}
constructor (
address factory,
address tokenA,
address tokenB,
address _owner_address,
address _timelock_address
) public Owned(_owner_address) {
IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));
pair = _pair;
token0 = _pair.token0();
token1 = _pair.token1();
price0CumulativeLast = _pair.price0CumulativeLast(); // Fetch the current accumulated price value (1 / 0)
price1CumulativeLast = _pair.price1CumulativeLast(); // Fetch the current accumulated price value (0 / 1)
uint112 reserve0;
uint112 reserve1;
(reserve0, reserve1, blockTimestampLast) = _pair.getReserves();
require(reserve0 != 0 && reserve1 != 0, 'UniswapPairOracle: NO_RESERVES'); // Ensure that there's liquidity in the pair
timelock_address = _timelock_address;
}
function setTimelock(address _timelock_address) external onlyByOwnGov {
timelock_address = _timelock_address;
}
function setPeriod(uint _period) external onlyByOwnGov {
PERIOD = _period;
}
function setConsultLeniency(uint _consult_leniency) external onlyByOwnGov {
CONSULT_LENIENCY = _consult_leniency;
}
function setAllowStaleConsults(bool _allow_stale_consults) external onlyByOwnGov {
ALLOW_STALE_CONSULTS = _allow_stale_consults;
}
// Check if update() can be called instead of wasting gas calling it
function canUpdate() public view returns (bool) {
uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp();
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
return (timeElapsed >= PERIOD);
}
function update() external {
(uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
// Ensure that at least one full period has passed since the last update
require(timeElapsed >= PERIOD, 'UniswapPairOracle: PERIOD_NOT_ELAPSED');
// Overflow is desired, casting never truncates
// Cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed));
price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed));
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
}
// Note this will always return 0 before update has been called successfully for the first time.
function consult(address token, uint amountIn) public view returns (uint amountOut) {
uint32 blockTimestamp = UniswapV2OracleLibrary.currentBlockTimestamp();
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // Overflow is desired
// Ensure that the price is not stale
require((timeElapsed < (PERIOD + CONSULT_LENIENCY)) || ALLOW_STALE_CONSULTS, 'UniswapPairOracle: PRICE_IS_STALE_NEED_TO_CALL_UPDATE');
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, 'UniswapPairOracle: INVALID_TOKEN');
amountOut = price1Average.mul(amountIn).decode144();
}
}
}
// File contracts/Uniswap/Interfaces/IUniswapV2Router01.sol
interface IUniswapV2Router01 {
function factory() external returns (address);
function WETH() external 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);
}
// File contracts/Uniswap/Interfaces/IUniswapV2Router02.sol
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File contracts/Proxy/Initializable.sol
// solhint-disable-next-line compiler-version
/**
* @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;
}
}
}
// File contracts/Math/Math.sol
/**
* @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);
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// File contracts/Curve/IveFXS.sol
pragma abicoder v2;
interface IveFXS {
struct LockedBalance {
int128 amount;
uint256 end;
}
function commit_transfer_ownership(address addr) external;
function apply_transfer_ownership() external;
function commit_smart_wallet_checker(address addr) external;
function apply_smart_wallet_checker() external;
function toggleEmergencyUnlock() external;
function recoverERC20(address token_addr, uint256 amount) external;
function get_last_user_slope(address addr) external view returns (int128);
function user_point_history__ts(address _addr, uint256 _idx) external view returns (uint256);
function locked__end(address _addr) external view returns (uint256);
function checkpoint() external;
function deposit_for(address _addr, uint256 _value) external;
function create_lock(uint256 _value, uint256 _unlock_time) external;
function increase_amount(uint256 _value) external;
function increase_unlock_time(uint256 _unlock_time) external;
function withdraw() external;
function balanceOf(address addr) external view returns (uint256);
function balanceOf(address addr, uint256 _t) external view returns (uint256);
function balanceOfAt(address addr, uint256 _block) external view returns (uint256);
function totalSupply() external view returns (uint256);
function totalSupply(uint256 t) external view returns (uint256);
function totalSupplyAt(uint256 _block) external view returns (uint256);
function totalFXSSupply() external view returns (uint256);
function totalFXSSupplyAt(uint256 _block) external view returns (uint256);
function changeController(address _newController) external;
function token() external view returns (address);
function supply() external view returns (uint256);
function locked(address addr) external view returns (LockedBalance memory);
function epoch() external view returns (uint256);
function point_history(uint256 arg0) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk, uint256 fxs_amt);
function user_point_history(address arg0, uint256 arg1) external view returns (int128 bias, int128 slope, uint256 ts, uint256 blk, uint256 fxs_amt);
function user_point_epoch(address arg0) external view returns (uint256);
function slope_changes(uint256 arg0) external view returns (int128);
function controller() external view returns (address);
function transfersEnabled() external view returns (bool);
function emergencyUnlockActive() external view returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function version() external view returns (string memory);
function decimals() external view returns (uint256);
function future_smart_wallet_checker() external view returns (address);
function smart_wallet_checker() external view returns (address);
function admin() external view returns (address);
function future_admin() external view returns (address);
}
// File contracts/ERC20/SafeERC20.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");
}
}
}
// File contracts/Utils/ReentrancyGuard.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 ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File contracts/Staking/veFXSYieldDistributorV4.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ======================veFXSYieldDistributorV4=======================
// ====================================================================
// Distributes Frax protocol yield based on the claimer's veFXS balance
// V3: Yield will now not accrue for unlocked veFXS
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
// Originally inspired by Synthetix.io, but heavily modified by the Frax team (veFXS portion)
// https://github.com/Synthetixio/synthetix/blob/develop/contracts/StakingRewards.sol
contract veFXSYieldDistributorV4 is Owned, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for ERC20;
/* ========== STATE VARIABLES ========== */
// Instances
IveFXS private veFXS;
ERC20 public emittedToken;
// Addresses
address public emitted_token_address;
// Admin addresses
address public timelock_address;
// Constant for price precision
uint256 private constant PRICE_PRECISION = 1e6;
// Yield and period related
uint256 public periodFinish;
uint256 public lastUpdateTime;
uint256 public yieldRate;
uint256 public yieldDuration = 604800; // 7 * 86400 (7 days)
mapping(address => bool) public reward_notifiers;
// Yield tracking
uint256 public yieldPerVeFXSStored = 0;
mapping(address => uint256) public userYieldPerTokenPaid;
mapping(address => uint256) public yields;
// veFXS tracking
uint256 public totalVeFXSParticipating = 0;
uint256 public totalVeFXSSupplyStored = 0;
mapping(address => bool) public userIsInitialized;
mapping(address => uint256) public userVeFXSCheckpointed;
mapping(address => uint256) public userVeFXSEndpointCheckpointed;
mapping(address => uint256) private lastRewardClaimTime; // staker addr -> timestamp
// Greylists
mapping(address => bool) public greylist;
// Admin booleans for emergencies
bool public yieldCollectionPaused = false; // For emergencies
struct LockedBalance {
int128 amount;
uint256 end;
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require( msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock");
_;
}
modifier notYieldCollectionPaused() {
require(yieldCollectionPaused == false, "Yield collection is paused");
_;
}
modifier checkpointUser(address account) {
_checkpointUser(account);
_;
}
/* ========== CONSTRUCTOR ========== */
constructor (
address _owner,
address _emittedToken,
address _timelock_address,
address _veFXS_address
) Owned(_owner) {
emitted_token_address = _emittedToken;
emittedToken = ERC20(_emittedToken);
veFXS = IveFXS(_veFXS_address);
lastUpdateTime = block.timestamp;
timelock_address = _timelock_address;
reward_notifiers[_owner] = true;
}
/* ========== VIEWS ========== */
function fractionParticipating() external view returns (uint256) {
return totalVeFXSParticipating.mul(PRICE_PRECISION).div(totalVeFXSSupplyStored);
}
// Only positions with locked veFXS can accrue yield. Otherwise, expired-locked veFXS
// is de-facto rewards for FXS.
function eligibleCurrentVeFXS(address account) public view returns (uint256 eligible_vefxs_bal, uint256 stored_ending_timestamp) {
uint256 curr_vefxs_bal = veFXS.balanceOf(account);
// Stored is used to prevent abuse
stored_ending_timestamp = userVeFXSEndpointCheckpointed[account];
// Only unexpired veFXS should be eligible
if (stored_ending_timestamp != 0 && (block.timestamp >= stored_ending_timestamp)){
eligible_vefxs_bal = 0;
}
else if (block.timestamp >= stored_ending_timestamp){
eligible_vefxs_bal = 0;
}
else {
eligible_vefxs_bal = curr_vefxs_bal;
}
}
function lastTimeYieldApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function yieldPerVeFXS() public view returns (uint256) {
if (totalVeFXSSupplyStored == 0) {
return yieldPerVeFXSStored;
} else {
return (
yieldPerVeFXSStored.add(
lastTimeYieldApplicable()
.sub(lastUpdateTime)
.mul(yieldRate)
.mul(1e18)
.div(totalVeFXSSupplyStored)
)
);
}
}
function earned(address account) public view returns (uint256) {
// Uninitialized users should not earn anything yet
if (!userIsInitialized[account]) return 0;
// Get eligible veFXS balances
(uint256 eligible_current_vefxs, uint256 ending_timestamp) = eligibleCurrentVeFXS(account);
// If your veFXS is unlocked
uint256 eligible_time_fraction = PRICE_PRECISION;
if (eligible_current_vefxs == 0){
// And you already claimed after expiration
if (lastRewardClaimTime[account] >= ending_timestamp) {
// You get NOTHING. You LOSE. Good DAY ser!
return 0;
}
// You haven't claimed yet
else {
uint256 eligible_time = (ending_timestamp).sub(lastRewardClaimTime[account]);
uint256 total_time = (block.timestamp).sub(lastRewardClaimTime[account]);
eligible_time_fraction = PRICE_PRECISION.mul(eligible_time).div(total_time);
}
}
// If the amount of veFXS increased, only pay off based on the old balance
// Otherwise, take the midpoint
uint256 vefxs_balance_to_use;
{
uint256 old_vefxs_balance = userVeFXSCheckpointed[account];
if (eligible_current_vefxs > old_vefxs_balance){
vefxs_balance_to_use = old_vefxs_balance;
}
else {
vefxs_balance_to_use = ((eligible_current_vefxs).add(old_vefxs_balance)).div(2);
}
}
return (
vefxs_balance_to_use
.mul(yieldPerVeFXS().sub(userYieldPerTokenPaid[account]))
.mul(eligible_time_fraction)
.div(1e18 * PRICE_PRECISION)
.add(yields[account])
);
}
function getYieldForDuration() external view returns (uint256) {
return (yieldRate.mul(yieldDuration));
}
/* ========== MUTATIVE FUNCTIONS ========== */
function _checkpointUser(address account) internal {
// Need to retro-adjust some things if the period hasn't been renewed, then start a new one
sync();
// Calculate the earnings first
_syncEarned(account);
// Get the old and the new veFXS balances
uint256 old_vefxs_balance = userVeFXSCheckpointed[account];
uint256 new_vefxs_balance = veFXS.balanceOf(account);
// Update the user's stored veFXS balance
userVeFXSCheckpointed[account] = new_vefxs_balance;
// Update the user's stored ending timestamp
IveFXS.LockedBalance memory curr_locked_bal_pack = veFXS.locked(account);
userVeFXSEndpointCheckpointed[account] = curr_locked_bal_pack.end;
// Update the total amount participating
if (new_vefxs_balance >= old_vefxs_balance) {
uint256 weight_diff = new_vefxs_balance.sub(old_vefxs_balance);
totalVeFXSParticipating = totalVeFXSParticipating.add(weight_diff);
} else {
uint256 weight_diff = old_vefxs_balance.sub(new_vefxs_balance);
totalVeFXSParticipating = totalVeFXSParticipating.sub(weight_diff);
}
// Mark the user as initialized
if (!userIsInitialized[account]) {
userIsInitialized[account] = true;
lastRewardClaimTime[account] = block.timestamp;
}
}
function _syncEarned(address account) internal {
if (account != address(0)) {
uint256 earned0 = earned(account);
yields[account] = earned0;
userYieldPerTokenPaid[account] = yieldPerVeFXSStored;
}
}
// Anyone can checkpoint another user
function checkpointOtherUser(address user_addr) external {
_checkpointUser(user_addr);
}
// Checkpoints the user
function checkpoint() external {
_checkpointUser(msg.sender);
}
function getYield() external nonReentrant notYieldCollectionPaused checkpointUser(msg.sender) returns (uint256 yield0) {
require(greylist[msg.sender] == false, "Address has been greylisted");
yield0 = yields[msg.sender];
if (yield0 > 0) {
yields[msg.sender] = 0;
TransferHelper.safeTransfer(
emitted_token_address,
msg.sender,
yield0
);
emit YieldCollected(msg.sender, yield0, emitted_token_address);
}
lastRewardClaimTime[msg.sender] = block.timestamp;
}
function sync() public {
// Update the total veFXS supply
yieldPerVeFXSStored = yieldPerVeFXS();
totalVeFXSSupplyStored = veFXS.totalSupply();
lastUpdateTime = lastTimeYieldApplicable();
}
function notifyRewardAmount(uint256 amount) external {
// Only whitelisted addresses can notify rewards
require(reward_notifiers[msg.sender], "Sender not whitelisted");
// Handle the transfer of emission tokens via `transferFrom` to reduce the number
// of transactions required and ensure correctness of the smission amount
emittedToken.safeTransferFrom(msg.sender, address(this), amount);
// Update some values beforehand
sync();
// Update the new yieldRate
if (block.timestamp >= periodFinish) {
yieldRate = amount.div(yieldDuration);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(yieldRate);
yieldRate = amount.add(leftover).div(yieldDuration);
}
// Update duration-related info
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(yieldDuration);
emit RewardAdded(amount, yieldRate);
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Added to support recovering LP Yield and other mistaken tokens from other systems to be distributed to holders
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov {
// Only the owner address can ever receive the recovery withdrawal
TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount);
emit RecoveredERC20(tokenAddress, tokenAmount);
}
function setYieldDuration(uint256 _yieldDuration) external onlyByOwnGov {
require( periodFinish == 0 || block.timestamp > periodFinish, "Previous yield period must be complete before changing the duration for the new period");
yieldDuration = _yieldDuration;
emit YieldDurationUpdated(yieldDuration);
}
function greylistAddress(address _address) external onlyByOwnGov {
greylist[_address] = !(greylist[_address]);
}
function toggleRewardNotifier(address notifier_addr) external onlyByOwnGov {
reward_notifiers[notifier_addr] = !reward_notifiers[notifier_addr];
}
function setPauses(bool _yieldCollectionPaused) external onlyByOwnGov {
yieldCollectionPaused = _yieldCollectionPaused;
}
function setYieldRate(uint256 _new_rate0, bool sync_too) external onlyByOwnGov {
yieldRate = _new_rate0;
if (sync_too) {
sync();
}
}
function setTimelock(address _new_timelock) external onlyByOwnGov {
timelock_address = _new_timelock;
}
/* ========== EVENTS ========== */
event RewardAdded(uint256 reward, uint256 yieldRate);
event OldYieldCollected(address indexed user, uint256 yield, address token_address);
event YieldCollected(address indexed user, uint256 yield, address token_address);
event YieldDurationUpdated(uint256 newDuration);
event RecoveredERC20(address token, uint256 amount);
event YieldPeriodRenewed(address token, uint256 yieldRate);
event DefaultInitialization();
/* ========== A CHICKEN ========== */
//
// ,~.
// ,-'__ `-,
// {,-' `. } ,')
// ,( a ) `-.__ ,',')~,
// <=.) ( `-.__,==' ' ' '}
// ( ) /)
// `-'\ , )
// | \ `~. /
// \ `._ \ /
// \ `._____,' ,'
// `-. ,'
// `-._ _,-'
// 77jj'
// //_||
// __//--'/`
// ,--'/` '
//
// [hjw] https://textart.io/art/vw6Sa3iwqIRGkZsN1BC2vweF/chicken
}
// File contracts/Misc_AMOs/FXS1559_AMO_V3.sol
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ========================== FXS1559_AMO_V3 ==========================
// ====================================================================
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Jason Huan: https://github.com/jasonhuan
// Sam Kazemian: https://github.com/samkazemian
contract FXS1559_AMO_V3 is Owned {
using SafeMath for uint256;
// SafeMath automatically included in Solidity >= 8.0.0
/* ========== STATE VARIABLES ========== */
ERC20 private collateral_token;
IFrax private FRAX;
IFxs private FXS;
IUniswapV2Router02 private UniRouterV2;
IFraxAMOMinter public amo_minter;
FraxPoolV3 public pool = FraxPoolV3(0x2fE065e6FFEf9ac95ab39E5042744d695F560729);
veFXSYieldDistributorV4 public yieldDistributor;
address private constant collateral_address = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public timelock_address;
address public custodian_address;
address private constant frax_address = 0x853d955aCEf822Db058eb8505911ED77F175b99e;
address private constant fxs_address = 0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0;
address payable public constant UNISWAP_ROUTER_ADDRESS = payable(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public amo_minter_address;
uint256 private missing_decimals;
uint256 private constant PRICE_PRECISION = 1e6;
uint256 private constant COLLATERAL_RATIO_PRECISION = 1e6;
// FRAX -> FXS max slippage
uint256 public max_slippage;
// Burned vs given to yield distributor
uint256 public burn_fraction; // E6. Fraction of FXS burned vs transferred to the yield distributor
/* ========== CONSTRUCTOR ========== */
constructor (
address _owner_address,
address _yield_distributor_address,
address _amo_minter_address
) Owned(_owner_address) {
owner = _owner_address;
FRAX = IFrax(frax_address);
FXS = IFxs(fxs_address);
collateral_token = ERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
missing_decimals = uint(18).sub(collateral_token.decimals());
yieldDistributor = veFXSYieldDistributorV4(_yield_distributor_address);
// Initializations
UniRouterV2 = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
amo_minter = IFraxAMOMinter(_amo_minter_address);
max_slippage = 50000; // 5%
burn_fraction = 0; // Give all to veFXS initially
// Get the custodian and timelock addresses from the minter
custodian_address = amo_minter.custodian_address();
timelock_address = amo_minter.timelock_address();
}
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock");
_;
}
modifier onlyByOwnGovCust() {
require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd");
_;
}
modifier onlyByMinter() {
require(msg.sender == address(amo_minter), "Not minter");
_;
}
/* ========== VIEWS ========== */
function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) {
frax_val_e18 = 1e18;
collat_val_e18 = 1e18;
}
/* ========== RESTRICTED FUNCTIONS ========== */
function _swapFRAXforFXS(uint256 frax_amount) internal returns (uint256 frax_spent, uint256 fxs_received) {
// Get the FXS price
uint256 fxs_price = pool.getFXSPrice();
// Approve the FRAX for the router
FRAX.approve(UNISWAP_ROUTER_ADDRESS, frax_amount);
address[] memory FRAX_FXS_PATH = new address[](2);
FRAX_FXS_PATH[0] = frax_address;
FRAX_FXS_PATH[1] = fxs_address;
uint256 min_fxs_out = frax_amount.mul(PRICE_PRECISION).div(fxs_price);
min_fxs_out = min_fxs_out.sub(min_fxs_out.mul(max_slippage).div(PRICE_PRECISION));
// Buy some FXS with FRAX
(uint[] memory amounts) = UniRouterV2.swapExactTokensForTokens(
frax_amount,
min_fxs_out,
FRAX_FXS_PATH,
address(this),
2105300114 // Expiration: a long time from now
);
return (amounts[0], amounts[1]);
}
// Burn unneeded or excess FRAX
function swapBurn(uint256 override_frax_amount, bool use_override) public onlyByOwnGov {
uint256 mintable_frax;
if (use_override){
// mintable_frax = override_USDC_amount.mul(10 ** missing_decimals).mul(COLLATERAL_RATIO_PRECISION).div(FRAX.global_collateral_ratio());
mintable_frax = override_frax_amount;
}
else {
mintable_frax = pool.buybackAvailableCollat();
}
(, uint256 fxs_received ) = _swapFRAXforFXS(mintable_frax);
// Calculate the amount to burn vs give to the yield distributor
uint256 amt_to_burn = fxs_received.mul(burn_fraction).div(PRICE_PRECISION);
uint256 amt_to_yield_distributor = fxs_received.sub(amt_to_burn);
// Burn some of the FXS
burnFXS(amt_to_burn);
// Give the rest to the yield distributor
FXS.approve(address(yieldDistributor), amt_to_yield_distributor);
yieldDistributor.notifyRewardAmount(amt_to_yield_distributor);
}
/* ========== Burns and givebacks ========== */
// Burn unneeded or excess FRAX. Goes through the minter
function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust {
FRAX.approve(address(amo_minter), frax_amount);
amo_minter.burnFraxFromAMO(frax_amount);
}
// Burn unneeded FXS. Goes through the minter
function burnFXS(uint256 fxs_amount) public onlyByOwnGovCust {
FXS.approve(address(amo_minter), fxs_amount);
amo_minter.burnFxsFromAMO(fxs_amount);
}
/* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */
function setBurnFraction(uint256 _burn_fraction) external onlyByOwnGov {
burn_fraction = _burn_fraction;
}
function setFraxPool(address _frax_pool_address) external onlyByOwnGov {
pool = FraxPoolV3(_frax_pool_address);
}
function setAMOMinter(address _amo_minter_address) external onlyByOwnGov {
amo_minter = IFraxAMOMinter(_amo_minter_address);
// Get the timelock address from the minter
timelock_address = amo_minter.timelock_address();
// Make sure the new address is not address(0)
require(timelock_address != address(0), "Invalid timelock");
}
function setSafetyParams(uint256 _max_slippage) external onlyByOwnGov {
max_slippage = _max_slippage;
}
function setYieldDistributor(address _yield_distributor_address) external onlyByOwnGov {
yieldDistributor = veFXSYieldDistributorV4(_yield_distributor_address);
}
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov {
TransferHelper.safeTransfer(address(tokenAddress), msg.sender, tokenAmount);
}
// Generic proxy
function execute(
address _to,
uint256 _value,
bytes calldata _data
) external onlyByOwnGov returns (bool, bytes memory) {
(bool success, bytes memory result) = _to.call{value:_value}(_data);
return (success, result);
}
}
|
Get the timelock address from the minter Make sure the new address is not address(0)
|
function setAMOMinter(address _amo_minter_address) external onlyByOwnGov {
amo_minter = IFraxAMOMinter(_amo_minter_address);
timelock_address = amo_minter.timelock_address();
require(timelock_address != address(0), "Invalid timelock");
}
| 448,752 |
./partial_match/1/0x81373f4E8D0BD48bbE8842E9eE16dB7B60c20613/sources/src/libraries/FixedPointMath.sol
|
Creates a rational fraction as a Number from 2 uint256 values n The numerator. d The denominator. return The fixed point decimal representation./
|
function rational(uint256 n, uint256 d) internal pure returns (Number memory) {
Number memory numerator = encode(n);
return FixedPointMath.div(numerator, d);
}
| 9,375,072 |
./full_match/5/0xB78299e5183C7746D825D9f92ABF6368F54f8537/sources/contracts/y00tsAnchorClub.sol
|
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. ====/ 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.
|
function isContract(address account) internal view returns(bool) {
return account.code.length > 0;
}
| 1,879,437 |
./full_match/1/0xcc7C704514198E379884B0Ccf1A604219cC1c03c/sources/src/Vault.sol
|
won't overflow since time is nowhere near uint256.max can overflow if _lockedProfit difference > uint256.max but in practice should never happen
|
function lockedProfit() public view returns (uint256 lockedAssets) {
uint256 last = lastReport;
uint256 duration = lockedProfitDuration;
unchecked {
if (block.timestamp >= last + duration) return 0;
return _lockedProfit - _lockedProfit.mulDivDown(block.timestamp - last, duration);
}
}
| 4,912,860 |
./partial_match/1/0x183b1C0339A97b097a827b5387F542b1CD147Ba6/sources/contracts/SaveOurDailyDoser.sol
|
Allow owner to send `mintNumber` tokens without cost to multiple addresses _receivers Array of addresses to send tokens to _mintNumber Array of number of tokens to send to each address/
|
function gift(address[] calldata _receivers, uint256[] calldata _mintNumber)
external
onlyOwner
{
require(
_receivers.length == _mintNumber.length,
"ARRAYS_MUST_BE_SAME_LENGTH"
);
uint256 totalMint = 0;
for (uint256 i = 0; i < _mintNumber.length; i++) {
totalMint += _mintNumber[i];
}
require(totalSupply() + totalMint <= maxSupply, "MINT_TOO_LARGE");
for (uint256 i = 0; i < _receivers.length; i++) {
_safeMint(_receivers[i], _mintNumber[i]);
}
}
| 15,553,074 |
./partial_match/97/0x53fADa23F98672442B6fE5Ff0Cb6b341a10EF062/sources/AnimalFactory.sol
|
The structure defining a single animal
|
{
struct AnimalProperties
{
uint id;
string name;
string desc;
bool upForSale;
uint priceForSale;
bool upForMating;
bool eggPhase;
uint priceForMating;
bool isBornByMating;
uint parentId1;
uint parentId2;
uint birthdate;
uint costumeId;
uint generationId;
}
using SafeMath for uint256;
uint public ownerPerThousandShareForBuying = 2;
uint public priceForBuyingCostume;
uint public priceForSaleAdvertisement = 0.00000001 ether;
uint[] eggPhaseAnimalIds;
uint[] animalIdsWithPendingCostumes;
ERC721Interface public token;
uint uniqueAnimalId=0;
mapping(uint=>AnimalProperties) animalAgainstId;
mapping(uint=>uint[]) childrenIdAgainstAnimalId;
uint[] upForMatingList;
uint[] upForSaleList;
address[] memberAddresses;
AnimalProperties animalObject;
uint public ownerPerThousandShareForMating = 2;
uint public freeAnimalsLimit = 4;
bool public isContractPaused;
uint public priceForMateAdvertisement = 0.00000001 ether;
uint256 public weiRaised;
uint256 public totalBunniesCreated=0;
uint256 public weiPerAnimal = 0.00000001 ether;
event AnimalsPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function AnimalFactory(address _walletOwner,address _tokenAddress) public
{
require(_walletOwner != 0x0);
owner = _walletOwner;
isContractPaused = false;
priceForMateAdvertisement = 0.00000001 ether;
priceForSaleAdvertisement = 0.00000001 ether;
priceForBuyingCostume = 0.00000001 ether;
token = ERC721Interface(_tokenAddress);
}
function getAnimalById(uint aid) public constant returns
(string, string,uint,uint ,uint, uint,uint)
{
if(animalAgainstId[aid].eggPhase==true)
{
return(animalAgainstId[aid].name,
animalAgainstId[aid].desc,
2**256 - 1,
animalAgainstId[aid].priceForSale,
animalAgainstId[aid].priceForMating,
animalAgainstId[aid].parentId1,
animalAgainstId[aid].parentId2
);
}
else
{
return(animalAgainstId[aid].name,
animalAgainstId[aid].desc,
animalAgainstId[aid].id,
animalAgainstId[aid].priceForSale,
animalAgainstId[aid].priceForMating,
animalAgainstId[aid].parentId1,
animalAgainstId[aid].parentId2
);
}
}
function getAnimalById(uint aid) public constant returns
(string, string,uint,uint ,uint, uint,uint)
{
if(animalAgainstId[aid].eggPhase==true)
{
return(animalAgainstId[aid].name,
animalAgainstId[aid].desc,
2**256 - 1,
animalAgainstId[aid].priceForSale,
animalAgainstId[aid].priceForMating,
animalAgainstId[aid].parentId1,
animalAgainstId[aid].parentId2
);
}
else
{
return(animalAgainstId[aid].name,
animalAgainstId[aid].desc,
animalAgainstId[aid].id,
animalAgainstId[aid].priceForSale,
animalAgainstId[aid].priceForMating,
animalAgainstId[aid].parentId1,
animalAgainstId[aid].parentId2
);
}
}
function getAnimalById(uint aid) public constant returns
(string, string,uint,uint ,uint, uint,uint)
{
if(animalAgainstId[aid].eggPhase==true)
{
return(animalAgainstId[aid].name,
animalAgainstId[aid].desc,
2**256 - 1,
animalAgainstId[aid].priceForSale,
animalAgainstId[aid].priceForMating,
animalAgainstId[aid].parentId1,
animalAgainstId[aid].parentId2
);
}
else
{
return(animalAgainstId[aid].name,
animalAgainstId[aid].desc,
animalAgainstId[aid].id,
animalAgainstId[aid].priceForSale,
animalAgainstId[aid].priceForMating,
animalAgainstId[aid].parentId1,
animalAgainstId[aid].parentId2
);
}
}
function getAnimalByIdVisibility(uint aid) public constant
returns (bool upforsale,bool upformating,bool eggphase,bool isbornbymating,
uint birthdate, uint costumeid, uint generationid )
{
return(
animalAgainstId[aid].upForSale,
animalAgainstId[aid].upForMating,
animalAgainstId[aid].eggPhase,
animalAgainstId[aid].isBornByMating,
animalAgainstId[aid].birthdate,
animalAgainstId[aid].costumeId,
animalAgainstId[aid].generationId
);
}
function getOwnerByAnimalId(uint aid) public constant
returns (address)
{
return token.ownerOf(aid);
}
function getAllAnimalsByAddress(address ad) public constant returns (uint[] listAnimals)
{
require (!isContractPaused);
return token.getAnimalIdAgainstAddress(ad);
}
function claimFreeAnimalFromAnimalFactory( string animalName, string animalDesc) public
{
require(msg.sender != 0x0);
require (!isContractPaused);
uint gId=0;
if (msg.sender!=owner)
{
require(token.getTotalTokensAgainstAddress(msg.sender)<freeAnimalsLimit);
gId=1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
eggPhase: false,
priceForSale:0,
upForMating: false,
priceForMating:0,
isBornByMating: false,
parentId1:0,
parentId2:0,
birthdate:now,
costumeId:0,
generationId:gId
});
token.sendToken(msg.sender, uniqueAnimalId,animalName);
totalBunniesCreated++;
}
function claimFreeAnimalFromAnimalFactory( string animalName, string animalDesc) public
{
require(msg.sender != 0x0);
require (!isContractPaused);
uint gId=0;
if (msg.sender!=owner)
{
require(token.getTotalTokensAgainstAddress(msg.sender)<freeAnimalsLimit);
gId=1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
eggPhase: false,
priceForSale:0,
upForMating: false,
priceForMating:0,
isBornByMating: false,
parentId1:0,
parentId2:0,
birthdate:now,
costumeId:0,
generationId:gId
});
token.sendToken(msg.sender, uniqueAnimalId,animalName);
totalBunniesCreated++;
}
uniqueAnimalId++;
function claimFreeAnimalFromAnimalFactory( string animalName, string animalDesc) public
{
require(msg.sender != 0x0);
require (!isContractPaused);
uint gId=0;
if (msg.sender!=owner)
{
require(token.getTotalTokensAgainstAddress(msg.sender)<freeAnimalsLimit);
gId=1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
eggPhase: false,
priceForSale:0,
upForMating: false,
priceForMating:0,
isBornByMating: false,
parentId1:0,
parentId2:0,
birthdate:now,
costumeId:0,
generationId:gId
});
token.sendToken(msg.sender, uniqueAnimalId,animalName);
totalBunniesCreated++;
}
animalAgainstId[uniqueAnimalId]=animalObject;
function MintAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable
{
require (!isContractPaused);
require(validPurchase());
require(msg.sender != 0x0);
uint gId=0;
if (msg.sender!=owner)
{
gId=1;
}
uint256 weiAmount = msg.value;
uniqueAnimalId++;
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: false,
priceForMating:0,
isBornByMating:false,
parentId1:0,
parentId2:0,
birthdate:now,
costumeId:0,
generationId:gId
});
emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens);
totalBunniesCreated++;
}
function MintAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable
{
require (!isContractPaused);
require(validPurchase());
require(msg.sender != 0x0);
uint gId=0;
if (msg.sender!=owner)
{
gId=1;
}
uint256 weiAmount = msg.value;
uniqueAnimalId++;
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: false,
priceForMating:0,
isBornByMating:false,
parentId1:0,
parentId2:0,
birthdate:now,
costumeId:0,
generationId:gId
});
emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens);
totalBunniesCreated++;
}
uint256 tokens = weiAmount.div(weiPerAnimal);
weiRaised = weiRaised.add(weiAmount);
function MintAnimalsFromAnimalFactory(string animalName, string animalDesc) public payable
{
require (!isContractPaused);
require(validPurchase());
require(msg.sender != 0x0);
uint gId=0;
if (msg.sender!=owner)
{
gId=1;
}
uint256 weiAmount = msg.value;
uniqueAnimalId++;
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: false,
priceForMating:0,
isBornByMating:false,
parentId1:0,
parentId2:0,
birthdate:now,
costumeId:0,
generationId:gId
});
emit AnimalsPurchased(msg.sender, owner, weiAmount, tokens);
totalBunniesCreated++;
}
token.sendToken(msg.sender, uniqueAnimalId,animalName);
animalAgainstId[uniqueAnimalId]=animalObject;
owner.transfer(msg.value);
function buyAnimalsFromUser(uint animalId) public payable
{
require (!isContractPaused);
require(msg.sender != 0x0);
address prevOwner=token.ownerOf(animalId);
require(prevOwner!=msg.sender);
uint price=animalAgainstId[animalId].priceForSale;
uint OwnerPercentage=animalAgainstId[animalId].priceForSale.mul(ownerPerThousandShareForBuying);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[animalId].priceForSale.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
token.safeTransferFrom(prevOwner,msg.sender,animalId);
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
for (uint j=0;j<upForSaleList.length;j++)
{
if (upForSaleList[j] == animalId)
delete upForSaleList[j];
}
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
function buyAnimalsFromUser(uint animalId) public payable
{
require (!isContractPaused);
require(msg.sender != 0x0);
address prevOwner=token.ownerOf(animalId);
require(prevOwner!=msg.sender);
uint price=animalAgainstId[animalId].priceForSale;
uint OwnerPercentage=animalAgainstId[animalId].priceForSale.mul(ownerPerThousandShareForBuying);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[animalId].priceForSale.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
token.safeTransferFrom(prevOwner,msg.sender,animalId);
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
for (uint j=0;j<upForSaleList.length;j++)
{
if (upForSaleList[j] == animalId)
delete upForSaleList[j];
}
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
prevOwner.transfer(price);
owner.transfer(OwnerPercentage);
if(msg.value>priceWithOwnerPercentage)
function buyAnimalsFromUser(uint animalId) public payable
{
require (!isContractPaused);
require(msg.sender != 0x0);
address prevOwner=token.ownerOf(animalId);
require(prevOwner!=msg.sender);
uint price=animalAgainstId[animalId].priceForSale;
uint OwnerPercentage=animalAgainstId[animalId].priceForSale.mul(ownerPerThousandShareForBuying);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[animalId].priceForSale.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
token.safeTransferFrom(prevOwner,msg.sender,animalId);
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
for (uint j=0;j<upForSaleList.length;j++)
{
if (upForSaleList[j] == animalId)
delete upForSaleList[j];
}
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable
{
require (!isContractPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
costumeId:0,
generationId:generationnum
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable
{
require (!isContractPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
costumeId:0,
generationId:generationnum
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable
{
require (!isContractPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
costumeId:0,
generationId:generationnum
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
uniqueAnimalId++;
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable
{
require (!isContractPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
costumeId:0,
generationId:generationnum
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
token.sendToken(msg.sender,uniqueAnimalId,animalName);
animalAgainstId[uniqueAnimalId]=animalObject;
eggPhaseAnimalIds.push(uniqueAnimalId);
childrenIdAgainstAnimalId[parent1Id].push(uniqueAnimalId);
for (uint i=0;i<upForMatingList.length;i++)
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable
{
require (!isContractPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
costumeId:0,
generationId:generationnum
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
animalAgainstId[parent1Id].upForMating = false;
token.ownerOf(parent1Id).transfer(price);
owner.transfer(OwnerPercentage);
if(msg.value>priceWithOwnerPercentage)
function mateAnimal(uint parent1Id, uint parent2Id, string animalName,string animalDesc) public payable
{
require (!isContractPaused);
require(msg.sender != 0x0);
require (token.ownerOf(parent2Id) == msg.sender);
require(token.ownerOf(parent2Id)!=token.ownerOf(parent1Id));
require(animalAgainstId[parent1Id].upForMating==true);
uint price=animalAgainstId[parent1Id].priceForMating;
uint OwnerPercentage=animalAgainstId[parent1Id].priceForMating.mul(ownerPerThousandShareForMating);
OwnerPercentage=OwnerPercentage.div(1000);
uint priceWithOwnerPercentage = animalAgainstId[parent1Id].priceForMating.add(OwnerPercentage);
require(msg.value>=priceWithOwnerPercentage);
uint generationnum = 1;
if(animalAgainstId[parent1Id].generationId >= animalAgainstId[parent2Id].generationId)
{
generationnum = animalAgainstId[parent1Id].generationId+1;
}
else{
generationnum = animalAgainstId[parent2Id].generationId+1;
}
animalObject = AnimalProperties({
id:uniqueAnimalId,
name:animalName,
desc:animalDesc,
upForSale: false,
priceForSale:0,
upForMating: false,
eggPhase: true,
priceForMating:0,
isBornByMating:true,
parentId1: parent1Id,
parentId2: parent2Id,
birthdate:now,
costumeId:0,
generationId:generationnum
});
childrenIdAgainstAnimalId[parent2Id].push(uniqueAnimalId);
{
if (upForMatingList[i]==parent1Id)
delete upForMatingList[i];
}
animalAgainstId[parent1Id].priceForMating = 0;
{
msg.sender.transfer(msg.value.sub(priceWithOwnerPercentage));
}
}
function TransferAnimalToAnotherUser(uint animalId,address to) public
{
require (!isContractPaused);
require(msg.sender != 0x0);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].upForSale == false);
require(animalAgainstId[animalId].upForMating == false);
token.safeTransferFrom(msg.sender, to, animalId);
}
function putSaleRequest(uint animalId, uint salePrice) public payable
{
require (!isContractPaused);
if (msg.sender!=owner)
{
require(msg.value>=priceForSaleAdvertisement);
}
animalAgainstId[animalId].priceForSale=salePrice;
upForSaleList.push(animalId);
}
function putSaleRequest(uint animalId, uint salePrice) public payable
{
require (!isContractPaused);
if (msg.sender!=owner)
{
require(msg.value>=priceForSaleAdvertisement);
}
animalAgainstId[animalId].priceForSale=salePrice;
upForSaleList.push(animalId);
}
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].eggPhase==false);
require(animalAgainstId[animalId].upForSale==false);
require(animalAgainstId[animalId].upForMating==false);
animalAgainstId[animalId].upForSale=true;
owner.transfer(msg.value);
function withdrawSaleRequest(uint animalId) public
{
require (!isContractPaused);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].upForSale==true);
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
for (uint i=0;i<upForSaleList.length;i++)
{
if (upForSaleList[i]==animalId)
delete upForSaleList[i];
}
}
function withdrawSaleRequest(uint animalId) public
{
require (!isContractPaused);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].upForSale==true);
animalAgainstId[animalId].upForSale=false;
animalAgainstId[animalId].priceForSale=0;
for (uint i=0;i<upForSaleList.length;i++)
{
if (upForSaleList[i]==animalId)
delete upForSaleList[i];
}
}
function putMatingRequest(uint animalId, uint matePrice) public payable
{
require(!isContractPaused);
if (msg.sender!=owner)
{
require(msg.value>=priceForMateAdvertisement);
}
require(token.ownerOf(animalId)==msg.sender);
animalAgainstId[animalId].upForMating=true;
animalAgainstId[animalId].priceForMating=matePrice;
upForMatingList.push(animalId);
}
function putMatingRequest(uint animalId, uint matePrice) public payable
{
require(!isContractPaused);
if (msg.sender!=owner)
{
require(msg.value>=priceForMateAdvertisement);
}
require(token.ownerOf(animalId)==msg.sender);
animalAgainstId[animalId].upForMating=true;
animalAgainstId[animalId].priceForMating=matePrice;
upForMatingList.push(animalId);
}
require(animalAgainstId[animalId].eggPhase==false);
require(animalAgainstId[animalId].upForSale==false);
require(animalAgainstId[animalId].upForMating==false);
owner.transfer(msg.value);
function withdrawMatingRequest(uint animalId) public
{
require(!isContractPaused);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].upForMating==true);
animalAgainstId[animalId].upForMating=false;
animalAgainstId[animalId].priceForMating=0;
for (uint i=0;i<upForMatingList.length;i++)
{
if (upForMatingList[i]==animalId)
delete upForMatingList[i];
}
}
function withdrawMatingRequest(uint animalId) public
{
require(!isContractPaused);
require(token.ownerOf(animalId)==msg.sender);
require(animalAgainstId[animalId].upForMating==true);
animalAgainstId[animalId].upForMating=false;
animalAgainstId[animalId].priceForMating=0;
for (uint i=0;i<upForMatingList.length;i++)
{
if (upForMatingList[i]==animalId)
delete upForMatingList[i];
}
}
function validPurchase() internal constant returns (bool)
{
if(msg.value.div(weiPerAnimal)<1)
return false;
uint quotient=msg.value.div(weiPerAnimal);
uint actualVal=quotient.mul(weiPerAnimal);
if(msg.value>actualVal)
return false;
else
return true;
}
function showMyAnimalBalance() public view returns (uint256 tokenBalance)
{
tokenBalance = token.balanceOf(msg.sender);
}
function setPriceRate(uint256 newPrice) public onlyOwner returns (bool)
{
weiPerAnimal = newPrice;
}
function setMateAdvertisementRate(uint256 newPrice) public onlyOwner returns (bool)
{
priceForMateAdvertisement = newPrice;
}
function setSaleAdvertisementRate(uint newPrice) public onlyOwner returns (bool)
{
priceForSaleAdvertisement = newPrice;
}
function setBuyingCostumeRate(uint newPrice) public onlyOwner returns (bool)
{
priceForBuyingCostume = newPrice;
}
function getAllMatingAnimals() public constant returns (uint[])
{
return upForMatingList;
}
function getAllSaleAnimals() public constant returns (uint[])
{
return upForSaleList;
}
function changeFreeAnimalsLimit(uint limit) public onlyOwner
{
freeAnimalsLimit = limit;
}
function changeOwnerSharePerThousandForBuying(uint buyshare) public onlyOwner
{
ownerPerThousandShareForBuying = buyshare;
}
function changeOwnerSharePerThousandForMating(uint mateshare) public onlyOwner
{
ownerPerThousandShareForMating = mateshare;
}
function pauseContract(bool isPaused) public onlyOwner
{
isContractPaused = isPaused;
}
function removeFromEggPhase(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<eggPhaseAnimalIds.length;j++)
{
if (eggPhaseAnimalIds[j]==animalId)
{
delete eggPhaseAnimalIds[j];
}
}
animalAgainstId[animalId].eggPhase = false;
}
}
}
function removeFromEggPhase(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<eggPhaseAnimalIds.length;j++)
{
if (eggPhaseAnimalIds[j]==animalId)
{
delete eggPhaseAnimalIds[j];
}
}
animalAgainstId[animalId].eggPhase = false;
}
}
}
function removeFromEggPhase(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<eggPhaseAnimalIds.length;j++)
{
if (eggPhaseAnimalIds[j]==animalId)
{
delete eggPhaseAnimalIds[j];
}
}
animalAgainstId[animalId].eggPhase = false;
}
}
}
function removeFromEggPhase(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<eggPhaseAnimalIds.length;j++)
{
if (eggPhaseAnimalIds[j]==animalId)
{
delete eggPhaseAnimalIds[j];
}
}
animalAgainstId[animalId].eggPhase = false;
}
}
}
function removeFromEggPhase(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<eggPhaseAnimalIds.length;j++)
{
if (eggPhaseAnimalIds[j]==animalId)
{
delete eggPhaseAnimalIds[j];
}
}
animalAgainstId[animalId].eggPhase = false;
}
}
}
function getChildrenAgainstAnimalId(uint id) public constant returns (uint[])
{
return childrenIdAgainstAnimalId[id];
}
function getEggPhaseList() public constant returns (uint[])
{
return eggPhaseAnimalIds;
}
function getAnimalIdsWithPendingCostume() public constant returns (uint[])
{
return animalIdsWithPendingCostumes;
}
function buyCostume(uint cId, uint aId) public payable
{
require(msg.value>=priceForBuyingCostume);
require(!isContractPaused);
require(token.ownerOf(aId)==msg.sender);
require(animalAgainstId[aId].costumeId==0);
animalAgainstId[aId].costumeId=cId;
animalIdsWithPendingCostumes.push(aId);
owner.transfer(msg.value);
}
function approvePendingCostume(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingCostumes.length;j++)
{
if (animalIdsWithPendingCostumes[j]==animalId)
{
delete animalIdsWithPendingCostumes[j];
}
}
}
}
}
function approvePendingCostume(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingCostumes.length;j++)
{
if (animalIdsWithPendingCostumes[j]==animalId)
{
delete animalIdsWithPendingCostumes[j];
}
}
}
}
}
function approvePendingCostume(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingCostumes.length;j++)
{
if (animalIdsWithPendingCostumes[j]==animalId)
{
delete animalIdsWithPendingCostumes[j];
}
}
}
}
}
function approvePendingCostume(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingCostumes.length;j++)
{
if (animalIdsWithPendingCostumes[j]==animalId)
{
delete animalIdsWithPendingCostumes[j];
}
}
}
}
}
function approvePendingCostume(uint animalId) public
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==msg.sender)
{
for (uint j=0;j<animalIdsWithPendingCostumes.length;j++)
{
if (animalIdsWithPendingCostumes[j]==animalId)
{
delete animalIdsWithPendingCostumes[j];
}
}
}
}
}
function addMember(address member) public onlyOwner
{
memberAddresses.push(member);
}
function listMembers() public constant returns (address[])
{
return memberAddresses;
}
function deleteMember(address member) public onlyOwner
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==member)
{
delete memberAddresses[i];
}
}
}
function deleteMember(address member) public onlyOwner
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==member)
{
delete memberAddresses[i];
}
}
}
function deleteMember(address member) public onlyOwner
{
for (uint i=0;i<memberAddresses.length;i++)
{
if (memberAddresses[i]==member)
{
delete memberAddresses[i];
}
}
}
function updateAnimal(uint animalId, string name, string desc) public
{
require(msg.sender==token.ownerOf(animalId));
animalAgainstId[animalId].name=name;
animalAgainstId[animalId].desc=desc;
token.setAnimalMeta(animalId, name);
}
}
| 11,440,486 |
./full_match/1/0xd2aa885f3231CbB7763450E94b79B9fc4d101D03/sources/browser/Power.sol
|
/ If x >= 2, then we compute the integer part of log2(x), which is larger than 0. If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
|
This functions assumes that "x >= FIXED_1", because the output would be negative otherwise.
function generalLog(uint256 _x) internal pure returns (uint256) {
uint256 res = 0;
uint256 x = _x;
if (x >= FIXED_2) {
uint8 count = floorLog2(x / FIXED_1);
res = count * FIXED_1;
}
if (x > FIXED_1) {
for (uint8 i = MAX_PRECISION; i > 0; --i) {
if (x >= FIXED_2) {
res += ONE << (i - 1);
}
}
}
return res * LN2_NUMERATOR / LN2_DENOMINATOR;
}
| 2,982,865 |
./full_match/80001/0xb022b7A15d6a499BC6F4Ee6257Cc35fD013b5269/sources/src/web3/contracts/Market.sol
|
create a MarketItem for NFT sale on the marketplace. List an NFT./ change to approve mechanism from the original direct transfer to marketIERC721(nftContract).transferFrom(msg.sender, address(this), tokenId);
|
function createMarketItem(
address nftContract,
uint256 tokenId,
uint256 price
) public payable nonReentrant {
require(price > 0, "Price must be at least 1 wei");
require(msg.value == listingFee, "Fee must be equal to listing fee");
require(IERC721(nftContract).getApproved(tokenId) == address(this), "NFT must be approved to market");
_itemCounter.increment();
uint256 id = _itemCounter.current();
marketItems[id] = MarketItem(
id,
nftContract,
tokenId,
payable(msg.sender),
payable(address(0)),
price,
State.Created
);
emit MarketItemCreated(
id,
nftContract,
tokenId,
msg.sender,
address(0),
price,
State.Created
);
}
| 849,353 |
pragma solidity ^0.4.17;
// ----------------------------------------------------------------------------
// Token Trustee Implementation
//
// Copyright (c) 2017 OpenST Ltd.
// https://simpletoken.org/
//
// The MIT Licence.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// SafeMath Library Implementation
//
// Copyright (c) 2017 OpenST Ltd.
// https://simpletoken.org/
//
// The MIT Licence.
//
// Based on the SafeMath library by the OpenZeppelin team.
// Copyright (c) 2016 Smart Contract Solutions, Inc.
// https://github.com/OpenZeppelin/zeppelin-solidity
// The MIT License.
// ----------------------------------------------------------------------------
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// 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;
}
}
//
// Implements basic ownership with 2-step transfers.
//
contract Owned {
address public owner;
address public proposedOwner;
event OwnershipTransferInitiated(address indexed _proposedOwner);
event OwnershipTransferCompleted(address indexed _newOwner);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(isOwner(msg.sender));
_;
}
function isOwner(address _address) internal view returns (bool) {
return (_address == owner);
}
function initiateOwnershipTransfer(address _proposedOwner) public onlyOwner returns (bool) {
proposedOwner = _proposedOwner;
OwnershipTransferInitiated(_proposedOwner);
return true;
}
function completeOwnershipTransfer() public returns (bool) {
require(msg.sender == proposedOwner);
owner = proposedOwner;
proposedOwner = address(0);
OwnershipTransferCompleted(owner);
return true;
}
}
//
// Implements a more advanced ownership and permission model based on owner,
// admin and ops per Simple Token key management specification.
//
contract OpsManaged is Owned {
address public opsAddress;
address public adminAddress;
event AdminAddressChanged(address indexed _newAddress);
event OpsAddressChanged(address indexed _newAddress);
function OpsManaged() public
Owned()
{
}
modifier onlyAdmin() {
require(isAdmin(msg.sender));
_;
}
modifier onlyAdminOrOps() {
require(isAdmin(msg.sender) || isOps(msg.sender));
_;
}
modifier onlyOwnerOrAdmin() {
require(isOwner(msg.sender) || isAdmin(msg.sender));
_;
}
modifier onlyOps() {
require(isOps(msg.sender));
_;
}
function isAdmin(address _address) internal view returns (bool) {
return (adminAddress != address(0) && _address == adminAddress);
}
function isOps(address _address) internal view returns (bool) {
return (opsAddress != address(0) && _address == opsAddress);
}
function isOwnerOrOps(address _address) internal view returns (bool) {
return (isOwner(_address) || isOps(_address));
}
// Owner and Admin can change the admin address. Address can also be set to 0 to 'disable' it.
function setAdminAddress(address _adminAddress) external onlyOwnerOrAdmin returns (bool) {
require(_adminAddress != owner);
require(_adminAddress != address(this));
require(!isOps(_adminAddress));
adminAddress = _adminAddress;
AdminAddressChanged(_adminAddress);
return true;
}
// Owner and Admin can change the operations address. Address can also be set to 0 to 'disable' it.
function setOpsAddress(address _opsAddress) external onlyOwnerOrAdmin returns (bool) {
require(_opsAddress != owner);
require(_opsAddress != address(this));
require(!isAdmin(_opsAddress));
opsAddress = _opsAddress;
OpsAddressChanged(_opsAddress);
return true;
}
}
contract SimpleTokenConfig {
string public constant TOKEN_SYMBOL = "ST";
string public constant TOKEN_NAME = "Simple Token";
uint8 public constant TOKEN_DECIMALS = 18;
uint256 public constant DECIMALSFACTOR = 10**uint256(TOKEN_DECIMALS);
uint256 public constant TOKENS_MAX = 800000000 * DECIMALSFACTOR;
}
contract ERC20Interface {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function name() public view returns (string);
function symbol() public view returns (string);
function decimals() public view returns (uint8);
function totalSupply() public view returns (uint256);
function balanceOf(address _owner) public view returns (uint256 balance);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
//
// Standard ERC20 implementation, with ownership.
//
contract ERC20Token is ERC20Interface, Owned {
using SafeMath for uint256;
string private tokenName;
string private tokenSymbol;
uint8 private tokenDecimals;
uint256 internal tokenTotalSupply;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
function ERC20Token(string _symbol, string _name, uint8 _decimals, uint256 _totalSupply) public
Owned()
{
tokenSymbol = _symbol;
tokenName = _name;
tokenDecimals = _decimals;
tokenTotalSupply = _totalSupply;
balances[owner] = _totalSupply;
// According to the ERC20 standard, a token contract which creates new tokens should trigger
// a Transfer event and transfers of 0 values must also fire the event.
Transfer(0x0, owner, _totalSupply);
}
function name() public view returns (string) {
return tokenName;
}
function symbol() public view returns (string) {
return tokenSymbol;
}
function decimals() public view returns (uint8) {
return tokenDecimals;
}
function totalSupply() public view returns (uint256) {
return tokenTotalSupply;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) public returns (bool success) {
// According to the EIP20 spec, "transfers of 0 values MUST be treated as normal
// transfers and fire the Transfer event".
// Also, should throw if not enough balance. This is taken care of by SafeMath.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
//
// SimpleToken is a standard ERC20 token with some additional functionality:
// - It has a concept of finalize
// - Before finalize, nobody can transfer tokens except:
// - Owner and operations can transfer tokens
// - Anybody can send back tokens to owner
// - After finalize, no restrictions on token transfers
//
//
// Permissions, according to the ST key management specification.
//
// Owner Admin Ops
// transfer (before finalize) x x
// transferForm (before finalize) x x
// finalize x
//
contract SimpleToken is ERC20Token, OpsManaged, SimpleTokenConfig {
bool public finalized;
// Events
event Burnt(address indexed _from, uint256 _amount);
event Finalized();
function SimpleToken() public
ERC20Token(TOKEN_SYMBOL, TOKEN_NAME, TOKEN_DECIMALS, TOKENS_MAX)
OpsManaged()
{
finalized = false;
}
// Implementation of the standard transfer method that takes into account the finalize flag.
function transfer(address _to, uint256 _value) public returns (bool success) {
checkTransferAllowed(msg.sender, _to);
return super.transfer(_to, _value);
}
// Implementation of the standard transferFrom method that takes into account the finalize flag.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
checkTransferAllowed(msg.sender, _to);
return super.transferFrom(_from, _to, _value);
}
function checkTransferAllowed(address _sender, address _to) private view {
if (finalized) {
// Everybody should be ok to transfer once the token is finalized.
return;
}
// Owner and Ops are allowed to transfer tokens before the sale is finalized.
// This allows the tokens to move from the TokenSale contract to a beneficiary.
// We also allow someone to send tokens back to the owner. This is useful among other
// cases, for the Trustee to transfer unlocked tokens back to the owner (reclaimTokens).
require(isOwnerOrOps(_sender) || _to == owner);
}
// Implement a burn function to permit msg.sender to reduce its balance
// which also reduces tokenTotalSupply
function burn(uint256 _value) public returns (bool success) {
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
tokenTotalSupply = tokenTotalSupply.sub(_value);
Burnt(msg.sender, _value);
return true;
}
// Finalize method marks the point where token transfers are finally allowed for everybody.
function finalize() external onlyAdmin returns (bool success) {
require(!finalized);
finalized = true;
Finalized();
return true;
}
}
//
// Implements a simple trustee which can release tokens based on
// an explicit call from the owner.
//
//
// Permissions, according to the ST key management specification.
//
// Owner Admin Ops Revoke
// grantAllocation x x
// revokeAllocation x
// processAllocation x
// reclaimTokens x
// setRevokeAddress x x
//
contract Trustee is OpsManaged {
using SafeMath for uint256;
SimpleToken public tokenContract;
struct Allocation {
uint256 amountGranted;
uint256 amountTransferred;
bool revokable;
}
// The trustee has a special 'revoke' key which is allowed to revoke allocations.
address public revokeAddress;
// Total number of tokens that are currently allocated.
// This does not include tokens that have been processed (sent to an address) already or
// the ones in the trustee's account that have not been allocated yet.
uint256 public totalLocked;
mapping (address => Allocation) public allocations;
//
// Events
//
event AllocationGranted(address indexed _from, address indexed _account, uint256 _amount, bool _revokable);
event AllocationRevoked(address indexed _from, address indexed _account, uint256 _amountRevoked);
event AllocationProcessed(address indexed _from, address indexed _account, uint256 _amount);
event RevokeAddressChanged(address indexed _newAddress);
event TokensReclaimed(uint256 _amount);
function Trustee(SimpleToken _tokenContract) public
OpsManaged()
{
require(address(_tokenContract) != address(0));
tokenContract = _tokenContract;
}
modifier onlyOwnerOrRevoke() {
require(isOwner(msg.sender) || isRevoke(msg.sender));
_;
}
modifier onlyRevoke() {
require(isRevoke(msg.sender));
_;
}
function isRevoke(address _address) private view returns (bool) {
return (revokeAddress != address(0) && _address == revokeAddress);
}
// Owner and revoke can change the revoke address. Address can also be set to 0 to 'disable' it.
function setRevokeAddress(address _revokeAddress) external onlyOwnerOrRevoke returns (bool) {
require(_revokeAddress != owner);
require(!isAdmin(_revokeAddress));
require(!isOps(_revokeAddress));
revokeAddress = _revokeAddress;
RevokeAddressChanged(_revokeAddress);
return true;
}
// Allows admin or ops to create new allocations for a specific account.
function grantAllocation(address _account, uint256 _amount, bool _revokable) public onlyAdminOrOps returns (bool) {
require(_account != address(0));
require(_account != address(this));
require(_amount > 0);
// Can't create an allocation if there is already one for this account.
require(allocations[_account].amountGranted == 0);
if (isOps(msg.sender)) {
// Once the token contract is finalized, the ops key should not be able to grant allocations any longer.
// Before finalized, it is used by the TokenSale contract to allocate pre-sales.
require(!tokenContract.finalized());
}
totalLocked = totalLocked.add(_amount);
require(totalLocked <= tokenContract.balanceOf(address(this)));
allocations[_account] = Allocation({
amountGranted : _amount,
amountTransferred : 0,
revokable : _revokable
});
AllocationGranted(msg.sender, _account, _amount, _revokable);
return true;
}
// Allows the revoke key to revoke allocations, if revoke is allowed.
function revokeAllocation(address _account) external onlyRevoke returns (bool) {
require(_account != address(0));
Allocation memory allocation = allocations[_account];
require(allocation.revokable);
uint256 ownerRefund = allocation.amountGranted.sub(allocation.amountTransferred);
delete allocations[_account];
totalLocked = totalLocked.sub(ownerRefund);
AllocationRevoked(msg.sender, _account, ownerRefund);
return true;
}
// Push model which allows ops to transfer tokens to the beneficiary.
// The exact amount to transfer is calculated based on agreements with
// the beneficiaries. Here we only restrict that the total amount transfered cannot
// exceed what has been granted.
function processAllocation(address _account, uint256 _amount) external onlyOps returns (bool) {
require(_account != address(0));
require(_amount > 0);
Allocation storage allocation = allocations[_account];
require(allocation.amountGranted > 0);
uint256 transferable = allocation.amountGranted.sub(allocation.amountTransferred);
if (transferable < _amount) {
return false;
}
allocation.amountTransferred = allocation.amountTransferred.add(_amount);
// Note that transfer will fail if the token contract has not been finalized yet.
require(tokenContract.transfer(_account, _amount));
totalLocked = totalLocked.sub(_amount);
AllocationProcessed(msg.sender, _account, _amount);
return true;
}
// Allows the admin to claim back all tokens that are not currently allocated.
// Note that the trustee should be able to move tokens even before the token is
// finalized because SimpleToken allows sending back to owner specifically.
function reclaimTokens() external onlyAdmin returns (bool) {
uint256 ownBalance = tokenContract.balanceOf(address(this));
// If balance <= amount locked, there is nothing to reclaim.
require(ownBalance > totalLocked);
uint256 amountReclaimed = ownBalance.sub(totalLocked);
address tokenOwner = tokenContract.owner();
require(tokenOwner != address(0));
require(tokenContract.transfer(tokenOwner, amountReclaimed));
TokensReclaimed(amountReclaimed);
return true;
}
}
|
Push model which allows ops to transfer tokens to the beneficiary. The exact amount to transfer is calculated based on agreements with the beneficiaries. Here we only restrict that the total amount transfered cannot exceed what has been granted.
|
function processAllocation(address _account, uint256 _amount) external onlyOps returns (bool) {
require(_account != address(0));
require(_amount > 0);
Allocation storage allocation = allocations[_account];
require(allocation.amountGranted > 0);
uint256 transferable = allocation.amountGranted.sub(allocation.amountTransferred);
if (transferable < _amount) {
return false;
}
allocation.amountTransferred = allocation.amountTransferred.add(_amount);
totalLocked = totalLocked.sub(_amount);
AllocationProcessed(msg.sender, _account, _amount);
return true;
}
| 12,781,055 |
/**
*Submitted for verification at Etherscan.io on 2021-05-14
*/
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: ICurveFi
interface ICurveFi {
function calc_withdraw_one_coin(uint256, int128) external view returns(uint256);
function remove_liquidity_one_coin(uint256, int128, uint256) external;
}
// Part: ISwap
interface ISwap {
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external;
function getAmountsOut(uint amountIn, address[] memory path) external view returns (uint[] memory amounts);
}
// Part: IVoterProxy
interface IVoterProxy {
function lock() external;
}
// Part: IyveCRV
interface IyveCRV {
function claimable(address) external view returns(uint256);
function supplyIndex(address) external view returns(uint256);
function balanceOf(address) external view returns(uint256);
function index() external view returns(uint256);
function claim() external;
function depositAll() 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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// 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, 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;
}
}
// 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: iearn-finance/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: iearn-finance/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.3.5";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external virtual view returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external virtual view returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public virtual view returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCost The keeper's estimated cast cost to call `tend()`.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCost) public virtual view returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost) public virtual view returns (bool) {
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by governance or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance());
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal virtual view returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// File: Strategy.sol
contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
address public constant yvBoost = address(0x9d409a0A012CFbA9B15F6D4B36Ac57A46966Ab9a);
address public constant crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52);
address public constant usdc = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
address public constant crv3 = address(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490);
address public constant crv3Pool = address(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);
address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address public constant sushiswap = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
address public constant ethCrvPair = address(0x58Dc5a51fE44589BEb22E8CE67720B5BC5378009); // Sushi
address public constant ethYvBoostPair = address(0x9461173740D27311b176476FA27e94C681b1Ea6b); // Sushi
address public constant ethUsdcPair = address(0x397FF1542f962076d0BFE58eA045FfA2d347ACa0);
address public proxy = address(0xA420A63BbEFfbda3B147d0585F1852C358e2C152);
// Configurable preference for locking CRV in vault vs market-buying yvBOOST.
// Default: Buy only when yvBOOST price becomes > 3% price of CRV
uint256 public vaultBuffer = 30;
uint256 public constant DENOMINATOR = 1000;
event UpdatedBuffer(uint256 newBuffer);
event BuyOrMint(bool shouldMint, uint256 projBuyAmount, uint256 projMintAmount);
constructor(address _vault) public BaseStrategy(_vault) {
// You can set these parameters on deployment to whatever you want
IERC20(crv).safeApprove(address(want), type(uint256).max);
IERC20(usdc).safeApprove(sushiswap, type(uint256).max);
}
function name() external view override returns (string memory) {
return "StrategyYearnVECRV";
}
function estimatedTotalAssets() public view override returns (uint256) {
uint256 _totalAssets = want.balanceOf(address(this));
uint256 claimable = getClaimable3Crv();
if(claimable > 0){
uint256 stable = quoteWithdrawFrom3Crv(claimable); // Calculate withdrawal amount
if(stable > 0){ // Quote will revert if amount is < 1
uint256 estveCrv = quote(usdc, address(want), stable);
_totalAssets = _totalAssets.add(estveCrv);
}
}
return _totalAssets;
}
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
if (_debtOutstanding > 0) {
(_debtPayment, _loss) = liquidatePosition(_debtOutstanding);
}
// Figure out how much want we have
uint256 claimable = getClaimable3Crv();
claimable = claimable > 0 ? claimable : IERC20(crv3).balanceOf(address(this)); // We do this to make testing harvest easier
if (claimable > 0) {
IyveCRV(address(want)).claim();
withdrawFrom3CrvToUSDC(); // Convert 3crv to USDC
uint256 usdcBalance = IERC20(usdc).balanceOf(address(this));
if(usdcBalance > 1e6){ // Don't bother to swap small amounts
uint256 profit = 0;
uint256 balanceBefore = want.balanceOf(address(this));
// Aquire yveCRV either via mint or market-buy
if(shouldMint(usdcBalance)){
swap(usdc, crv, usdcBalance);
deposityveCRV(); // Mint yveCRV
profit = want.balanceOf(address(this)).sub(balanceBefore);
}
else{
// Avoid rugging strategists
uint256 strategistRewards = vault.balanceOf(address(this));
swap(usdc, yvBoost, usdcBalance);
uint256 swapGain = vault.balanceOf(address(this)).sub(strategistRewards);
if(vault.balanceOf(address(this)) > 0){
// Here we get our profit by burning yvBOOST shares on withdraw.
// It would be incorrect to calculate profit by taking a diff on before/after "want"
// balance. This is because the "want" balance of the strategy will be unchanged
// after withdrawing to itself. Profits we realize here come frome burning shares.
profit = vault.withdraw(swapGain);
}
}
_profit = profit;
}
}
}
// Here we lock curve in the voter contract. Lock doesn't require approval.
function adjustPosition(uint256 _debtOutstanding) internal override {
IVoterProxy(proxy).lock();
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 totalAssets = want.balanceOf(address(this));
if (_amountNeeded > totalAssets) {
_liquidatedAmount = totalAssets;
_loss = _amountNeeded.sub(totalAssets);
} else {
_liquidatedAmount = _amountNeeded;
}
}
// NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary
function prepareMigration(address _newStrategy) internal override {
uint256 balance3crv = IERC20(crv3).balanceOf(address(this));
uint256 balanceYveCrv = IERC20(address(want)).balanceOf(address(this));
if(balance3crv > 0){
IERC20(crv3).safeTransfer(_newStrategy, balance3crv);
}
if(balanceYveCrv > 0){
IERC20(address(want)).safeTransfer(_newStrategy, balanceYveCrv);
}
IERC20(crv).safeApprove(address(want), 0);
IERC20(usdc).safeApprove(sushiswap, 0);
}
// Here we determine if better to market-buy yvBOOST or mint it via backscratcher
function shouldMint(uint256 _amountIn) internal returns (bool) {
// Using reserve ratios of swap pairs will allow us to compare whether it's more efficient to:
// 1) Buy yvBOOST (unwrapped for yveCRV)
// 2) Buy CRV (and use to mint yveCRV 1:1)
address[] memory path = new address[](3);
path[0] = usdc;
path[1] = weth;
path[2] = yvBoost;
uint256[] memory amounts = ISwap(sushiswap).getAmountsOut(_amountIn, path);
uint256 projectedYvBoost = amounts[2];
// Convert yvBOOST to yveCRV
uint256 projectedYveCrv = projectedYvBoost.mul(vault.pricePerShare()).div(1e18); // save some gas by hardcoding 1e18
path = new address[](3);
path[0] = usdc;
path[1] = weth;
path[2] = crv;
amounts = ISwap(sushiswap).getAmountsOut(_amountIn, path);
uint256 projectedCrv = amounts[2];
// Here we favor minting by a % value defined by "vaultBuffer"
bool shouldMint = projectedCrv.mul(DENOMINATOR.add(vaultBuffer)).div(DENOMINATOR) > projectedYveCrv;
emit BuyOrMint(shouldMint, projectedYveCrv, projectedCrv);
return shouldMint;
}
function withdrawFrom3CrvToUSDC() internal {
uint256 amount = IERC20(crv3).balanceOf(address(this));
ICurveFi(crv3Pool).remove_liquidity_one_coin(amount, 1, 0);
}
function quoteWithdrawFrom3Crv(uint256 _amount) internal view returns(uint256) {
return ICurveFi(crv3Pool).calc_withdraw_one_coin(_amount, 1);
}
function quote(address token_in, address token_out, uint256 amount_in) internal view returns (uint256) {
bool is_weth = token_in == weth || token_out == weth;
address[] memory path = new address[](is_weth ? 2 : 3);
path[0] = token_in;
if (is_weth) {
path[1] = token_out;
} else {
path[1] = weth;
path[2] = token_out;
}
uint256[] memory amounts = ISwap(sushiswap).getAmountsOut(amount_in, path);
return amounts[amounts.length - 1];
}
function getClaimable3Crv() public view returns (uint256) {
IyveCRV YveCrv = IyveCRV(address(want));
uint256 claimable = YveCrv.claimable(address(this));
uint256 claimableToAdd = (YveCrv.index().sub(YveCrv.supplyIndex(address(this))))
.mul(YveCrv.balanceOf(address(this)))
.div(1e18);
return claimable.mul(1e18).add(claimableToAdd);
}
// Common API used to update Yearn's StrategyProxy if needed in case of upgrades.
function setProxy(address _proxy) external onlyGovernance {
proxy = _proxy;
}
function swap(address token_in, address token_out, uint amount_in) internal {
bool is_weth = token_in == weth || token_out == weth;
address[] memory path = new address[](is_weth ? 2 : 3);
path[0] = token_in;
if (is_weth) {
path[1] = token_out;
} else {
path[1] = weth;
path[2] = token_out;
}
ISwap(sushiswap).swapExactTokensForTokens(
amount_in,
0,
path,
address(this),
now
);
}
function deposityveCRV() internal {
IyveCRV(address(want)).depositAll();
}
function setBuffer(uint256 _newBuffer) external onlyGovernance {
require(_newBuffer < DENOMINATOR, "!TooHigh");
vaultBuffer = _newBuffer;
emit UpdatedBuffer(_newBuffer);
}
function restoreApprovals() external onlyGovernance {
IERC20(crv).safeApprove(address(want), 0); // CRV must go to zero first before increase
IERC20(usdc).safeApprove(sushiswap, 0); // USDC must go to zero first before increase
IERC20(crv).safeApprove(address(want), type(uint256).max);
IERC20(usdc).safeApprove(sushiswap, type(uint256).max);
}
// internal helpers
function protectedTokens()
internal
view
override
returns (address[] memory)
{
address[] memory protected = new address[](2);
protected[0] = crv3;
protected[1] = usdc;
return protected;
}
}
|
Here we determine if better to market-buy yvBOOST or mint it via backscratcher Using reserve ratios of swap pairs will allow us to compare whether it's more efficient to: 1) Buy yvBOOST (unwrapped for yveCRV) 2) Buy CRV (and use to mint yveCRV 1:1) Convert yvBOOST to yveCRV Here we favor minting by a % value defined by "vaultBuffer"
|
function shouldMint(uint256 _amountIn) internal returns (bool) {
address[] memory path = new address[](3);
path[0] = usdc;
path[1] = weth;
path[2] = yvBoost;
uint256[] memory amounts = ISwap(sushiswap).getAmountsOut(_amountIn, path);
uint256 projectedYvBoost = amounts[2];
path = new address[](3);
path[0] = usdc;
path[1] = weth;
path[2] = crv;
amounts = ISwap(sushiswap).getAmountsOut(_amountIn, path);
uint256 projectedCrv = amounts[2];
bool shouldMint = projectedCrv.mul(DENOMINATOR.add(vaultBuffer)).div(DENOMINATOR) > projectedYveCrv;
emit BuyOrMint(shouldMint, projectedYveCrv, projectedCrv);
return shouldMint;
}
| 15,230,354 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IERC20 {
function TOTALSUPPLY267() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF771(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER36(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE520(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE275(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER513(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL255(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD260(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB684(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB684(a, b, "SafeMath: subtraction overflow");
}
function SUB684(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL872(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV551(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV551(a, b, "SafeMath: division by zero");
}
function DIV551(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
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;
}
function MOD699(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD699(a, b, "SafeMath: modulo by zero");
}
function MOD699(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT292(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
function SENDVALUE986(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
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");
}
function FUNCTIONCALL437(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL437(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL437(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE654(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE142(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE142(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE142(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE654(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE654(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT292(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);
}
}
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER627(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.TRANSFER36.selector, to, value));
}
function SAFETRANSFERFROM565(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.TRANSFERFROM54.selector, from, to, value));
}
function SAFEAPPROVE47(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// 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.ALLOWANCE520(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, value));
}
function SAFEINCREASEALLOWANCE824(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE520(address(this), spender).ADD260(value);
_CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE914(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE520(address(this), spender).SUB684(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN808(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// 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).FUNCTIONCALL437(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");
}
}
}
interface IMultiVaultStrategy {
function WANT777() external view returns (address); //inject NONSTANDARD NAMING
function DEPOSIT294() external; //inject NONSTANDARD NAMING
function WITHDRAW808(address _asset) external; //inject NONSTANDARD NAMING
function WITHDRAW808(uint _amount) external returns (uint); //inject NONSTANDARD NAMING
function WITHDRAWTOCONTROLLER653(uint _amount) external; //inject NONSTANDARD NAMING
function SKIM294() external; //inject NONSTANDARD NAMING
function HARVEST506(address _mergedStrategy) external; //inject NONSTANDARD NAMING
function WITHDRAWALL927() external returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF771() external view returns (uint); //inject NONSTANDARD NAMING
function WITHDRAWFEE692(uint) external view returns (uint); // pJar: 0.5% (50/10000) //inject NONSTANDARD NAMING
}
interface IValueMultiVault {
function CAP418() external view returns (uint); //inject NONSTANDARD NAMING
function GETCONVERTER215(address _want) external view returns (address); //inject NONSTANDARD NAMING
function GETVAULTMASTER236() external view returns (address); //inject NONSTANDARD NAMING
function BALANCE180() external view returns (uint); //inject NONSTANDARD NAMING
function TOKEN385() external view returns (address); //inject NONSTANDARD NAMING
function AVAILABLE930(address _want) external view returns (uint); //inject NONSTANDARD NAMING
function ACCEPT281(address _input) external view returns (bool); //inject NONSTANDARD NAMING
function CLAIMINSURANCE45() external; //inject NONSTANDARD NAMING
function EARN427(address _want) external; //inject NONSTANDARD NAMING
function HARVEST506(address reserve, uint amount) external; //inject NONSTANDARD NAMING
function WITHDRAW_FEE118(uint _shares) external view returns (uint); //inject NONSTANDARD NAMING
function CALC_TOKEN_AMOUNT_DEPOSIT453(uint[] calldata _amounts) external view returns (uint); //inject NONSTANDARD NAMING
function CALC_TOKEN_AMOUNT_WITHDRAW2(uint _shares, address _output) external view returns (uint); //inject NONSTANDARD NAMING
function CONVERT_RATE825(address _input, uint _amount) external view returns (uint); //inject NONSTANDARD NAMING
function GETPRICEPERFULLSHARE124() external view returns (uint); //inject NONSTANDARD NAMING
function GET_VIRTUAL_PRICE769() external view returns (uint); // average dollar value of vault share token //inject NONSTANDARD NAMING
function DEPOSIT294(address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING
function DEPOSITFOR247(address _account, address _to, address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING
function DEPOSITALL52(uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING
function DEPOSITALLFOR442(address _account, address _to, uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING
function WITHDRAW808(uint _shares, address _output, uint _min_output_amount) external returns (uint); //inject NONSTANDARD NAMING
function WITHDRAWFOR513(address _account, uint _shares, address _output, uint _min_output_amount) external returns (uint _output_amount); //inject NONSTANDARD NAMING
function HARVESTSTRATEGY825(address _strategy) external; //inject NONSTANDARD NAMING
function HARVESTWANT168(address _want) external; //inject NONSTANDARD NAMING
function HARVESTALLSTRATEGIES334() external; //inject NONSTANDARD NAMING
}
interface IShareConverter {
function CONVERT_SHARES_RATE463(address _input, address _output, uint _inputAmount) external view returns (uint _outputAmount); //inject NONSTANDARD NAMING
function CONVERT_SHARES33(address _input, address _output, uint _inputAmount) external returns (uint _outputAmount); //inject NONSTANDARD NAMING
}
interface Converter {
function CONVERT349(address) external returns (uint); //inject NONSTANDARD NAMING
}
contract MultiStablesVaultController {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
address public governance;
address public strategist;
struct StrategyInfo {
address strategy;
uint quota; // set = 0 to disable
uint percent;
}
IValueMultiVault public vault;
address public basedWant;
address[] public wantTokens; // sorted by preference
// want => quota, length
mapping(address => uint) public wantQuota;
mapping(address => uint) public wantStrategyLength;
// want => stratId => StrategyInfo
mapping(address => mapping(uint => StrategyInfo)) public strategies;
mapping(address => mapping(address => bool)) public approvedStrategies;
mapping(address => bool) public investDisabled;
IShareConverter public shareConverter; // converter for shares (3CRV <-> BCrv, etc ...)
address public lazySelectedBestStrategy; // we pre-set the best strategy to avoid gas cost of iterating the array
constructor(IValueMultiVault _vault) public {
require(address(_vault) != address(0), "!_vault");
vault = _vault;
basedWant = vault.TOKEN385();
governance = msg.sender;
strategist = msg.sender;
}
function SETGOVERNANCE701(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function SETSTRATEGIST330(address _strategist) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
strategist = _strategist;
}
function APPROVESTRATEGY673(address _want, address _strategy) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
approvedStrategies[_want][_strategy] = true;
}
function REVOKESTRATEGY92(address _want, address _strategy) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
approvedStrategies[_want][_strategy] = false;
}
function SETWANTQUOTA716(address _want, uint _quota) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
wantQuota[_want] = _quota;
}
function SETWANTSTRATEGYLENGTH858(address _want, uint _length) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
wantStrategyLength[_want] = _length;
}
// want => stratId => StrategyInfo
function SETSTRATEGYINFO462(address _want, uint _sid, address _strategy, uint _quota, uint _percent) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
require(approvedStrategies[_want][_strategy], "!approved");
strategies[_want][_sid].strategy = _strategy;
strategies[_want][_sid].quota = _quota;
strategies[_want][_sid].percent = _percent;
}
function SETSHARECONVERTER560(IShareConverter _shareConverter) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
shareConverter = _shareConverter;
}
function SETINVESTDISABLED819(address _want, bool _investDisabled) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
investDisabled[_want] = _investDisabled;
}
function SETWANTTOKENS997(address[] memory _wantTokens) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
delete wantTokens;
uint _wlength = _wantTokens.length;
for (uint i = 0; i < _wlength; ++i) {
wantTokens.push(_wantTokens[i]);
}
}
function GETSTRATEGYCOUNT337() external view returns(uint _strategyCount) { //inject NONSTANDARD NAMING
_strategyCount = 0;
uint _wlength = wantTokens.length;
for (uint i = 0; i < _wlength; i++) {
_strategyCount = _strategyCount.ADD260(wantStrategyLength[wantTokens[i]]);
}
}
function WANTLENGTH873() external view returns (uint) { //inject NONSTANDARD NAMING
return wantTokens.length;
}
function WANTSTRATEGYBALANCE73(address _want) public view returns (uint) { //inject NONSTANDARD NAMING
uint _bal = 0;
for (uint _sid = 0; _sid < wantStrategyLength[_want]; _sid++) {
_bal = _bal.ADD260(IMultiVaultStrategy(strategies[_want][_sid].strategy).BALANCEOF771());
}
return _bal;
}
function WANT777() external view returns (address) { //inject NONSTANDARD NAMING
if (lazySelectedBestStrategy != address(0)) {
return IMultiVaultStrategy(lazySelectedBestStrategy).WANT777();
}
uint _wlength = wantTokens.length;
if (_wlength > 0) {
if (_wlength == 1) {
return wantTokens[0];
}
for (uint i = 0; i < _wlength; i++) {
address _want = wantTokens[i];
uint _bal = WANTSTRATEGYBALANCE73(_want);
if (_bal < wantQuota[_want]) {
return _want;
}
}
}
return basedWant;
}
function SETLAZYSELECTEDBESTSTRATEGY629(address _strategy) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
lazySelectedBestStrategy = _strategy;
}
function GETBESTSTRATEGY227(address _want) public view returns (address _strategy) { //inject NONSTANDARD NAMING
if (lazySelectedBestStrategy != address(0) && IMultiVaultStrategy(lazySelectedBestStrategy).WANT777() == _want) {
return lazySelectedBestStrategy;
}
uint _wantStrategyLength = wantStrategyLength[_want];
_strategy = address(0);
if (_wantStrategyLength == 0) return _strategy;
uint _totalBal = WANTSTRATEGYBALANCE73(_want);
if (_totalBal == 0) {
// first depositor, simply return the first strategy
return strategies[_want][0].strategy;
}
uint _bestDiff = 201;
for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) {
StrategyInfo storage sinfo = strategies[_want][_sid];
uint _stratBal = IMultiVaultStrategy(sinfo.strategy).BALANCEOF771();
if (_stratBal < sinfo.quota) {
uint _diff = _stratBal.ADD260(_totalBal).MUL872(100).DIV551(_totalBal).SUB684(sinfo.percent); // [100, 200] - [percent]
if (_diff < _bestDiff) {
_bestDiff = _diff;
_strategy = sinfo.strategy;
}
}
}
if (_strategy == address(0)) {
_strategy = strategies[_want][0].strategy;
}
}
function EARN427(address _token, uint _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist");
address _strategy = GETBESTSTRATEGY227(_token);
if (_strategy == address(0) || IMultiVaultStrategy(_strategy).WANT777() != _token) {
// forward to vault and then call earnExtra() by its governance
IERC20(_token).SAFETRANSFER627(address(vault), _amount);
} else {
IERC20(_token).SAFETRANSFER627(_strategy, _amount);
IMultiVaultStrategy(_strategy).DEPOSIT294();
}
}
function WITHDRAW_FEE118(address _want, uint _amount) external view returns (uint) { //inject NONSTANDARD NAMING
address _strategy = GETBESTSTRATEGY227(_want);
return (_strategy == address(0)) ? 0 : IMultiVaultStrategy(_strategy).WITHDRAWFEE692(_amount);
}
function BALANCEOF771(address _want, bool _sell) external view returns (uint _totalBal) { //inject NONSTANDARD NAMING
uint _wlength = wantTokens.length;
if (_wlength == 0) {
return 0;
}
_totalBal = 0;
for (uint i = 0; i < _wlength; i++) {
address wt = wantTokens[i];
uint _bal = WANTSTRATEGYBALANCE73(wt);
if (wt != _want) {
_bal = shareConverter.CONVERT_SHARES_RATE463(wt, _want, _bal);
if (_sell) {
_bal = _bal.MUL872(9998).DIV551(10000); // minus 0.02% for selling
}
}
_totalBal = _totalBal.ADD260(_bal);
}
}
function WITHDRAWALL927(address _strategy) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
// WithdrawAll sends 'want' to 'vault'
IMultiVaultStrategy(_strategy).WITHDRAWALL927();
}
function INCASETOKENSGETSTUCK116(address _token, uint _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
IERC20(_token).SAFETRANSFER627(address(vault), _amount);
}
function INCASESTRATEGYGETSTUCK927(address _strategy, address _token) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
IMultiVaultStrategy(_strategy).WITHDRAW808(_token);
IERC20(_token).SAFETRANSFER627(address(vault), IERC20(_token).BALANCEOF771(address(this)));
}
function CLAIMINSURANCE45() external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
vault.CLAIMINSURANCE45();
}
// note that some strategies do not allow controller to harvest
function HARVESTSTRATEGY825(address _strategy) external { //inject NONSTANDARD NAMING
require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault");
IMultiVaultStrategy(_strategy).HARVEST506(address(0));
}
function HARVESTWANT168(address _want) external { //inject NONSTANDARD NAMING
require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault");
uint _wantStrategyLength = wantStrategyLength[_want];
address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here
for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) {
StrategyInfo storage sinfo = strategies[_want][_sid];
if (_firstStrategy == address(0)) {
_firstStrategy = sinfo.strategy;
} else {
IMultiVaultStrategy(sinfo.strategy).HARVEST506(_firstStrategy);
}
}
if (_firstStrategy != address(0)) {
IMultiVaultStrategy(_firstStrategy).HARVEST506(address(0));
}
}
function HARVESTALLSTRATEGIES334() external { //inject NONSTANDARD NAMING
require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault");
uint _wlength = wantTokens.length;
address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here
for (uint i = 0; i < _wlength; i++) {
address _want = wantTokens[i];
uint _wantStrategyLength = wantStrategyLength[_want];
for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) {
StrategyInfo storage sinfo = strategies[_want][_sid];
if (_firstStrategy == address(0)) {
_firstStrategy = sinfo.strategy;
} else {
IMultiVaultStrategy(sinfo.strategy).HARVEST506(_firstStrategy);
}
}
}
if (_firstStrategy != address(0)) {
IMultiVaultStrategy(_firstStrategy).HARVEST506(address(0));
}
}
function SWITCHFUND172(IMultiVaultStrategy _srcStrat, IMultiVaultStrategy _destStrat, uint _amount) external { //inject NONSTANDARD NAMING
require(msg.sender == strategist || msg.sender == governance, "!strategist");
_srcStrat.WITHDRAWTOCONTROLLER653(_amount);
address _srcWant = _srcStrat.WANT777();
address _destWant = _destStrat.WANT777();
if (_srcWant != _destWant) {
_amount = IERC20(_srcWant).BALANCEOF771(address(this));
require(shareConverter.CONVERT_SHARES_RATE463(_srcWant, _destWant, _amount) > 0, "rate=0");
IERC20(_srcWant).SAFETRANSFER627(address(shareConverter), _amount);
shareConverter.CONVERT_SHARES33(_srcWant, _destWant, _amount);
}
IERC20(_destWant).SAFETRANSFER627(address(_destStrat), IERC20(_destWant).BALANCEOF771(address(this)));
_destStrat.DEPOSIT294();
}
function WITHDRAW808(address _want, uint _amount) external returns (uint _withdrawFee) { //inject NONSTANDARD NAMING
require(msg.sender == address(vault), "!vault");
_withdrawFee = 0;
uint _toWithdraw = _amount;
uint _wantStrategyLength = wantStrategyLength[_want];
uint _received;
for (uint _sid = _wantStrategyLength; _sid > 0; _sid--) {
StrategyInfo storage sinfo = strategies[_want][_sid - 1];
IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy);
uint _stratBal = _strategy.BALANCEOF771();
if (_toWithdraw < _stratBal) {
_received = _strategy.WITHDRAW808(_toWithdraw);
_withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_received));
return _withdrawFee;
}
_received = _strategy.WITHDRAWALL927();
_withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_received));
if (_received >= _toWithdraw) {
return _withdrawFee;
}
_toWithdraw = _toWithdraw.SUB684(_received);
}
if (_toWithdraw > 0) {
// still not enough, try to withdraw from other wants strategies
uint _wlength = wantTokens.length;
for (uint i = _wlength; i > 0; i--) {
address wt = wantTokens[i - 1];
if (wt != _want) {
(uint _wamt, uint _wdfee) = _WITHDRAWOTHERWANT971(_want, wt, _toWithdraw);
_withdrawFee = _withdrawFee.ADD260(_wdfee);
if (_wamt >= _toWithdraw) {
return _withdrawFee;
}
_toWithdraw = _toWithdraw.SUB684(_wamt);
}
}
}
return _withdrawFee;
}
function _WITHDRAWOTHERWANT971(address _want, address _other, uint _amount) internal returns (uint _wantAmount, uint _withdrawFee) { //inject NONSTANDARD NAMING
// Check balance
uint b = IERC20(_want).BALANCEOF771(address(this));
_withdrawFee = 0;
if (b >= _amount) {
_wantAmount = b;
} else {
uint _toWithdraw = _amount.SUB684(b);
uint _toWithdrawOther = _toWithdraw.MUL872(101).DIV551(100); // add 1% extra
uint _otherBal = IERC20(_other).BALANCEOF771(address(this));
if (_otherBal < _toWithdrawOther) {
uint _otherStrategyLength = wantStrategyLength[_other];
for (uint _sid = _otherStrategyLength; _sid > 0; _sid--) {
StrategyInfo storage sinfo = strategies[_other][_sid - 1];
IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy);
uint _stratBal = _strategy.BALANCEOF771();
uint _needed = _toWithdrawOther.SUB684(_otherBal);
uint _wdamt = (_needed < _stratBal) ? _needed : _stratBal;
_strategy.WITHDRAWTOCONTROLLER653(_wdamt);
_withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_wdamt));
_otherBal = IERC20(_other).BALANCEOF771(address(this));
if (_otherBal >= _toWithdrawOther) {
break;
}
}
}
IERC20(_other).SAFETRANSFER627(address(shareConverter), _otherBal);
shareConverter.CONVERT_SHARES33(_other, _want, _otherBal);
_wantAmount = IERC20(_want).BALANCEOF771(address(this));
}
IERC20(_want).SAFETRANSFER627(address(vault), _wantAmount);
}
}
|
inject NONSTANDARD NAMING
|
function WITHDRAW_FEE118(address _want, uint _amount) external view returns (uint) {
| 13,085,403 |
./full_match/100/0xF2B4E81ba39F5215Db2e05B2F66f482BB8e87FD2/sources/project_/contracts/superfluid/SuperfluidToken.sol
|
ISuperfluidToken.makeLiquidationPayoutsV2 implementation we set the rewardAccount to the user who executed the liquidation if no rewardAccount is set (aka. ANARCHY MODE - should not occur in reality, for testing purposes) LIKELY BRANCH: target account pays penalty to rewarded account LESS LIKELY BRANCH: target account is bailed out NOTE: useDefaultRewardAccount being true is undefined behavior because the default reward account isn't receiving the rewardAmount by default
|
function makeLiquidationPayoutsV2(
bytes32 id,
bytes memory liquidationTypeData,
) external override onlyAgreement {
address rewardAccount = _getRewardAccount();
if (rewardAccount == address(0)) {
rewardAccount = liquidatorAccount;
}
address rewardAmountReceiver = useDefaultRewardAccount ? rewardAccount : liquidatorAccount;
if (targetAccountBalanceDelta <= 0) {
assert(rewardAmount.toInt256() == -targetAccountBalanceDelta);
_balances[rewardAmountReceiver] += rewardAmount.toInt256();
_balances[targetAccount] += targetAccountBalanceDelta;
EventsEmitter.emitTransfer(targetAccount, rewardAmountReceiver, rewardAmount);
assert(!useDefaultRewardAccount);
_balances[rewardAccount] -= (rewardAmount.toInt256() + targetAccountBalanceDelta);
_balances[liquidatorAccount] += rewardAmount.toInt256();
_balances[targetAccount] += targetAccountBalanceDelta;
EventsEmitter.emitTransfer(rewardAccount, liquidatorAccount, rewardAmount);
EventsEmitter.emitTransfer(rewardAccount, targetAccount, uint256(targetAccountBalanceDelta));
}
emit AgreementLiquidatedV2(
msg.sender,
id,
liquidatorAccount,
targetAccount,
rewardAmountReceiver,
rewardAmount,
targetAccountBalanceDelta,
liquidationTypeData
);
}
| 14,278,261 |
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
/**
* @title IFO
* @notice IFO model with 2 pools
*/
contract IFO is ReentrancyGuard, Ownable {
using SafeERC20 for IERC20;
// The deal token used
IERC20 public dealToken;
// The offering token
IERC20 public offeringToken;
// Number of pools
uint8 public constant numberPools = 2;
// The block number when IFO starts
uint256 public startBlock;
// The block number when IFO ends
uint256 public endBlock;
//Tax range by tax overflow given the raisingAmountPool and the totalAmountPool: totalAmountPool / raisingAmountPool
uint256[4] public taxRange;
//Tax percentage by each range. Index[5]: percentage from zero to first range
//100,000,000,000 means 0.1 (10%) / 1 means 0.0000000000001 (0.0000001%) / 1,000,000,000,000 means 1 (100%)
uint256[5] public taxPercent;
// Array of PoolCharacteristics of size numberPools
PoolCharacteristics[numberPools] private _poolInfo;
// It maps the address to pool id to UserInfo
mapping(address => mapping(uint8 => UserInfo)) private _userInfo;
// Struct that contains each pool characteristics
struct PoolCharacteristics {
uint256 raisingAmountPool; // amount of tokens raised for the pool (in deal tokens)
uint256 offeringAmountPool; // amount of tokens offered for the pool (in offeringTokens)
uint256 limitPerUserInDealToken; // limit of tokens per user (if 0, it is ignored)
bool hasTax; // tax on the overflow (if any, it works with _calculateTaxOverflow)
uint256 totalAmountPool; // total amount pool deposited (in deal tokens)
uint256 sumTaxesOverflow; // total taxes collected (starts at 0, increases with each harvest if overflow)
}
// Struct that contains each user information for both pools
struct UserInfo {
uint256 amountPool; // How many tokens the user has provided for pool
bool claimedPool; // Whether the user has claimed (default: false) for pool
}
// Admin withdraw events
event AdminWithdraw(uint256 amountDealToken, uint256 amountOfferingToken);
// Admin recovers token
event AdminTokenRecovery(address tokenAddress, uint256 amountTokens);
// Deposit event
event Deposit(address indexed user, uint256 amount, uint8 indexed pid);
// Harvest event
event Harvest(address indexed user, uint256 offeringAmount, uint256 excessAmount, uint8 indexed pid);
// Event for new start & end blocks
event NewStartAndEndBlocks(uint256 startBlock, uint256 endBlock);
// Event when parameters are set for one of the pools
event PoolParametersSet(uint256 offeringAmountPool, uint256 raisingAmountPool, uint8 pid);
event NewTaxRangeAndPercents(uint256[4] _taxRange, uint256[5] _taxPercent);
// Modifier to prevent contracts to participate
modifier notContract() {
require(!_isContract(msg.sender), "contract not allowed");
require(msg.sender == tx.origin, "proxy contract not allowed");
_;
}
/**
* @notice It initializes the contract (for proxy patterns)
* @dev It can only be called once.
* @param _dealToken: the deal token used
* @param _offeringToken: the token that is offered for the IFO
* @param _startBlock: the start block for the IFO
* @param _endBlock: the end block for the IFO
*/
constructor(
IERC20 _dealToken,
IERC20 _offeringToken,
uint256 _startBlock,
uint256 _endBlock
) {
require(_dealToken != _offeringToken, "Tokens must be different");
require(_startBlock > block.number, "Start block must be older than current");
require(_endBlock > _startBlock, "End block must be older than _startBlock");
dealToken = _dealToken;
offeringToken = _offeringToken;
startBlock = _startBlock;
endBlock = _endBlock;
}
/**
* @notice It allows users to deposit deal tokens to pool
* @param _amount: the number of deal token used (18 decimals)
* @param _pid: pool id
*/
function depositPool(uint256 _amount, uint8 _pid) external nonReentrant notContract {
// Checks whether the pool id is valid
require(_pid < numberPools, "Non valid pool id");
// Checks that pool was set
require(
_poolInfo[_pid].offeringAmountPool > 0 && _poolInfo[_pid].raisingAmountPool > 0,
"Pool not set"
);
// Checks whether the block number is not too early
require(block.number > startBlock, "Too early");
// Checks whether the block number is not too late
require(block.number < endBlock, "Too late");
// Checks that the amount deposited is not inferior to 0
require(_amount > 0, "Amount must be > 0");
// Transfers funds to this contract
dealToken.safeTransferFrom(msg.sender, address(this), _amount);
// Update the user status
_userInfo[msg.sender][_pid].amountPool += _amount;
// Check if the pool has a limit per user
if (_poolInfo[_pid].limitPerUserInDealToken > 0) {
// Checks whether the limit has been reached
require(
_userInfo[msg.sender][_pid].amountPool <= _poolInfo[_pid].limitPerUserInDealToken,
"New amount above user limit"
);
}
// Updates the totalAmount for pool
_poolInfo[_pid].totalAmountPool += _amount;
emit Deposit(msg.sender, _amount, _pid);
}
/**
* @notice It allows users to harvest from pool
* @param _pid: pool id
*/
function harvestPool(uint8 _pid) external nonReentrant notContract {
// Checks whether it is too early to harvest
require(block.number > endBlock, "Too early to harvest");
// Checks whether pool id is valid
require(_pid < numberPools, "Non valid pool id");
// Checks whether the user has participated
require(_userInfo[msg.sender][_pid].amountPool > 0, "Did not participate");
// Checks whether the user has already harvested
require(!_userInfo[msg.sender][_pid].claimedPool, "Has harvested");
_harvestPool(_pid);
}
/**
* @notice It allows users to harvest from all pools
*/
function harvestAllPools() external nonReentrant notContract {
// Checks whether it is too early to harvest
require(block.number > endBlock, "Too early to harvest");
for(uint8 i = 0; i < numberPools; i++){
// Checks whether the user has participated
// Checks whether the user has already harvested
if(_userInfo[msg.sender][i].amountPool > 0 &&
!_userInfo[msg.sender][i].claimedPool
){
_harvestPool(i);
}
}
}
/**
* @notice It allows the admin to set tax range and percentage
* @param _taxRange: 4 elements array with tax ranges
* @param _taxPercent: 4 elements array with tax percentage for each tax range
*/
function setTaxRangeAndPercents(uint256[4] calldata _taxRange, uint256[5] calldata _taxPercent) external onlyOwner {
require(_taxRange[0] > _taxRange[1] && _taxRange[1] > _taxRange[2] && _taxRange[2] > _taxRange[3],
"tax range must be from max to min");
taxRange = _taxRange;
taxPercent = _taxPercent;
emit NewTaxRangeAndPercents(_taxRange, _taxPercent);
}
/**
* @notice It allows the admin to withdraw funds
* @param _dealTokenAmount: the number of deal token to withdraw (18 decimals)
* @param _offerAmount: the number of offering amount to withdraw
* @dev This function is only callable by admin.
*/
function finalWithdraw(uint256 _dealTokenAmount, uint256 _offerAmount) external onlyOwner {
require(_dealTokenAmount <= dealToken.balanceOf(address(this)), "Not enough deal tokens");
require(_offerAmount <= offeringToken.balanceOf(address(this)), "Not enough offering token");
if (_dealTokenAmount > 0) {
dealToken.safeTransfer(msg.sender, _dealTokenAmount);
}
if (_offerAmount > 0) {
offeringToken.safeTransfer(msg.sender, _offerAmount);
}
emit AdminWithdraw(_dealTokenAmount, _offerAmount);
}
/**
* @notice It allows the admin to recover wrong tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw (18 decimals)
* @param _tokenAmount: the number of token amount to withdraw
* @dev This function is only callable by admin.
*/
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(dealToken), "Cannot be deal token");
require(_tokenAddress != address(offeringToken), "Cannot be offering token");
IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
emit AdminTokenRecovery(_tokenAddress, _tokenAmount);
}
/**
* @notice It sets parameters for pool
* @param _offeringAmountPool: offering amount (in tokens)
* @param _raisingAmountPool: raising amount (in deal tokens)
* @param _limitPerUserInDealToken: limit per user (in deal tokens)
* @param _hasTax: if the pool has a tax
* @param _pid: pool id
* @dev This function is only callable by admin.
*/
function setPool(
uint256 _offeringAmountPool,
uint256 _raisingAmountPool,
uint256 _limitPerUserInDealToken,
bool _hasTax,
uint8 _pid
) external onlyOwner {
require(block.number < startBlock, "IFO has started");
require(_pid < numberPools, "Pool does not exist");
_poolInfo[_pid].offeringAmountPool = _offeringAmountPool;
_poolInfo[_pid].raisingAmountPool = _raisingAmountPool;
_poolInfo[_pid].limitPerUserInDealToken = _limitPerUserInDealToken;
_poolInfo[_pid].hasTax = _hasTax;
emit PoolParametersSet(_offeringAmountPool, _raisingAmountPool, _pid);
}
/**
* @notice It allows the admin to update start and end blocks
* @param _startBlock: the new start block
* @param _endBlock: the new end block
* @dev This function is only callable by admin.
*/
function updateStartAndEndBlocks(uint256 _startBlock, uint256 _endBlock) external onlyOwner {
require(block.number < startBlock, "IFO has started");
require(_startBlock < _endBlock, "New startBlock must be lower than new endBlock");
require(block.number < _startBlock, "New startBlock must be higher than current block");
startBlock = _startBlock;
endBlock = _endBlock;
emit NewStartAndEndBlocks(_startBlock, _endBlock);
}
/**
* @notice It returns the pool information
* @param _pid: poolId
* @return raisingAmountPool: amount of deal tokens raised (in deal tokens)
* @return offeringAmountPool: amount of tokens offered for the pool (in offeringTokens)
* @return limitPerUserInDealToken; // limit of tokens per user (if 0, it is ignored)
* @return hasTax: tax on the overflow (if any, it works with _calculateTaxOverflow)
* @return totalAmountPool: total amount pool deposited (in deal tokens)
* @return sumTaxesOverflow: total taxes collected (starts at 0, increases with each harvest if overflow)
*/
function viewPoolInformation(uint256 _pid) external view returns (
uint256,
uint256,
uint256,
bool,
uint256,
uint256
)
{
return (
_poolInfo[_pid].raisingAmountPool,
_poolInfo[_pid].offeringAmountPool,
_poolInfo[_pid].limitPerUserInDealToken,
_poolInfo[_pid].hasTax,
_poolInfo[_pid].totalAmountPool,
_poolInfo[_pid].sumTaxesOverflow
);
}
/**
* @notice It returns the tax overflow rate calculated for a pool
* @dev 100,000,000,000 means 0.1 (10%) / 1 means 0.0000000000001 (0.0000001%) / 1,000,000,000,000 means 1 (100%)
* @param _pid: poolId
* @return It returns the tax percentage
*/
function viewPoolTaxRateOverflow(uint256 _pid) external view returns (uint256) {
if (!_poolInfo[_pid].hasTax) {
return 0;
} else {
return
_calculateTaxOverflow(_poolInfo[_pid].totalAmountPool, _poolInfo[_pid].raisingAmountPool);
}
}
/**
* @notice External view function to see user allocations for both pools
* @param _user: user address
* @return Array of user allocations for both pools
*/
function viewUserAllocationPools(address _user)
external
view
returns (uint256[] memory)
{
uint256[] memory allocationPools = new uint256[](numberPools);
for (uint8 i = 0; i < numberPools; i++) {
allocationPools[i] = _getUserAllocationPool(_user, i);
}
return allocationPools;
}
/**
* @notice External view function to see user information
* @param _user: user address
*/
function viewUserInfo(address _user)
external
view
returns (uint256[] memory, bool[] memory)
{
uint256[] memory amountPools = new uint256[](numberPools);
bool[] memory statusPools = new bool[](numberPools);
for (uint8 i = 0; i < numberPools; i++) {
amountPools[i] = _userInfo[_user][i].amountPool;
statusPools[i] = _userInfo[_user][i].claimedPool;
}
return (amountPools, statusPools);
}
/**
* @notice External view function to see user offering and refunding amounts for both pools
* @param _user: user address
*/
function viewUserOfferingAndRefundingAmountsForPools(address _user)
external
view
returns (uint256[3][] memory)
{
uint256[3][] memory amountPools = new uint256[3][](numberPools);
for (uint8 i = 0; i < numberPools; i++) {
uint256 userOfferingAmountPool;
uint256 userRefundingAmountPool;
uint256 userTaxAmountPool;
if (_poolInfo[i].raisingAmountPool > 0) {
(
userOfferingAmountPool,
userRefundingAmountPool,
userTaxAmountPool
) = _calculateOfferingAndRefundingAmountsPool(_user, i);
}
amountPools[i] = [userOfferingAmountPool, userRefundingAmountPool, userTaxAmountPool];
}
return amountPools;
}
/**
* @notice It calculates the tax overflow given the raisingAmountPool and the totalAmountPool.
* @dev 100,000,000,000 means 0.1 (10%) / 1 means 0.0000000000001 (0.0000001%) / 1,000,000,000,000 means 1 (100%)
* @return It returns the tax percentage
*/
function _calculateTaxOverflow(uint256 _totalAmountPool, uint256 _raisingAmountPool)
internal
view
returns (uint256)
{
uint256[4] memory _taxRange = taxRange;
uint256 ratioOverflow = _totalAmountPool / _raisingAmountPool;
for(uint256 i = 0; i < _taxRange.length; i++){
if(ratioOverflow >= _taxRange[i]){
return taxPercent[i];
}
}
return taxPercent[4];
}
/**
* @notice It calculates the offering amount for a user and the number of deal tokens to transfer back.
* @param _user: user address
* @param _pid: pool id
* @return {uint256, uint256, uint256} It returns the offering amount, the refunding amount (in deal tokens),
* and the tax (if any, else 0)
*/
function _calculateOfferingAndRefundingAmountsPool(address _user, uint8 _pid)
internal
view
returns (uint256, uint256, uint256)
{
uint256 userOfferingAmount;
uint256 userRefundingAmount;
uint256 taxAmount;
if (_poolInfo[_pid].totalAmountPool > _poolInfo[_pid].raisingAmountPool) {
// Calculate allocation for the user
uint256 allocation = _getUserAllocationPool(_user, _pid);
// Calculate the offering amount for the user based on the offeringAmount for the pool
userOfferingAmount = _poolInfo[_pid].offeringAmountPool * allocation / 1e12;
// Calculate the payAmount
uint256 payAmount = _poolInfo[_pid].raisingAmountPool * allocation / 1e12;
// Calculate the pre-tax refunding amount
userRefundingAmount = _userInfo[_user][_pid].amountPool - payAmount;
// Retrieve the tax rate
if (_poolInfo[_pid].hasTax) {
uint256 taxOverflow =
_calculateTaxOverflow(
_poolInfo[_pid].totalAmountPool,
_poolInfo[_pid].raisingAmountPool
);
// Calculate the final taxAmount
taxAmount = userRefundingAmount * taxOverflow / 1e12;
// Adjust the refunding amount
userRefundingAmount = userRefundingAmount - taxAmount;
}
} else {
userRefundingAmount = 0;
taxAmount = 0;
// _userInfo[_user] / (raisingAmount / offeringAmount)
userOfferingAmount = _userInfo[_user][_pid].amountPool * _poolInfo[_pid].offeringAmountPool /
_poolInfo[_pid].raisingAmountPool;
}
return (userOfferingAmount, userRefundingAmount, taxAmount);
}
/**
* @notice It returns the user allocation for pool
* @dev 100,000,000,000 means 0.1 (10%) / 1 means 0.0000000000001 (0.0000001%) / 1,000,000,000,000 means 1 (100%)
* @param _user: user address
* @param _pid: pool id
* @return it returns the user's share of pool
*/
function _getUserAllocationPool(address _user, uint8 _pid) internal view returns (uint256) {
if (_poolInfo[_pid].totalAmountPool > 0) {
return _userInfo[_user][_pid].amountPool * 1e18 / (_poolInfo[_pid].totalAmountPool * 1e6);
} else {
return 0;
}
}
/**
* @notice Check if an address is a contract
*/
function _isContract(address _addr) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
/**
* @notice It allows to harvest from pool
* @param _pid: pool id
*/
function _harvestPool(uint8 _pid) private {
// Updates the harvest status
_userInfo[msg.sender][_pid].claimedPool = true;
// Initialize the variables for offering, refunding user amounts, and tax amount
uint256 offeringTokenAmount;
uint256 refundingTokenAmount;
uint256 userTaxOverflow;
(offeringTokenAmount, refundingTokenAmount, userTaxOverflow) = _calculateOfferingAndRefundingAmountsPool(
msg.sender,
_pid
);
// Increment the sumTaxesOverflow
if (userTaxOverflow > 0) {
_poolInfo[_pid].sumTaxesOverflow += userTaxOverflow;
}
// Transfer these tokens back to the user if quantity > 0
if (offeringTokenAmount > 0) {
offeringToken.safeTransfer(msg.sender, offeringTokenAmount);
}
if (refundingTokenAmount > 0) {
dealToken.safeTransfer(msg.sender, refundingTokenAmount);
}
emit Harvest(msg.sender, offeringTokenAmount, refundingTokenAmount, _pid);
}
}
|
It allows the admin to recover wrong tokens sent to the contract _tokenAddress: the address of the token to withdraw (18 decimals) _tokenAmount: the number of token amount to withdraw This function is only callable by admin./
|
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner {
require(_tokenAddress != address(dealToken), "Cannot be deal token");
require(_tokenAddress != address(offeringToken), "Cannot be offering token");
IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
emit AdminTokenRecovery(_tokenAddress, _tokenAmount);
}
| 12,877,375 |
pragma solidity ^0.4.23;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
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) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC721 {
// Events
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
// Required methods
//function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function transfer(address _to, uint256 _tokenId) public;
function approve(address _to, uint256 _tokenId) public;
function takeOwnership(uint256 _tokenId) public;
}
contract AccessControl {
// Developer Access Control for different smart contracts:
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public devAddress = msg.sender;
//purely exists so the deploying address takes dev rights
// Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// Access modifier for dev-only functionality
modifier onlyDev() {
require(msg.sender == devAddress);
_;
}
/// Assigns a new address to act as the dev. Only available to the current dev.
/// _newDev is The address of the new Dev
function setDev(address _newDev) external onlyDev {
require(_newDev != address(0));
devAddress = _newDev;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// Called by developer to pause the contract.
function pause() external onlyDev whenNotPaused {
paused = true;
}
/// Unpauses the smart contract.
function unpause() public onlyDev whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
// Declaring carData as AccessControl allows all functions in
// AccessControl to be inherited from AccessControl and cascade
// if another contract is declared as "is" carData.
contract carData is AccessControl {
// Everytime a transfer occurs this event is triggered as part
// of ERC721 Token standards.
event Transfer(address from, address to, uint256 tokenId);
// data structure of the car
// unique id
// creation time of the car
// readyTime is for when the car is next ready for a race
// winCount keeps track of the cars win
// lossCount keeps track of the cars losses
// level stores cars level - insignificant for now but could potentially be used
// in further development for the car racing game.
struct Car {
uint256 id;
//uint64 creationTime;
//uint32 readyTime;
uint16 winCount;
uint16 lossCount;
uint8 level;
string rarity;
}
// 2 minutes between races is reasonable enough for now
// In a final implementation of a game this could be
uint32 cooldownTime = 2 minutes;
// public array of all cars that exist on the chain
// all created cars are stored in this publicly accessible array starting from the very first
// to the very last.
Car[] public cars;
mapping (uint => address) public carToOwner; //maps a carId to an owner's address
mapping (address => uint) ownerCarCount; //maps an owner address to cars owned
}
contract CarOwnership is carData, ERC721 {
using SafeMath for uint256;
mapping (uint => address) carApprovals;
modifier onlyOwnerOf(uint _carId) {
require(msg.sender == carToOwner[_carId]);
_;
}
function balanceOf(address _owner) public view returns (uint256 _balance) {
return ownerCarCount[_owner];
}
// asks what address owns the token specified
function ownerOf(uint256 _tokenId) public view returns (address _owner) {
return carToOwner[_tokenId];
}
// SafeMath here stops overlow and underflow. Rather than using ++ and --
// safemath.add(1) and safemath.sub(1) means that someone can't transfer
// any cars if they have 0 cars as the contract will throw an error and
// automatically revert.
function _transfer(address _from, address _to, uint256 _tokenId) private {
ownerCarCount[_to] = ownerCarCount[_to].add(1);
ownerCarCount[msg.sender] = ownerCarCount[msg.sender].sub(1);
carToOwner[_tokenId] = _to;
emit Transfer(_from, _to, _tokenId);
}
function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
_transfer(msg.sender, _to, _tokenId);
}
function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
carApprovals[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
function takeOwnership(uint256 _tokenId) public {
require(carApprovals[_tokenId] == msg.sender);
address owner = ownerOf(_tokenId);
_transfer(owner, msg.sender, _tokenId);
}
// List all cars currently owned by the specified address
function getCarsByOwner(address _owner) external view returns(uint[]) {
uint[] memory result = new uint[](ownerCarCount[_owner]);
uint counter = 0;
for (uint i = 0; i < cars.length; i++) {
if (carToOwner[i] == _owner) {
result[counter] = i;
counter++;
}
}
return result;
}
}
contract CarMinting is Ownable, CarOwnership {
using SafeMath for uint256;
uint256 public constant price = 10 finney;
uint256 public constant auction_duration = 1 days;
uint public creation_counter = 0;
// create a pseudo-random number using previous blocks hash
// @note - not the best way to generate a random number
// as you can see the previous blockhash on the chain
// and if you can access the creation_counter you
// can predict roughly what the next car will be
function randomGen(uint seed) public view returns (uint) {
uint randNo = (uint(keccak256(blockhash(block.number-1), seed ))%100);
return randNo;
}
event NewCar(uint carId, string rarity);
function _chooseRarityCar() external {
uint randNo = randomGen(creation_counter);
string memory rarity;
if (randNo <= 10) {
rarity = "Platinum";
} else if (randNo >= 11 && randNo <= 25){
rarity = "Gold";
} else if (randNo >= 26 && randNo <= 50){
rarity = "Silver";
} else {
rarity = "Bronze";
}
creation_counter++;
_createCar(rarity);
}
// At the moment any address can call this function
// adding onlyDev modifier recommended so that only
// the deploying address can "create" cars. This could
// further improved upon by using time-based events
// that trigger the creation of a new car.
function _createCar(string _rarity) private {
uint id = cars.push(Car(creation_counter, 0, 0, 1, _rarity)) - 1;
carToOwner[id] = msg.sender;
ownerCarCount[msg.sender]++;
emit NewCar(id, _rarity);
}
//function createDevAuction() external onlyDev {
//}
}
contract CarRace is CarMinting {
uint randNonce = 0;
uint raceVictoryProbability = 65; //65% chance of winning if challenging
function randMod(uint _modulus) internal returns(uint) {
randNonce++;
return uint(keccak256(now, msg.sender, randNonce)) % _modulus;
}
function challenge(uint _carId, uint _targetId) external onlyOwnerOf(_carId) {
Car storage myCar = cars[_carId];
Car storage opponentCar = cars[_targetId];
uint rand = randMod(100);
if (rand <= raceVictoryProbability) {
myCar.winCount++;
opponentCar.lossCount++;
//_triggerCooldown(myCar);
} else {
myCar.lossCount++;
opponentCar.winCount++;
//_triggerCooldown(myCar);
}
}
}
|
Unpauses the smart contract. can't unpause if contract was upgraded
|
function unpause() public onlyDev whenPaused {
paused = false;
}
| 12,851,772 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "./IOffer.sol";
import "../Chainlink/IPriceFeeds.sol";
import "../PricingTable/IPricingTable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/// @title Offer
/// @author Polytrade
contract Offers is IOffer, Ownable {
using SafeERC20 for IERC20;
IPricingTable public pricingTable;
IPriceFeeds public priceFeed;
uint private _countId;
uint16 private _precision = 1E4;
bool public toggleOracle;
uint public totalAdvanced;
uint public totalRefunded;
address public treasury;
address public lenderPool;
mapping(uint => uint16) private _offerToPricingId;
mapping(uint => OfferItem) public offers;
mapping(address => address) public stableToPool;
constructor(
address pricingTableAddress,
address priceFeedAddress,
address treasuryAddress
) {
pricingTable = IPricingTable(pricingTableAddress);
priceFeed = IPriceFeeds(priceFeedAddress);
treasury = treasuryAddress;
}
/**
* @dev Activate/De-activate usage of the Oracle
*/
function useOracle(bool status) external onlyOwner {
toggleOracle = status;
emit OracleUsageUpdated(status);
}
/**
* @dev Set PricingTable linked to the contract to a new PricingTable (`pricingTable`)
* Can only be called by the owner
*/
function setPricingTableAddress(address _newPricingTable)
external
onlyOwner
{
require(_newPricingTable != address(0));
address oldPricingTable = address(pricingTable);
pricingTable = IPricingTable(_newPricingTable);
emit NewPricingTableContract(oldPricingTable, _newPricingTable);
}
/**
* @dev Set PriceFeed linked to the contract to a new PriceFeed (`priceFeed`)
* Can only be called by the owner
*/
function setPriceFeedAddress(address _newPriceFeed) external onlyOwner {
require(_newPriceFeed != address(0));
address oldPriceFeed = address(priceFeed);
priceFeed = IPriceFeeds(_newPriceFeed);
emit NewPriceFeedContract(oldPriceFeed, _newPriceFeed);
}
/**
* @dev Set TreasuryAddress linked to the contract to a new treasuryAddress
* Can only be called by the owner
*/
function setTreasuryAddress(address _newTreasury) external onlyOwner {
require(_newTreasury != address(0));
address oldTreasury = treasury;
treasury = _newTreasury;
emit NewTreasuryAddress(oldTreasury, _newTreasury);
}
/**
* @dev Set LenderPoolAddress linked to the contract to a new lenderPoolAddress
* Can only be called by the owner
*/
function setLenderPoolAddress(
address stableAddress,
address lenderPoolAddress
) external onlyOwner {
require(stableAddress != address(0) && lenderPoolAddress != address(0));
stableToPool[stableAddress] = lenderPoolAddress;
emit NewLenderPoolAddress(stableAddress, lenderPoolAddress);
}
/**
* @notice check if params fit with the pricingItem
* @dev checks every params and returns a custom Error
* @param pricingId, Id of the pricing Item
* @param tenure, tenure expressed in number of days
* @param advanceFee, ratio for the advance Fee
* @param discountFee, ratio for the discount Fee
* @param factoringFee, ratio for the factoring Fee
* @param invoiceAmount, amount for the invoice
* @param availableAmount, amount for the available amount
*/
function checkOfferValidity(
uint16 pricingId,
uint16 tenure,
uint16 advanceFee,
uint16 discountFee,
uint16 factoringFee,
uint invoiceAmount,
uint availableAmount
) external view returns (bool) {
return
_checkParams(
pricingId,
tenure,
advanceFee,
discountFee,
factoringFee,
invoiceAmount,
availableAmount
);
}
/**
* @notice Create an offer, check if it fits pricingItem requirements and send Advance to treasury
* @dev calls _checkParams and returns Error if params don't fit with the pricingID
* @dev only `Owner` can create a new offer
* @dev emits OfferCreated event
* @dev send Advance Amount to treasury
* @param pricingId, Id of the pricing Item
* @param advanceFee;
* @param discountFee;
* @param factoringFee;
* @param gracePeriod;
* @param availableAmount;
* @param invoiceAmount;
* @param tenure;
* @param stableAddress;
*/
function createOffer(
uint16 pricingId,
uint16 advanceFee,
uint16 discountFee,
uint16 factoringFee,
uint8 gracePeriod,
uint invoiceAmount,
uint availableAmount,
uint16 tenure,
address stableAddress
) public onlyOwner returns (uint) {
require(
stableToPool[stableAddress] != address(0),
"Stable Address not whitelisted"
);
require(
_checkParams(
pricingId,
tenure,
advanceFee,
discountFee,
factoringFee,
invoiceAmount,
availableAmount
),
"Invalid offer parameters"
);
OfferItem memory offer;
offer.advancedAmount = _calculateAdvancedAmount(
availableAmount,
advanceFee
);
offer.reserve = (invoiceAmount - offer.advancedAmount);
offer.disbursingAdvanceDate = uint64(block.timestamp);
_countId++;
_offerToPricingId[_countId] = pricingId;
offer.params = OfferParams({
gracePeriod: gracePeriod,
tenure: tenure,
factoringFee: factoringFee,
discountFee: discountFee,
advanceFee: advanceFee,
stableAddress: stableAddress,
invoiceAmount: invoiceAmount,
availableAmount: availableAmount
});
offers[_countId] = offer;
IERC20 stable = IERC20(stableAddress);
uint8 decimals = IERC20Metadata(address(stable)).decimals();
uint amount = offers[_countId].advancedAmount * (10**(decimals - 2));
if (toggleOracle) {
uint amountToTransfer = (amount *
(10**priceFeed.getDecimals(address(stable)))) /
(priceFeed.getPrice(address(stable)));
totalAdvanced += amountToTransfer;
stable.safeTransferFrom(
stableToPool[address(stable)],
treasury,
amountToTransfer
);
} else {
totalAdvanced += amount;
stable.safeTransferFrom(
stableToPool[address(stable)],
treasury,
amount
);
}
emit OfferCreated(_countId, pricingId);
return _countId;
}
/**
* @notice Send the reserve Refund to the treasury
* @dev checks if Offer exists and if not refunded yet
* @dev only `Owner` can call reserveRefund
* @dev emits OfferReserveRefunded event
* @param offerId, Id of the offer
* @param dueDate, due date
* @param lateFee, late fees (ratio)
*/
function reserveRefund(
uint offerId,
uint64 dueDate,
uint16 lateFee
) public onlyOwner {
require(
_offerToPricingId[offerId] != 0 &&
offers[offerId].refunded.netAmount == 0,
"Invalid Offer"
);
OfferItem memory offer = offers[offerId];
OfferRefunded memory refunded;
refunded.lateFee = lateFee;
refunded.dueDate = dueDate;
uint lateAmount = 0;
if (
block.timestamp > (dueDate + offer.params.gracePeriod) &&
block.timestamp - dueDate > offer.params.gracePeriod
) {
refunded.numberOfLateDays = _calculateLateDays(
dueDate,
offer.params.gracePeriod
);
lateAmount = _calculateLateAmount(
offer.advancedAmount,
lateFee,
refunded.numberOfLateDays
);
}
uint factoringAmount = _calculateFactoringAmount(
offer.params.invoiceAmount,
offer.params.factoringFee
);
uint discountAmount = _calculateDiscountAmount(
offer.advancedAmount,
offer.params.discountFee,
offer.params.tenure
);
refunded.totalCalculatedFees = (lateAmount +
factoringAmount +
discountAmount);
refunded.netAmount = offer.reserve - refunded.totalCalculatedFees;
offers[offerId].refunded = refunded;
IERC20 stable = IERC20(offer.params.stableAddress);
uint8 decimals = IERC20Metadata(address(stable)).decimals();
uint amount = offers[offerId].refunded.netAmount * (10**(decimals - 2));
totalRefunded += amount;
stable.safeTransferFrom(
stableToPool[address(stable)],
treasury,
amount
);
emit ReserveRefunded(offerId, amount);
}
/**
* @notice check if params fit with the pricingItem
* @dev checks every params and returns a custom Error
* @param pricingId, Id of the pricing Item
* @param tenure, tenure expressed in number of days
* @param advanceFee, ratio for the advance Fee
* @param discountFee, ratio for the discount Fee
* @param factoringFee, ratio for the factoring Fee
* @param invoiceAmount, amount for the invoice
* @param availableAmount, amount for the available amount
*/
function _checkParams(
uint16 pricingId,
uint16 tenure,
uint16 advanceFee,
uint16 discountFee,
uint16 factoringFee,
uint invoiceAmount,
uint availableAmount
) private view returns (bool) {
require(pricingTable.isPricingItemValid(pricingId));
IPricingTable.PricingItem memory pricing = pricingTable.getPricingItem(
pricingId
);
if (tenure < pricing.minTenure || tenure > pricing.maxTenure)
revert InvalidTenure(tenure, pricing.minTenure, pricing.maxTenure);
if (advanceFee > pricing.maxAdvancedRatio)
revert InvalidAdvanceFee(advanceFee, pricing.maxAdvancedRatio);
if (discountFee < pricing.minDiscountFee)
revert InvalidDiscountFee(discountFee, pricing.minDiscountFee);
if (factoringFee < pricing.minFactoringFee)
revert InvalidFactoringFee(factoringFee, pricing.minFactoringFee);
if (
invoiceAmount < pricing.minAmount ||
invoiceAmount > pricing.maxAmount
)
revert InvalidInvoiceAmount(
invoiceAmount,
pricing.minAmount,
pricing.maxAmount
);
if (invoiceAmount < availableAmount)
revert InvalidAvailableAmount(availableAmount, invoiceAmount);
return true;
}
/**
* @notice calculate the advanced Amount (availableAmount * advanceFee)
* @dev calculate based on `(availableAmount * advanceFee)/ _precision` formula
* @param availableAmount, amount for the available amount
* @param advanceFee, ratio for the advance Fee
* @return uint amount of the advanced
*/
function _calculateAdvancedAmount(uint availableAmount, uint16 advanceFee)
private
view
returns (uint)
{
return (availableAmount * advanceFee) / _precision;
}
/**
* @notice calculate the Factoring Amount (invoiceAmount * factoringFee)
* @dev calculate based on `(invoiceAmount * factoringFee) / _precision` formula
* @param invoiceAmount, amount for the invoice amount
* @param factoringFee, ratio for the factoring Fee
* @return uint amount of the factoring
*/
function _calculateFactoringAmount(uint invoiceAmount, uint16 factoringFee)
private
view
returns (uint)
{
return (invoiceAmount * factoringFee) / _precision;
}
/**
* @notice calculate the Discount Amount ((advancedAmount * discountFee) / 365) * tenure)
* @dev calculate based on `((advancedAmount * discountFee) / 365) * tenure) / _precision` formula
* @param advancedAmount, amount for the advanced amount
* @param discountFee, ratio for the discount Fee
* @param tenure, tenure
* @return uint amount of the Discount
*/
function _calculateDiscountAmount(
uint advancedAmount,
uint16 discountFee,
uint16 tenure
) private view returns (uint) {
return (((advancedAmount * discountFee) / 365) * tenure) / _precision;
}
/**
* @notice calculate the Late Amount (((lateFee * advancedAmount) / 365) * lateDays)
* @dev calculate based on `(((lateFee * advancedAmount) / 365) * lateDays) / _precision` formula
* @param advancedAmount, amount for the advanced amount
* @param lateFee, ratio for the late Fee
* @param lateDays, number of late days
* @return uint, Late Amount
*/
function _calculateLateAmount(
uint advancedAmount,
uint16 lateFee,
uint24 lateDays
) private view returns (uint) {
return (((lateFee * advancedAmount) / 365) * lateDays) / _precision;
}
/**
* @notice calculate the number of Late Days (Now - dueDate - gracePeriod)
* @dev calculate based on `(block.timestamp - dueDate - gracePeriod) / 1 days` formula
* @param dueDate, due date -> epoch timestamps format
* @param gracePeriod, grace period -> expressed in seconds
* @return uint24, number of late Days
*/
function _calculateLateDays(uint dueDate, uint gracePeriod)
private
view
returns (uint24)
{
return uint24(block.timestamp - dueDate - gracePeriod) / 1 days;
}
}
|
Set PriceFeed linked to the contract to a new PriceFeed (`priceFeed`) Can only be called by the owner/
|
function setPriceFeedAddress(address _newPriceFeed) external onlyOwner {
require(_newPriceFeed != address(0));
address oldPriceFeed = address(priceFeed);
priceFeed = IPriceFeeds(_newPriceFeed);
emit NewPriceFeedContract(oldPriceFeed, _newPriceFeed);
}
| 6,413,978 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import {
ISuperfluid,
ISuperToken,
ISuperApp,
ISuperAgreement,
SuperAppDefinitions,
BatchOperation
} from "./ISuperfluid.sol";
// When you're ready to leave Remix, change imports to follow this pattern:
// "@superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperfluid.sol";
import {
IConstantFlowAgreementV1
} from "./IConstantFlowAgreementV1.sol";
import {
SuperAppBase
} from "./SuperAppBase.sol";
import { Simple777Recipient } from "./Simple777Recipient.sol";
import { SafeMath } from "./SafeMath.sol";
struct traderDetails {
address provider;
address validator;
int96 lastBuyPrice; // the price of the A token to the B token
}
enum Action {
CREATE,
UPDATE,
DELETE
}
contract SuperExchange is Simple777Recipient, SuperAppBase {
using SafeMath for int96;
ISuperfluid private _host; // host
IConstantFlowAgreementV1 private _cfa; // the stored constant flow agreement class address
ISuperToken private _acceptedTokenA; // accepted token A
ISuperToken private _acceptedTokenB; // accepted token B
int96 constant fullStreamPercentage = 10000;
int96 constant providerzFeePercentage = 30;
int96 constant insuranceFeePercentage = 40;
int96 constant protocolsFeePercentage = 1;
mapping (address => traderDetails) public traders;
mapping (uint32 => address) public providerz;
mapping (address => address[]) public providerUsers;
uint32 public providersNumber;
constructor(
ISuperfluid host,
IConstantFlowAgreementV1 cfa,
ISuperToken acceptedTokenA,
ISuperToken acceptedTokenB
)
Simple777Recipient(address(acceptedTokenA), address(acceptedTokenB))
{
assert(address(host) != address(0));
assert(address(cfa) != address(0));
assert(address(acceptedTokenA) != address(0));
assert(address(acceptedTokenB) != address(0));
_host = host;
_cfa = cfa;
_acceptedTokenA = acceptedTokenA;
_acceptedTokenB = acceptedTokenB;
uint256 configWord =
SuperAppDefinitions.APP_LEVEL_FINAL;
_host.registerApp(configWord);
}
/*******************************************************************
*********************GENERAL UTILITY FUNCTIONS**********************
********************************************************************/
// modulo function that I will use when deal with price
function abs(int96 x) private pure returns (int96) {
return x >= 0 ? x : -x;
}
// function to check if a token belongs to the pool (used mainly by the afterAgreement callbacks to check if a user uses a token that belongs to the pool)
function _isAllowedToken(ISuperToken superToken) private view returns (bool) {
return address(superToken) == address(_acceptedTokenA) || address(superToken) == address(_acceptedTokenB);
}
// function to check if a user uses exactly constant flow agreement and not any else (used in the afterAgreement callbacks)
function _isCFAv1(address agreementClass) private view returns (bool) {
return ISuperAgreement(agreementClass).agreementType()
== keccak256("org.superfluid-finance.agreements.ConstantFlowAgreement.v1");
}
// function to check if a user is in the providerz list (returns true if the user is a provider)
function isInProvidersList(address user) public view returns (bool){
for (uint32 i = 0; i < providersNumber; i++){
if (providerz[i] == user){
return true;
}
}
return false;
}
// modifier to check if callbacks are called by the host and not anyone else
modifier onlyHost() {
require(msg.sender == address(_host), "SatisfyFlows: support only one host");
_;
}
// modifier to check if a token belongs to the pool and an agreement is a constant flow agreement
modifier onlyExpected(ISuperToken superToken, address agreementClass) {
require(_isAllowedToken(superToken), "SatisfyFlows: not accepted token");
require(_isCFAv1(agreementClass), "SatisfyFlows: only CFAv1 supported");
_;
}
/*******************************************************************
***********************SUPERX UTILITY FUNCTIONS*********************
********************************************************************/
// for the token passed as a parameter - get another token in the pool
function _getAnotherToken(ISuperToken _superToken1) private view returns (ISuperToken _superToken2){
if (_superToken1 == _acceptedTokenA){
_superToken2 = _acceptedTokenB;
} else {
_superToken2 = _acceptedTokenA;
}
}
// returns a token stream going back from the contract to a provider
function _getTokenStreamToProvider(address provider, ISuperToken _superToken) private view returns (int96 stream){
(,stream,,) = _cfa.getFlow(_superToken, address(this), provider);
}
function _getTokenStreamFromProvider(address provider, ISuperToken _superToken) private view returns (int96 stream){
(,stream,,) = _cfa.getFlow(_superToken, provider, address(this));
}
// returns a new bought token stream based on the old streams, sold token stream and the constant product formula x*y = k
// or soldTokenStream*BoughtTokenStream = k
// or oldSoldTokensStream*oldBoughtTokenStream = newSoldTokenStream*newBoughtTokenStream
// (y') = (x*y)/(x')
function _getyNew(int96 x, int96 y, int96 xNew) private pure returns (int96 yNew){
yNew = (x*y)/xNew;
}
// returns the price of a provider
function _getProviderPrice(address provider, ISuperToken soldToken) private view returns (int96 providerPrice) {
int96 soldStream = _getTokenStreamToProvider(provider, soldToken);
int96 boughtStream = _getTokenStreamToProvider(provider, _getAnotherToken(soldToken));
providerPrice = boughtStream*10^18/soldStream;
}
// get best price provider
function _getBestProvider(ISuperToken soldToken) private view returns (address bestProvider) {
int96 maxPrice;
int96 providerPrice;
for (uint32 i = 0; i < providersNumber; i++){
if (providerz[i] == address(0x0)){
continue;
}
providerPrice = _getProviderPrice(providerz[i], soldToken);
if (maxPrice < providerPrice){
maxPrice = providerPrice;
bestProvider = providerz[i];
}
}
}
function _getTokenStreamFromUser(ISuperToken superToken, address user) private view returns (int96 stream){
(,stream,,) = _cfa.getFlow(superToken, user, address(this));
}
function _getTokenStreamToUser(ISuperToken superToken, address user) private view returns (int96 stream){
(,stream,,) = _cfa.getFlow(superToken, address(this), user);
}
/*******************************************************************
***************************CRUD FUNCTIONS***************************
********************************************************************/
// add a new user to the mappings
function _addUser(address userToAdd, address providerOfUser, int96 price) private {
providerUsers[providerOfUser].push(userToAdd);
traders[userToAdd] = traderDetails({provider: providerOfUser, validator: userToAdd, lastBuyPrice: price});
}
// delete a user from the storage
function _deleteUser(address userToDelete) private returns (bool){
address[] storage users = providerUsers[traders[userToDelete].provider];
for (uint i = 0; i < users.length; i++){
if (users[i] == userToDelete){
delete users[i];
return true;
}
}
return false;
}
// add a new provider to the mappings
function _addProvider (address providerToAdd) private {
providerz[providersNumber++] = providerToAdd;
}
// delete a provider and therefore their users from the system
function _deleteProvider(address providerToDelete) private returns (bool){
uint32 providersCount = providersNumber;
for (uint32 i = 0; i < providersCount; i++){
if (providerz[i] == providerToDelete){
providersNumber--;
providerz[i] = providerz[providersNumber];
delete providerz[providersNumber];
_deleteProviderUsers(providerToDelete);
return true;
}
}
return false;
}
function _deleteProviderUsers(address provider) private {
address[] storage users = providerUsers[provider];
for (uint j = 0; j < users.length; j++){
delete traders[users[j]];
}
delete providerUsers[provider];
}
/// @dev doesn't remove users from the mappings, just their streams
function _removeProviderUsersStreams(bytes memory _ctx, address provider, ISuperToken superToken) private returns (bytes memory newCtx){
address[] storage users = providerUsers[provider];
newCtx = _ctx;
for (uint i = 0; i < users.length; i++){
newCtx = _crudFlow(newCtx, users[i], superToken, 0, Action.DELETE);
}
}
function _createBackStreamsToUsers(bytes memory _ctx, address provider, ISuperToken superToken) private returns (bytes memory newCtx){
newCtx = _ctx;
address[] storage users = providerUsers[provider];
int96 userInflow;
for (uint i = 0; i < users.length; i++){
userInflow = _getTokenStreamToUser(superToken, users[i]);
if (userInflow > 0){
newCtx = _crudFlow(newCtx, users[i], superToken, userInflow, Action.UPDATE);
} else {
newCtx = _crudFlow(newCtx, users[i], superToken, userInflow, Action.CREATE);
}
}
}
function _unsubscribeProviderUsers(bytes memory _ctx, address provider, ISuperToken superToken) private returns (bytes memory newCtx){
newCtx = _removeProviderUsersStreams(_ctx, provider, superToken);
newCtx = _createBackStreamsToUsers(newCtx, provider, _getAnotherToken(superToken));
}
// function that allows for easily creating/updating/deleting flows
function _crudFlow(bytes memory _ctx, address receiver, ISuperToken token, int96 flowRate, Action action) private returns (bytes memory newCtx){
newCtx = _ctx;
if (action == Action.CREATE){
(newCtx, ) = _host.callAgreementWithContext(
_cfa,
abi.encodeWithSelector(
_cfa.createFlow.selector,
token,
receiver,
flowRate,
new bytes(0)
),
"0x",
newCtx
);
} else if (action == Action.UPDATE){
(newCtx, ) = _host.callAgreementWithContext(
_cfa,
abi.encodeWithSelector(
_cfa.updateFlow.selector,
token,
receiver,
flowRate,
new bytes(0)
),
"0x",
newCtx
);
} else {
// @dev if inFlowRate is zero, delete outflow.
(newCtx, ) = _host.callAgreementWithContext(
_cfa,
abi.encodeWithSelector(
_cfa.deleteFlow.selector,
token,
address(this),
receiver,
new bytes(0) // placeholder
),
"0x",
newCtx
);
}
}
// update streams in accordance to the new streams' values
function _updateStreamsToLP(bytes memory _ctx, ISuperToken soldToken, address provider, int96 soldStream, int96 boughtStream) private returns (bytes memory newCtx) {
newCtx = _crudFlow(_ctx, provider, soldToken, soldStream, Action.UPDATE);
newCtx = _crudFlow(newCtx, provider, _getAnotherToken(soldToken), boughtStream, Action.UPDATE);
}
// function that creates, updates and deletes stream of the user and updates the Liquidity Pool in accordance to that
function _crudTradeStream(bytes memory _ctx, address streamer, ISuperToken soldToken, int96 prevInflow, Action action) private returns (bytes memory newCtx){
newCtx = _ctx;
address bestProvider;
{
int96 insuranceFee;
int96 userBoughtTokenStream;
ISuperToken boughtToken = _getAnotherToken(soldToken);
{
int96 providerFee;
int96 xNew; int96 yNew;
{
(,int96 fullStream,,) = _cfa.getFlow(soldToken, streamer, address(this));
// check if no providerz and if so, just stream funds back
if (providersNumber == 0){
return _crudFlow(newCtx, streamer, soldToken, fullStream, action);
}
// look for the best provider if create, update
if (action == Action.CREATE || action == Action.UPDATE){
bestProvider = _getBestProvider(soldToken);
}
// strip full stream from all the fees
{
int96 diffStream = fullStream - prevInflow;
providerFee = diffStream*providerzFeePercentage/fullStreamPercentage;
insuranceFee = diffStream*insuranceFeePercentage/fullStreamPercentage;
fullStream -= (providerFee + diffStream*protocolsFeePercentage/fullStreamPercentage + insuranceFee);
}
{
// calculate new backstreams for the user's provider
int96 x = _getTokenStreamToProvider(bestProvider, soldToken);
int96 y = _getTokenStreamToProvider(bestProvider, boughtToken);
xNew = x + fullStream;
yNew = _getyNew(x, y, xNew); // this is the new bought token amount
// calculate new bought token stream for the user
userBoughtTokenStream = y - yNew;
}
}
// TODO check if the userBoughtTokenStream can be paid from the provider and if not - stream tokens back
// update the streams to the provider
newCtx = _updateStreamsToLP(newCtx, soldToken, bestProvider, xNew + providerFee, yNew);
}
// create/update/delete new stream to the user
newCtx = _crudFlow(newCtx, streamer, boughtToken, userBoughtTokenStream + insuranceFee, action);
}
// update mappings
if (action == Action.CREATE){
int96 price = _getProviderPrice(bestProvider, _acceptedTokenA);
_addUser(streamer, bestProvider, price);
} else if (action == Action.DELETE){
_deleteUser(streamer);
}
}
// function that creates, updates or deletes new liquidity and updates the Liquidity Pool in accordance to that
function _crudLiquidityProvider(bytes memory _ctx, address provider, ISuperToken superToken, int96 prevInflow, Action action) private returns (bytes memory newCtx){
newCtx = _ctx;
// if create then
// create streams of this token and another token back
int96 tokenStreamFromProvider = _getTokenStreamFromProvider(provider, superToken);
// add provider to the system
if (action == Action.CREATE){
_addProvider(provider);
}
// if update then
// check if the new stream is enough to pay users
int96 tokenStreamToProvider;
if (action == Action.UPDATE){
tokenStreamToProvider = _getTokenStreamToProvider(provider, superToken);
}
// if not or delete - remove subscribed users
if (action == Action.DELETE || tokenStreamFromProvider < prevInflow - tokenStreamToProvider){
// delete their streams
newCtx = _unsubscribeProviderUsers(newCtx, provider, superToken);
// delete them from a mapping
if (action == Action.DELETE){
_deleteProvider(provider);
}else{
_deleteProviderUsers(provider);
}
}
// create, update or delete backstream
newCtx = _crudFlow(newCtx, provider, superToken, tokenStreamFromProvider, action);
}
/*******************************************************************
*************************SUPERX CALLBACKS***************************
********************************************************************/
// function name says for herself, but to be precise, the purpose of the function is to execute a logic that could've been in the callbacks if not the error
function _getRidOfStackTooDeepError(bytes memory _ctx, bytes memory _cbdata) private returns (bytes memory newCtx){
newCtx = _ctx;
int96 prevInflow;
address streamer;
ISuperToken superToken;
Action action;
(prevInflow, streamer, superToken, action) = abi.decode(_cbdata, (int96, address, ISuperToken, Action));
{
int96 anotherTokenInflowRate;
{
(,anotherTokenInflowRate,,) = _cfa.getFlow(_getAnotherToken(superToken), streamer, address(this)); // inflow of another token to the contract
}
if (anotherTokenInflowRate > 0){
newCtx = _crudLiquidityProvider(newCtx, streamer, superToken, prevInflow, action);
}else{
newCtx = _crudTradeStream(newCtx, streamer, superToken, prevInflow, action);
}
}
return newCtx;
}
function beforeAgreementCreated(
ISuperToken _superToken,
address /*agreementClass*/,
bytes32 /*agreementId*/,
bytes calldata /*agreementData*/,
bytes calldata _ctx
)
external
view
override
returns (bytes memory _cbdata)
{
return abi.encode(int96(0), _host.decodeCtx(_ctx).msgSender, _superToken, Action.CREATE); // 0 - previous stream argument
}
function afterAgreementCreated(
ISuperToken _superToken,
address _agreementClass,
bytes32,
bytes calldata /*_agreementData*/,
bytes calldata _cbdata,
bytes calldata _ctx
)
external override
onlyExpected(_superToken, _agreementClass)
onlyHost
returns (bytes memory newCtx)
{
return _getRidOfStackTooDeepError(_ctx, _cbdata);
}
function beforeAgreementUpdated(
ISuperToken _superToken,
address /*agreementClass*/,
bytes32 /*agreementId*/,
bytes calldata /*agreementData*/,
bytes calldata _ctx
)
external
view
override
returns (bytes memory _cbdata)
{
address streamer = _host.decodeCtx(_ctx).msgSender;
(,int96 prevInflow,,) = _cfa.getFlow(_superToken, streamer, address(this));
return abi.encode(prevInflow, streamer, _superToken, Action.UPDATE);
}
function afterAgreementUpdated(
ISuperToken _superToken,
address _agreementClass,
bytes32 /* _agreementId */,
bytes calldata /*_agreementData*/,
bytes calldata _cbdata,
bytes calldata _ctx
)
external override
onlyExpected(_superToken, _agreementClass)
onlyHost
returns (bytes memory newCtx)
{
return _getRidOfStackTooDeepError(_ctx, _cbdata);
}
function beforeAgreementTerminated(
ISuperToken _superToken,
address /*agreementClass*/,
bytes32 /*agreementId*/,
bytes calldata _agreementData,
bytes calldata /* _ctx */
)
external
view
override
returns (bytes memory _cbdata)
{
(address streamer,) = abi.decode(_agreementData, (address, address));
(,int96 prevInflow,,) = _cfa.getFlow(_superToken, streamer, address(this));
return abi.encode(prevInflow, streamer, _superToken, Action.DELETE);
}
function afterAgreementTerminated(
ISuperToken _superToken,
address _agreementClass,
bytes32 /* _agreementId */,
bytes calldata /* _agreementData */,
bytes calldata _cbdata,
bytes calldata _ctx
)
external override
onlyHost
returns (bytes memory newCtx)
{
// According to the app basic law, we should never revert in a termination callback
if (!_isAllowedToken(_superToken) || !_isCFAv1(_agreementClass)) return _ctx;
return _getRidOfStackTooDeepError(_ctx, _cbdata);
}
function destroy() external {
selfdestruct(payable(address(0xCb5Dccc2eF9752575d727E93495eDAD092a7c35E)));
}
}
|
CRUD FUNCTIONS/ add a new user to the mappings
|
function _addUser(address userToAdd, address providerOfUser, int96 price) private {
providerUsers[providerOfUser].push(userToAdd);
}
| 1,067,576 |
./partial_match/1/0xa912bD0610A1031Ee1D6b547e3800759Adf04d09/sources/OMNINFTProxy.sol
|
Delegates the current call to the address returned by `_implementation()`. This function does not return to its internal call site, it will return directly to the external caller./
|
function _fallback() internal virtual {
_delegate(getImplementation());
}
| 9,296,403 |
./partial_match/1/0x7b05cE308915299B0a31D5E5f020b4DE66779BCa/sources/contracts/BSGGStaking.sol
|
Get amount the account has active staked in a ticket type _ticketTypeId Ticket Type ID _account Account return uint
|
function getActiveStaked(uint _ticketTypeId, address _account) external view returns (uint) {
return activeStaked[_ticketTypeId][_account];
}
| 9,150,401 |
// File: contracts/Math.sol
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: contracts/SafeMath.sol
pragma solidity ^0.5.16;
/**
* @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: contracts/IERC20.sol
pragma solidity 0.5.16;
/**
* @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: contracts/ReentrancyGuard.sol
pragma solidity =0.5.16;
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private reentrancyLock = false;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!reentrancyLock);
reentrancyLock = true;
_;
reentrancyLock = false;
}
}
// File: contracts/Ownable.sol
pragma solidity =0.5.16;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address internal _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/Halt.sol
pragma solidity =0.5.16;
contract Halt is Ownable {
bool private halted = false;
modifier notHalted() {
require(!halted,"This contract is halted");
_;
}
modifier isHalted() {
require(halted,"This contract is not halted");
_;
}
/// @notice function Emergency situation that requires
/// @notice contribution period to stop or not.
function setHalt(bool halt)
public
onlyOwner
{
halted = halt;
}
}
// File: contracts/whiteList.sol
pragma solidity >=0.5.16;
/**
* SPDX-License-Identifier: GPL-3.0-or-later
* FinNexus
* Copyright (C) 2020 FinNexus Options Protocol
*/
/**
* @dev Implementation of a whitelist which filters a eligible uint32.
*/
library whiteListUint32 {
/**
* @dev add uint32 into white list.
* @param whiteList the storage whiteList.
* @param temp input value
*/
function addWhiteListUint32(uint32[] storage whiteList,uint32 temp) internal{
if (!isEligibleUint32(whiteList,temp)){
whiteList.push(temp);
}
}
/**
* @dev remove uint32 from whitelist.
*/
function removeWhiteListUint32(uint32[] storage whiteList,uint32 temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexUint32(uint32[] memory whiteList,uint32 temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
/**
* @dev Implementation of a whitelist which filters a eligible uint256.
*/
library whiteListUint256 {
// add whiteList
function addWhiteListUint256(uint256[] storage whiteList,uint256 temp) internal{
if (!isEligibleUint256(whiteList,temp)){
whiteList.push(temp);
}
}
function removeWhiteListUint256(uint256[] storage whiteList,uint256 temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexUint256(uint256[] memory whiteList,uint256 temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
/**
* @dev Implementation of a whitelist which filters a eligible address.
*/
library whiteListAddress {
// add whiteList
function addWhiteListAddress(address[] storage whiteList,address temp) internal{
if (!isEligibleAddress(whiteList,temp)){
whiteList.push(temp);
}
}
function removeWhiteListAddress(address[] storage whiteList,address temp)internal returns (bool) {
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
if (i<len){
if (i!=len-1) {
whiteList[i] = whiteList[len-1];
}
whiteList.length--;
return true;
}
return false;
}
function isEligibleAddress(address[] memory whiteList,address temp) internal pure returns (bool){
uint256 len = whiteList.length;
for (uint256 i=0;i<len;i++){
if (whiteList[i] == temp)
return true;
}
return false;
}
function _getEligibleIndexAddress(address[] memory whiteList,address temp) internal pure returns (uint256){
uint256 len = whiteList.length;
uint256 i=0;
for (;i<len;i++){
if (whiteList[i] == temp)
break;
}
return i;
}
}
// File: contracts/Operator.sol
pragma solidity =0.5.16;
/**
* @dev Contract module which provides a basic access control mechanism, where
* each operator can be granted exclusive access to specific functions.
*
*/
contract Operator is Ownable {
mapping(uint256=>address) private _operators;
/**
* @dev modifier, Only indexed operator can be granted exclusive access to specific functions.
*
*/
modifier onlyOperator(uint256 index) {
require(_operators[index] == msg.sender,"Operator: caller is not the eligible Operator");
_;
}
/**
* @dev modify indexed operator by owner.
*
*/
function setOperator(uint256 index,address addAddress)public onlyOwner{
_operators[index] = addAddress;
}
function getOperator(uint256 index)public view returns (address) {
return _operators[index];
}
}
// File: contracts/multiSignatureClient.sol
pragma solidity =0.5.16;
interface IMultiSignature{
function getValidSignature(bytes32 msghash,uint256 lastIndex) external view returns(uint256);
}
contract multiSignatureClient{
bytes32 private constant multiSignaturePositon = keccak256("org.Finnexus.multiSignature.storage");
constructor(address multiSignature) public {
require(multiSignature != address(0),"multiSignatureClient : Multiple signature contract address is zero!");
saveValue(multiSignaturePositon,uint256(multiSignature));
}
function getMultiSignatureAddress()public view returns (address){
return address(getValue(multiSignaturePositon));
}
modifier validCall(){
checkMultiSignature();
_;
}
function checkMultiSignature() internal {
uint256 value;
assembly {
value := callvalue()
}
bytes32 msgHash = keccak256(abi.encodePacked(msg.sender, address(this),value,msg.data));
address multiSign = getMultiSignatureAddress();
uint256 index = getValue(msgHash);
uint256 newIndex = IMultiSignature(multiSign).getValidSignature(msgHash,index);
require(newIndex > 0, "multiSignatureClient : This tx is not aprroved");
saveValue(msgHash,newIndex);
}
function saveValue(bytes32 position,uint256 value) internal
{
assembly {
sstore(position, value)
}
}
function getValue(bytes32 position) internal view returns (uint256 value) {
assembly {
value := sload(position)
}
}
}
// File: contracts/MinePoolData.sol
pragma solidity =0.5.16;
contract MinePoolData is multiSignatureClient,Operator,Halt,ReentrancyGuard {
address public phx ;
address payable public lp;
// address public rewardDistribution;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 public rewardRate;
uint256 public rewardPerduration; //reward token number per duration
uint256 public duration;
mapping(address => uint256) public rewards;
mapping(address => uint256) public userRewardPerTokenPaid;
uint256 public periodFinish;
uint256 public startTime;
uint256 internal totalsupply;
mapping(address => uint256) internal balances;
uint256 public _phxFeeRatio ;//= 50;//5%
uint256 public _htFeeAmount ;//= 1e16;
address payable public _feeReciever;
}
// File: contracts/LPTokenWrapper.sol
pragma solidity =0.5.16;
contract LPTokenWrapper is MinePoolData {
using SafeMath for uint256;
function totalSupply() public view returns(uint256) {
return totalsupply;
}
function balanceOf(address account) public view returns(uint256) {
return balances[account];
}
function stake(uint256 amount) internal {
if(lp==address(0)) {
require(msg.value>0,"stake input value is is 0");
amount = msg.value;
address payable poolAddr = address(uint160(address(this)));
address(poolAddr).transfer(amount);
} else {
require(amount > 0, "cannot stake 0");
uint256 preBalance = IERC20(lp).balanceOf(address(this));
IERC20(lp).transferFrom(msg.sender,address(this), amount);
uint256 afterBalance = IERC20(lp).balanceOf(address(this));
require(afterBalance-preBalance==amount,"token stake transfer error!");
}
totalsupply = totalsupply.add(amount);
balances[msg.sender] = balances[msg.sender].add(amount);
}
function unstake (uint256 amount) internal {
totalsupply = totalsupply.sub(amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
if(lp==address(0)) {
msg.sender.transfer(amount);
} else {
uint256 preBalance = IERC20(lp).balanceOf(address(this));
IERC20(lp).transfer(msg.sender, amount);
uint256 afterBalance = IERC20(lp).balanceOf(address(this));
require(preBalance - afterBalance==amount,"token unstake transfer error!");
}
}
}
// File: contracts/MinePoolDelegate.sol
pragma solidity ^0.5.16;
contract MinePool is LPTokenWrapper {
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event HisReward(address indexed user, uint256 indexed reward,uint256 indexed idx);
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
require(now >= startTime,"not reach start time");
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
constructor(address _multiSignature)
multiSignatureClient(_multiSignature)
public
{
}
function update() onlyOwner public{
//for the future use
}
function setPoolMineAddress(address payable _liquidpool,address _phxaddress) public onlyOwner{
// require(_liquidpool != address(0));
require(_phxaddress != address(0));
lp = _liquidpool;
phx = _phxaddress;
}
function setMineRate(uint256 _reward,uint256 _duration) public onlyOwner updateReward(address(0)){
//require(_reward>0);
require(_duration>0);
//token number per seconds
rewardRate = _reward.div(_duration);
// require(rewardRate > 0);
rewardPerduration = _reward;
duration = _duration;
}
function setPeriodFinish(uint256 startime,uint256 endtime)public onlyOwner updateReward(address(0)) {
//the setting time must pass timebeing
require(startime >=now);
require(endtime > startTime);
//set new finish time
lastUpdateTime = startime;
periodFinish = endtime;
startTime = startime;
}
/**
* @dev getting back the left mine token
* @param reciever the reciever for getting back mine token
*/
function getbackLeftMiningToken(address payable reciever) public
onlyOperator(0)
validCall
{
uint256 bal = IERC20(phx).balanceOf(address(this));
IERC20(phx).transfer(reciever,bal);
if(lp==address(0)){
reciever.transfer(address(this).balance);
}
}
function setFeePara(uint256 phxFeeRatio,uint256 htFeeAmount,address payable feeReciever) onlyOwner public {
if(phxFeeRatio>0) {
_phxFeeRatio = phxFeeRatio;
}
if(htFeeAmount >0 ) {
_htFeeAmount = htFeeAmount;
}
if(feeReciever != address(0)){
_feeReciever = feeReciever;
}
}
function collectFee(address mineCoin,uint256 amount) internal returns (uint256){
if(_phxFeeRatio==0) {
return amount;
}
require(msg.value>=_htFeeAmount,"need input ht coin value 0.01");
//charged ht fee
_feeReciever.transfer(_htFeeAmount);
if (mineCoin != address(0)){
//charge phx token fee
uint256 fee = amount.mul(_phxFeeRatio).div(1000);
IERC20 token = IERC20(mineCoin);
uint256 preBalance = token.balanceOf(address(this));
//ERC20(this).safeTransfer(token,_feeReciever,fee);
token.transfer(_feeReciever, fee);
uint256 afterBalance = token.balanceOf(address(this));
require(preBalance - afterBalance == fee,"settlement token transfer error!");
return amount.sub(fee);
}
return amount;
}
//////////////////////////public function/////////////////////////////////
function lastTimeRewardApplicable() public view returns(uint256) {
uint256 timestamp = Math.max(block.timestamp,startTime);
return Math.min(timestamp,periodFinish);
}
function rewardPerToken() public view returns(uint256) {
if (totalSupply() == 0 || now < startTime) {
return rewardPerTokenStored;
}
return rewardPerTokenStored.add(
lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(totalSupply())
);
}
function earned(address account) internal view returns(uint256) {
return balanceOf(account).mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]);
}
//keep same name with old version
function totalRewards(address account) public view returns(uint256) {
return earned(account);
}
function stake(uint256 amount,bytes memory data) public updateReward(msg.sender) payable notHalted nonReentrant {
require(now < periodFinish,"over finish time");//do not allow to stake after finish
super.stake(amount);
emit Staked(msg.sender, amount);
}
function unstake(uint256 amount,bytes memory data) public updateReward(msg.sender) payable notHalted nonReentrant {
require(amount > 0, "Cannot withdraw 0");
super.unstake(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() public notHalted nonReentrant {
unstake(balanceOf(msg.sender));
getReward();
}
function getReward() public updateReward(msg.sender) payable notHalted nonReentrant {
uint256 reward = earned(msg.sender);
if (reward > 0) {
//get fee for reciever
//reward = collectFee(phx,reward);
rewards[msg.sender] = 0;
uint256 preBalance = IERC20(phx).balanceOf(address(this));
IERC20(phx).transfer(msg.sender, reward);
uint256 afterBalance = IERC20(phx).balanceOf(address(this));
require(preBalance - afterBalance==reward,"phx award transfer error!");
emit RewardPaid(msg.sender, reward);
}
}
/**
* @return Total number of distribution tokens balance.
*/
function distributionBalance() public view returns (uint256) {
return IERC20(phx).balanceOf(address(this));
}
/**
* @param addr The user to look up staking information for.
* @return The number of staking tokens deposited for addr.
*/
function totalStakedFor(address addr) public view returns (uint256) {
return super.balanceOf(addr);
}
/**
* @dev all stake token.
* @return The number of staking tokens
*/
function getMineInfo() public view returns (uint256,uint256,uint256,uint256) {
return (rewardPerduration,duration,startTime,periodFinish);
}
function getVersion() public view returns (uint256) {
return 1;
}
///////////////////////////////////////////////////////////////////////////////////////
function deposit(uint256 _pid, uint256 _amount) public payable {
bytes memory data = new bytes(1);
stake(_amount,data);
}
function withdraw(uint256 _pid, uint256 _amount) public payable{
if(_amount==0) {
getReward();
}else {
bytes memory data = new bytes(1);
unstake(_amount,data);
}
}
function allPendingReward(uint256 _pid,address _user) public view returns(uint256,uint256,uint256){
return (totalStakedFor(_user),totalRewards(_user),0);
}
function totalStaked(uint256 _pid) public view returns (uint256){
return super.totalSupply();
}
}
|
get fee for recieverreward = collectFee(phx,reward);
|
function getReward() public updateReward(msg.sender) payable notHalted nonReentrant {
uint256 reward = earned(msg.sender);
if (reward > 0) {
rewards[msg.sender] = 0;
uint256 preBalance = IERC20(phx).balanceOf(address(this));
IERC20(phx).transfer(msg.sender, reward);
uint256 afterBalance = IERC20(phx).balanceOf(address(this));
require(preBalance - afterBalance==reward,"phx award transfer error!");
emit RewardPaid(msg.sender, reward);
}
}
| 14,804,350 |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
import "../math/SafeMathUint128.sol";
import "../interfaces/IHEZToken.sol";
import "../interfaces/IHermezAuctionProtocol.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
/**
* @dev Hermez will run an auction to incentivise efficiency in coordinators,
* meaning that they need to be very effective and include as many transactions
* as they can in the slots in order to compensate for their bidding costs, gas
* costs and operations costs.The general porpouse of this smartcontract is to
* define the rules to coordinate this auction where the bids will be placed
* only in HEZ utility token.
*/
contract HermezAuctionProtocol is
Initializable,
ReentrancyGuardUpgradeable,
IHermezAuctionProtocol
{
using SafeMath128 for uint128;
struct Coordinator {
address forger; // Address allowed by the bidder to forge a batch
string coordinatorURL;
}
// The closedMinBid is the minimum bidding with which it has been closed a slot and may be
// higher than the bidAmount. This means that the funds must be returned to whoever has bid
struct SlotState {
address bidder;
bool fulfilled;
bool forgerCommitment;
uint128 bidAmount; // Since the total supply of HEZ will be less than 100M, with 128 bits it is enough to
uint128 closedMinBid; // store the bidAmount and closed minBid. bidAmount is the bidding for an specific slot.
}
// bytes4 private constant _PERMIT_SIGNATURE =
// bytes4(keccak256(bytes("permit(address,address,uint256,uint256,uint8,bytes32,bytes32)")));
bytes4 private constant _PERMIT_SIGNATURE = 0xd505accf;
// Blocks per slot
uint8 public constant BLOCKS_PER_SLOT = 40;
// Minimum bid when no one has bid yet
uint128 public constant INITIAL_MINIMAL_BIDDING = 1000000 * (1e18);
// Hermez Network Token with which the bids will be made
IHEZToken public tokenHEZ;
// HermezRollup smartcontract address
address public hermezRollup;
// Hermez Governance smartcontract address who controls some parameters and collects HEZ fee
address public governanceAddress;
// Boot Donation Address
address private _donationAddress;
// Boot Coordinator Address
address private _bootCoordinator;
// boot coordinator URL
string public bootCoordinatorURL;
// The minimum bid value in a series of 6 slots
uint128[6] private _defaultSlotSetBid;
// First block where the first slot begins
uint128 public genesisBlock;
// Number of closed slots after the current slot ( 2 Slots = 2 * 40 Blocks = 20 min )
uint16 private _closedAuctionSlots;
// Total number of open slots which you can bid ( 30 days = 4320 slots )
uint16 private _openAuctionSlots;
// How the HEZ tokens deposited by the slot winner are distributed ( Burn: 40.00% - Donation: 40.00% - HGT: 20.00% )
uint16[3] private _allocationRatio; // Two decimal precision
// Minimum outbid (percentage, two decimal precision) over the previous one to consider it valid
uint16 private _outbidding; // Two decimal precision
// Number of blocks after the beginning of a slot after which any coordinator can forge if the winner has not forged
// any batch in that slot
uint8 private _slotDeadline;
// Mapping to control slot state
mapping(uint128 => SlotState) public slots;
// Mapping to control balances pending to claim
mapping(address => uint128) public pendingBalances;
// Mapping to register all the coordinators. The address used for the mapping is the bidder address
mapping(address => Coordinator) public coordinators;
event NewBid(
uint128 indexed slot,
uint128 bidAmount,
address indexed bidder
);
event NewSlotDeadline(uint8 newSlotDeadline);
event NewClosedAuctionSlots(uint16 newClosedAuctionSlots);
event NewOutbidding(uint16 newOutbidding);
event NewDonationAddress(address indexed newDonationAddress);
event NewBootCoordinator(
address indexed newBootCoordinator,
string newBootCoordinatorURL
);
event NewOpenAuctionSlots(uint16 newOpenAuctionSlots);
event NewAllocationRatio(uint16[3] newAllocationRatio);
event SetCoordinator(
address indexed bidder,
address indexed forger,
string coordinatorURL
);
event NewForgeAllocated(
address indexed bidder,
address indexed forger,
uint128 indexed slotToForge,
uint128 burnAmount,
uint128 donationAmount,
uint128 governanceAmount
);
event NewDefaultSlotSetBid(uint128 slotSet, uint128 newInitialMinBid);
event NewForge(address indexed forger, uint128 indexed slotToForge);
event HEZClaimed(address indexed owner, uint128 amount);
// Event emitted when the contract is initialized
event InitializeHermezAuctionProtocolEvent(
address donationAddress,
address bootCoordinatorAddress,
string bootCoordinatorURL,
uint16 outbidding,
uint8 slotDeadline,
uint16 closedAuctionSlots,
uint16 openAuctionSlots,
uint16[3] allocationRatio
);
modifier onlyGovernance() {
require(
governanceAddress == msg.sender,
"HermezAuctionProtocol::onlyGovernance: ONLY_GOVERNANCE"
);
_;
}
/**
* @dev Initializer function (equivalent to the constructor). Since we use
* upgradeable smartcontracts the state vars have to be initialized here.
* @param token Hermez Network token with which the bids will be made
* @param hermezRollupAddress address authorized to forge
* @param donationAddress address that can claim donated tokens
* @param _governanceAddress Hermez Governance smartcontract
* @param bootCoordinatorAddress Boot Coordinator Address
*/
function hermezAuctionProtocolInitializer(
address token,
uint128 genesis,
address hermezRollupAddress,
address _governanceAddress,
address donationAddress,
address bootCoordinatorAddress,
string memory _bootCoordinatorURL
) public initializer {
__ReentrancyGuard_init_unchained();
require(
hermezRollupAddress != address(0),
"HermezAuctionProtocol::hermezAuctionProtocolInitializer ADDRESS_0_NOT_VALID"
);
_outbidding = 1000;
_slotDeadline = 20;
_closedAuctionSlots = 2;
_openAuctionSlots = 4320;
_allocationRatio = [4000, 4000, 2000];
_defaultSlotSetBid = [
INITIAL_MINIMAL_BIDDING,
INITIAL_MINIMAL_BIDDING,
INITIAL_MINIMAL_BIDDING,
INITIAL_MINIMAL_BIDDING,
INITIAL_MINIMAL_BIDDING,
INITIAL_MINIMAL_BIDDING
];
require(
genesis >= block.number,
"HermezAuctionProtocol::hermezAuctionProtocolInitializer GENESIS_BELOW_MINIMAL"
);
tokenHEZ = IHEZToken(token);
genesisBlock = genesis;
hermezRollup = hermezRollupAddress;
governanceAddress = _governanceAddress;
_donationAddress = donationAddress;
_bootCoordinator = bootCoordinatorAddress;
bootCoordinatorURL = _bootCoordinatorURL;
emit InitializeHermezAuctionProtocolEvent(
donationAddress,
bootCoordinatorAddress,
_bootCoordinatorURL,
_outbidding,
_slotDeadline,
_closedAuctionSlots,
_openAuctionSlots,
_allocationRatio
);
}
/**
* @notice Getter of the current `_slotDeadline`
* @return The `_slotDeadline` value
*/
function getSlotDeadline() external override view returns (uint8) {
return _slotDeadline;
}
/**
* @notice Allows to change the `_slotDeadline` if it's called by the owner
* @param newDeadline new `_slotDeadline`
* Events: `NewSlotDeadline`
*/
function setSlotDeadline(uint8 newDeadline)
external
override
onlyGovernance
{
require(
newDeadline <= BLOCKS_PER_SLOT,
"HermezAuctionProtocol::setSlotDeadline: GREATER_THAN_BLOCKS_PER_SLOT"
);
_slotDeadline = newDeadline;
emit NewSlotDeadline(_slotDeadline);
}
/**
* @notice Getter of the current `_openAuctionSlots`
* @return The `_openAuctionSlots` value
*/
function getOpenAuctionSlots() external override view returns (uint16) {
return _openAuctionSlots;
}
/**
* @notice Allows to change the `_openAuctionSlots` if it's called by the owner
* @dev Max newOpenAuctionSlots = 65536 slots
* @param newOpenAuctionSlots new `_openAuctionSlots`
* Events: `NewOpenAuctionSlots`
* Note: the governance could set this parameter equal to `ClosedAuctionSlots`, this means that it can prevent bids
* from being made and that only the boot coordinator can forge
*/
function setOpenAuctionSlots(uint16 newOpenAuctionSlots)
external
override
onlyGovernance
{
_openAuctionSlots = newOpenAuctionSlots;
emit NewOpenAuctionSlots(_openAuctionSlots);
}
/**
* @notice Getter of the current `_closedAuctionSlots`
* @return The `_closedAuctionSlots` value
*/
function getClosedAuctionSlots() external override view returns (uint16) {
return _closedAuctionSlots;
}
/**
* @notice Allows to change the `_closedAuctionSlots` if it's called by the owner
* @dev Max newClosedAuctionSlots = 65536 slots
* @param newClosedAuctionSlots new `_closedAuctionSlots`
* Events: `NewClosedAuctionSlots`
* Note: the governance could set this parameter equal to `OpenAuctionSlots`, this means that it can prevent bids
* from being made and that only the boot coordinator can forge
*/
function setClosedAuctionSlots(uint16 newClosedAuctionSlots)
external
override
onlyGovernance
{
_closedAuctionSlots = newClosedAuctionSlots;
emit NewClosedAuctionSlots(_closedAuctionSlots);
}
/**
* @notice Getter of the current `_outbidding`
* @return The `_outbidding` value
*/
function getOutbidding() external override view returns (uint16) {
return _outbidding;
}
/**
* @notice Allows to change the `_outbidding` if it's called by the owner
* @dev newOutbidding between 0.01% and 100.00%
* @param newOutbidding new `_outbidding`
* Events: `NewOutbidding`
*/
function setOutbidding(uint16 newOutbidding)
external
override
onlyGovernance
{
require(
newOutbidding > 1 && newOutbidding < 10000,
"HermezAuctionProtocol::setOutbidding: OUTBIDDING_NOT_VALID"
);
_outbidding = newOutbidding;
emit NewOutbidding(_outbidding);
}
/**
* @notice Getter of the current `_allocationRatio`
* @return The `_allocationRatio` array
*/
function getAllocationRatio()
external
override
view
returns (uint16[3] memory)
{
return _allocationRatio;
}
/**
* @notice Allows to change the `_allocationRatio` array if it's called by the owner
* @param newAllocationRatio new `_allocationRatio` uint8[3] array
* Events: `NewAllocationRatio`
*/
function setAllocationRatio(uint16[3] memory newAllocationRatio)
external
override
onlyGovernance
{
require(
newAllocationRatio[0] <= 10000 &&
newAllocationRatio[1] <= 10000 &&
newAllocationRatio[2] <= 10000 &&
newAllocationRatio[0] +
newAllocationRatio[1] +
newAllocationRatio[2] ==
10000,
"HermezAuctionProtocol::setAllocationRatio: ALLOCATION_RATIO_NOT_VALID"
);
_allocationRatio = newAllocationRatio;
emit NewAllocationRatio(_allocationRatio);
}
/**
* @notice Getter of the current `_donationAddress`
* @return The `_donationAddress`
*/
function getDonationAddress() external override view returns (address) {
return _donationAddress;
}
/**
* @notice Allows to change the `_donationAddress` if it's called by the owner
* @param newDonationAddress new `_donationAddress`
* Events: `NewDonationAddress`
*/
function setDonationAddress(address newDonationAddress)
external
override
onlyGovernance
{
require(
newDonationAddress != address(0),
"HermezAuctionProtocol::setDonationAddress: NOT_VALID_ADDRESS"
);
_donationAddress = newDonationAddress;
emit NewDonationAddress(_donationAddress);
}
/**
* @notice Getter of the current `_bootCoordinator`
* @return The `_bootCoordinator`
*/
function getBootCoordinator() external override view returns (address) {
return _bootCoordinator;
}
/**
* @notice Allows to change the `_bootCoordinator` if it's called by the owner
* @param newBootCoordinator new `_bootCoordinator` uint8[3] array
* Events: `NewBootCoordinator`
*/
function setBootCoordinator(
address newBootCoordinator,
string memory newBootCoordinatorURL
) external override onlyGovernance {
_bootCoordinator = newBootCoordinator;
bootCoordinatorURL = newBootCoordinatorURL;
emit NewBootCoordinator(_bootCoordinator, newBootCoordinatorURL);
}
/**
* @notice Returns the minimum default bid for an slotSet
* @param slotSet to obtain the minimum default bid
* @return the minimum default bid for an slotSet
*/
function getDefaultSlotSetBid(uint8 slotSet) public view returns (uint128) {
return _defaultSlotSetBid[slotSet];
}
/**
* @notice Allows to change the change the min bid for an slotSet if it's called by the owner.
* @dev If an slotSet has the value of 0 it's considered decentralized, so the minbid cannot be modified
* @param slotSet the slotSet to update
* @param newInitialMinBid the minBid
* Events: `NewDefaultSlotSetBid`
*/
function changeDefaultSlotSetBid(uint128 slotSet, uint128 newInitialMinBid)
external
override
onlyGovernance
{
require(
slotSet < _defaultSlotSetBid.length,
"HermezAuctionProtocol::changeDefaultSlotSetBid: NOT_VALID_SLOT_SET"
);
require(
_defaultSlotSetBid[slotSet] != 0,
"HermezAuctionProtocol::changeDefaultSlotSetBid: SLOT_DECENTRALIZED"
);
uint128 current = getCurrentSlotNumber();
// This prevents closed bids from being modified
for (uint128 i = current; i <= current + _closedAuctionSlots; i++) {
// Save the minbid in case it has not been previously set
if (slots[i].closedMinBid == 0) {
slots[i].closedMinBid = _defaultSlotSetBid[getSlotSet(i)];
}
}
_defaultSlotSetBid[slotSet] = newInitialMinBid;
emit NewDefaultSlotSetBid(slotSet, newInitialMinBid);
}
/**
* @notice Allows to register a new coordinator
* @dev The `msg.sender` will be considered the `bidder`, who can change the forger address and the url
* @param forger the address allowed to forger batches
* @param coordinatorURL endopoint for this coordinator
* Events: `NewCoordinator`
*/
function setCoordinator(address forger, string memory coordinatorURL)
external
override
{
require(
keccak256(abi.encodePacked(coordinatorURL)) !=
keccak256(abi.encodePacked("")),
"HermezAuctionProtocol::setCoordinator: NOT_VALID_URL"
);
coordinators[msg.sender].forger = forger;
coordinators[msg.sender].coordinatorURL = coordinatorURL;
emit SetCoordinator(msg.sender, forger, coordinatorURL);
}
/**
* @notice Returns the current slot number
* @return slotNumber an uint128 with the current slot
*/
function getCurrentSlotNumber() public view returns (uint128) {
return getSlotNumber(uint128(block.number));
}
/**
* @notice Returns the slot number of a given block
* @param blockNumber from which to calculate the slot
* @return slotNumber an uint128 with the slot calculated
*/
function getSlotNumber(uint128 blockNumber) public view returns (uint128) {
return
(blockNumber >= genesisBlock)
? ((blockNumber - genesisBlock) / BLOCKS_PER_SLOT)
: uint128(0);
}
/**
* @notice Returns an slotSet given an slot
* @param slot from which to calculate the slotSet
* @return the slotSet of the slot
*/
function getSlotSet(uint128 slot) public view returns (uint128) {
return slot.mod(uint128(_defaultSlotSetBid.length));
}
/**
* @notice gets the minimum bid that someone has to bid to win the slot for a given slot
* @dev it will revert in case of trying to obtain the minimum bid for a closed slot
* @param slot from which to get the minimum bid
* @return the minimum amount to bid
*/
function getMinBidBySlot(uint128 slot) public view returns (uint128) {
require(
slot > (getCurrentSlotNumber() + _closedAuctionSlots),
"HermezAuctionProtocol::getMinBidBySlot: AUCTION_CLOSED"
);
uint128 slotSet = getSlotSet(slot);
// If the bidAmount for a slot is 0 it means that it has not yet been bid, so the midBid will be the minimum
// bid for the slot time plus the outbidding set, otherwise it will be the bidAmount plus the outbidding
return
(slots[slot].bidAmount == 0)
? _defaultSlotSetBid[slotSet].add(
_defaultSlotSetBid[slotSet].mul(_outbidding).div(
uint128(10000) // two decimal precision
)
)
: slots[slot].bidAmount.add(
slots[slot].bidAmount.mul(_outbidding).div(uint128(10000)) // two decimal precision
);
}
/**
* @notice Function to process a single bid
* @dev If the bytes calldata permit parameter is empty the smart contract assume that it has enough allowance to
* make the transferFrom. In case you want to use permit, you need to send the data of the permit call in bytes
* @param amount the amount of tokens that have been sent
* @param slot the slot for which the caller is bidding
* @param bidAmount the amount of the bidding
*/
function processBid(
uint128 amount,
uint128 slot,
uint128 bidAmount,
bytes calldata permit
) external override {
// To avoid possible mistakes we don't allow anyone to bid without setting a forger
require(
coordinators[msg.sender].forger != address(0),
"HermezAuctionProtocol::processBid: COORDINATOR_NOT_REGISTERED"
);
require(
slot > (getCurrentSlotNumber() + _closedAuctionSlots),
"HermezAuctionProtocol::processBid: AUCTION_CLOSED"
);
require(
bidAmount >= getMinBidBySlot(slot),
"HermezAuctionProtocol::processBid: BELOW_MINIMUM"
);
require(
slot <=
(getCurrentSlotNumber() +
_closedAuctionSlots +
_openAuctionSlots),
"HermezAuctionProtocol::processBid: AUCTION_NOT_OPEN"
);
if (permit.length != 0) {
_permit(amount, permit);
}
require(
tokenHEZ.transferFrom(msg.sender, address(this), amount),
"HermezAuctionProtocol::processBid: TOKEN_TRANSFER_FAILED"
);
pendingBalances[msg.sender] = pendingBalances[msg.sender].add(amount);
require(
pendingBalances[msg.sender] >= bidAmount,
"HermezAuctionProtocol::processBid: NOT_ENOUGH_BALANCE"
);
_doBid(slot, bidAmount, msg.sender);
}
/**
* @notice function to process a multi bid
* @dev If the bytes calldata permit parameter is empty the smart contract assume that it has enough allowance to
* make the transferFrom. In case you want to use permit, you need to send the data of the permit call in bytes
* @param amount the amount of tokens that have been sent
* @param startingSlot the first slot to bid
* @param endingSlot the last slot to bid
* @param slotSets the set of slots to which the coordinator wants to bid
* @param maxBid the maximum bid that is allowed
* @param minBid the minimum that you want to bid
*/
function processMultiBid(
uint128 amount,
uint128 startingSlot,
uint128 endingSlot,
bool[6] memory slotSets,
uint128 maxBid,
uint128 minBid,
bytes calldata permit
) external override {
require(
startingSlot > (getCurrentSlotNumber() + _closedAuctionSlots),
"HermezAuctionProtocol::processMultiBid AUCTION_CLOSED"
);
require(
endingSlot <=
(getCurrentSlotNumber() +
_closedAuctionSlots +
_openAuctionSlots),
"HermezAuctionProtocol::processMultiBid AUCTION_NOT_OPEN"
);
require(
maxBid >= minBid,
"HermezAuctionProtocol::processMultiBid MAXBID_GREATER_THAN_MINBID"
);
// To avoid possible mistakes we don't allow anyone to bid without setting a forger
require(
coordinators[msg.sender].forger != address(0),
"HermezAuctionProtocol::processMultiBid COORDINATOR_NOT_REGISTERED"
);
if (permit.length != 0) {
_permit(amount, permit);
}
require(
tokenHEZ.transferFrom(msg.sender, address(this), amount),
"HermezAuctionProtocol::processMultiBid: TOKEN_TRANSFER_FAILED"
);
pendingBalances[msg.sender] = pendingBalances[msg.sender].add(amount);
uint128 bidAmount;
for (uint128 slot = startingSlot; slot <= endingSlot; slot++) {
uint128 minBidBySlot = getMinBidBySlot(slot);
// In case that the minimum bid is below the desired minimum bid, we will use this lower limit as the bid
if (minBidBySlot <= minBid) {
bidAmount = minBid;
// If the `minBidBySlot` is between the upper (`maxBid`) and lower limit (`minBid`) we will use
// this value `minBidBySlot` as the bid
} else if (minBidBySlot > minBid && minBidBySlot <= maxBid) {
bidAmount = minBidBySlot;
// if the `minBidBySlot` is higher than the upper limit `maxBid`, we will not bid for this slot
} else {
continue;
}
// check if it is a selected slotSet
if (slotSets[getSlotSet(slot)]) {
require(
pendingBalances[msg.sender] >= bidAmount,
"HermezAuctionProtocol::processMultiBid NOT_ENOUGH_BALANCE"
);
_doBid(slot, bidAmount, msg.sender);
}
}
}
/**
* @notice function to call token permit function
* @param _amount the quantity that is expected to be allowed
* @param _permitData the raw data of the call `permit` of the token
*/
function _permit(uint256 _amount, bytes calldata _permitData) internal {
bytes4 sig = abi.decode(_permitData, (bytes4));
require(
sig == _PERMIT_SIGNATURE,
"HermezAuctionProtocol::_permit: NOT_VALID_CALL"
);
(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) = abi.decode(
_permitData[4:],
(address, address, uint256, uint256, uint8, bytes32, bytes32)
);
require(
owner == msg.sender,
"HermezAuctionProtocol::_permit: OWNER_NOT_EQUAL_SENDER"
);
require(
spender == address(this),
"HermezAuctionProtocol::_permit: SPENDER_NOT_EQUAL_THIS"
);
require(
value == _amount,
"HermezAuctionProtocol::_permit: WRONG_AMOUNT"
);
// we call without checking the result, in case it fails and he doesn't have enough balance
// the following transferFrom should be fail. This prevents DoS attacks from using a signature
// before the smartcontract call
/* solhint-disable avoid-low-level-calls avoid-call-value */
address(tokenHEZ).call(
abi.encodeWithSelector(
_PERMIT_SIGNATURE,
owner,
spender,
value,
deadline,
v,
r,
s
)
);
}
/**
* @notice Internal function to make the bid
* @dev will only be called by processBid or processMultiBid
* @param slot the slot for which the caller is bidding
* @param bidAmount the amount of the bidding
* @param bidder the address of the bidder
* Events: `NewBid`
*/
function _doBid(
uint128 slot,
uint128 bidAmount,
address bidder
) private {
address prevBidder = slots[slot].bidder;
uint128 prevBidValue = slots[slot].bidAmount;
require(
bidAmount > prevBidValue,
"HermezAuctionProtocol::_doBid: BID_MUST_BE_HIGHER"
);
pendingBalances[bidder] = pendingBalances[bidder].sub(bidAmount);
slots[slot].bidder = bidder;
slots[slot].bidAmount = bidAmount;
// If there is a previous bid we must return the HEZ tokens
if (prevBidder != address(0) && prevBidValue != 0) {
pendingBalances[prevBidder] = pendingBalances[prevBidder].add(
prevBidValue
);
}
emit NewBid(slot, bidAmount, bidder);
}
/**
* @notice function to know if a certain address can forge into a certain block
* @param forger the address of the coodirnator's forger
* @param blockNumber block number to check
* @return a bool true in case it can forge, false otherwise
*/
function canForge(address forger, uint256 blockNumber)
external
override
view
returns (bool)
{
return _canForge(forger, blockNumber);
}
/**
* @notice function to know if a certain address can forge into a certain block
* @param forger the address of the coodirnator's forger
* @param blockNumber block number to check
* @return a bool true in case it can forge, false otherwise
*/
function _canForge(address forger, uint256 blockNumber)
internal
view
returns (bool)
{
require(
blockNumber < 2**128,
"HermezAuctionProtocol::canForge WRONG_BLOCKNUMBER"
);
require(
blockNumber >= genesisBlock,
"HermezAuctionProtocol::canForge AUCTION_NOT_STARTED"
);
uint128 slotToForge = getSlotNumber(uint128(blockNumber));
// Get the relativeBlock to check if the slotDeadline has been exceeded
uint128 relativeBlock = uint128(blockNumber).sub(
(slotToForge.mul(BLOCKS_PER_SLOT)).add(genesisBlock)
);
// If the closedMinBid is 0 it means that we have to take as minBid the one that is set for this slot set,
// otherwise the one that has been saved will be used
uint128 minBid = (slots[slotToForge].closedMinBid == 0)
? _defaultSlotSetBid[getSlotSet(slotToForge)]
: slots[slotToForge].closedMinBid;
// if the relative block has exceeded the slotDeadline and no batch has been forged, anyone can forge
if (
!slots[slotToForge].forgerCommitment &&
(relativeBlock >= _slotDeadline)
) {
return true;
//if forger bidAmount has exceeded the minBid it can forge
} else if (
(coordinators[slots[slotToForge].bidder].forger == forger) &&
(slots[slotToForge].bidAmount >= minBid)
) {
return true;
//if it's the boot coordinator and it has not been bid or the bid is below the minimum it can forge
} else if (
(_bootCoordinator == forger) &&
((slots[slotToForge].bidAmount < minBid) ||
(slots[slotToForge].bidAmount == 0))
) {
return true;
// if it is not any of these three cases will not be able to forge
} else {
return false;
}
}
/**
* @notice function to process the forging
* @param forger the address of the coodirnator's forger
* Events: `NewForgeAllocated` and `NewForge`
*/
function forge(address forger) external override {
require(
msg.sender == hermezRollup,
"HermezAuctionProtocol::forge: ONLY_HERMEZ_ROLLUP"
);
require(
_canForge(forger, block.number),
"HermezAuctionProtocol::forge: CANNOT_FORGE"
);
uint128 slotToForge = getCurrentSlotNumber();
if (!slots[slotToForge].forgerCommitment) {
// Get the relativeBlock to check if the slotDeadline has been exceeded
uint128 relativeBlock = uint128(block.number).sub(
(slotToForge.mul(BLOCKS_PER_SLOT)).add(genesisBlock)
);
if (relativeBlock < _slotDeadline) {
slots[slotToForge].forgerCommitment = true;
}
}
// Default values:** Burn: 40% - Donation: 40% - HGT: 20%
// Allocated is used to know if we have already distributed the HEZ tokens
if (!slots[slotToForge].fulfilled) {
slots[slotToForge].fulfilled = true;
if (slots[slotToForge].bidAmount != 0) {
// If the closedMinBid is 0 it means that we have to take as minBid the one that is set for this slot set,
// otherwise the one that has been saved will be used
uint128 minBid = (slots[slotToForge].closedMinBid == 0)
? _defaultSlotSetBid[getSlotSet(slotToForge)]
: slots[slotToForge].closedMinBid;
// If the bootcoordinator is forging and there has been a previous bid that is lower than the slot min bid,
// we must return the tokens to the bidder and the tokens have not been distributed
if (slots[slotToForge].bidAmount < minBid) {
// We save the minBid that this block has had
pendingBalances[slots[slotToForge]
.bidder] = pendingBalances[slots[slotToForge].bidder]
.add(slots[slotToForge].bidAmount);
// In case the winner is forging we have to allocate the tokens according to the desired distribution
} else {
uint128 bidAmount = slots[slotToForge].bidAmount;
// calculation of token distribution
uint128 amountToBurn = bidAmount
.mul(_allocationRatio[0])
.div(uint128(10000)); // Two decimal precision
uint128 donationAmount = bidAmount
.mul(_allocationRatio[1])
.div(uint128(10000)); // Two decimal precision
uint128 governanceAmount = bidAmount
.mul(_allocationRatio[2])
.div(uint128(10000)); // Two decimal precision
// Tokens to burn
require(
tokenHEZ.burn(amountToBurn),
"HermezAuctionProtocol::forge: TOKEN_BURN_FAILED"
);
// Tokens to donate
pendingBalances[_donationAddress] = pendingBalances[_donationAddress]
.add(donationAmount);
// Tokens for the governace address
pendingBalances[governanceAddress] = pendingBalances[governanceAddress]
.add(governanceAmount);
emit NewForgeAllocated(
slots[slotToForge].bidder,
forger,
slotToForge,
amountToBurn,
donationAmount,
governanceAmount
);
}
}
}
emit NewForge(forger, slotToForge);
}
function claimPendingHEZ(uint128 slot) public {
require(
slot < getCurrentSlotNumber(),
"HermezAuctionProtocol::claimPendingHEZ: ONLY_IF_PREVIOUS_SLOT"
);
require(
!slots[slot].fulfilled,
"HermezAuctionProtocol::claimPendingHEZ: ONLY_IF_NOT_FULFILLED"
);
// If the closedMinBid is 0 it means that we have to take as minBid the one that is set for this slot set,
// otherwise the one that has been saved will be used
uint128 minBid = (slots[slot].closedMinBid == 0)
? _defaultSlotSetBid[getSlotSet(slot)]
: slots[slot].closedMinBid;
require(
slots[slot].bidAmount < minBid,
"HermezAuctionProtocol::claimPendingHEZ: ONLY_IF_NOT_FULFILLED"
);
slots[slot].closedMinBid = minBid;
slots[slot].fulfilled = true;
pendingBalances[slots[slot].bidder] = pendingBalances[slots[slot]
.bidder]
.add(slots[slot].bidAmount);
}
/**
* @notice function to know how much HEZ tokens are pending to be claimed for an address
* @param bidder address to query
* @return the total claimable HEZ by an address
*/
function getClaimableHEZ(address bidder) public view returns (uint128) {
return pendingBalances[bidder];
}
/**
* @notice distributes the tokens to msg.sender address
* Events: `HEZClaimed`
*/
function claimHEZ() public nonReentrant {
uint128 pending = getClaimableHEZ(msg.sender);
require(
pending > 0,
"HermezAuctionProtocol::claimHEZ: NOT_ENOUGH_BALANCE"
);
pendingBalances[msg.sender] = 0;
require(
tokenHEZ.transfer(msg.sender, pending),
"HermezAuctionProtocol::claimHEZ: TOKEN_TRANSFER_FAILED"
);
emit HEZClaimed(msg.sender, pending);
}
}
// SPDX-License-Identifier: AGPL-3.0
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 SafeMath128 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint128 a, uint128 b) internal pure returns (uint128) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b <= a, errorMessage);
uint128 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint128 a, uint128 b) internal pure returns (uint128) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint128 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint128 a, uint128 b) internal pure returns (uint128) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b > 0, errorMessage);
uint128 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint128 a, uint128 b) internal pure returns (uint128) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
interface IHEZToken {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function burn(uint256 value) external returns (bool);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
/**
* @dev Hermez will run an auction to incentivise efficiency in coordinators,
* meaning that they need to be very effective and include as many transactions
* as they can in the slots in order to compensate for their bidding costs, gas
* costs and operations costs.The general porpouse of this smartcontract is to
* define the rules to coordinate this auction where the bids will be placed
* only in HEZ utility token.
*/
interface IHermezAuctionProtocol {
/**
* @notice Getter of the current `_slotDeadline`
* @return The `_slotDeadline` value
*/
function getSlotDeadline() external view returns (uint8);
/**
* @notice Allows to change the `_slotDeadline` if it's called by the owner
* @param newDeadline new `_slotDeadline`
* Events: `NewSlotDeadline`
*/
function setSlotDeadline(uint8 newDeadline) external;
/**
* @notice Getter of the current `_openAuctionSlots`
* @return The `_openAuctionSlots` value
*/
function getOpenAuctionSlots() external view returns (uint16);
/**
* @notice Allows to change the `_openAuctionSlots` if it's called by the owner
* @dev Max newOpenAuctionSlots = 65536 slots
* @param newOpenAuctionSlots new `_openAuctionSlots`
* Events: `NewOpenAuctionSlots`
* Note: the governance could set this parameter equal to `ClosedAuctionSlots`, this means that it can prevent bids
* from being made and that only the boot coordinator can forge
*/
function setOpenAuctionSlots(uint16 newOpenAuctionSlots) external;
/**
* @notice Getter of the current `_closedAuctionSlots`
* @return The `_closedAuctionSlots` value
*/
function getClosedAuctionSlots() external view returns (uint16);
/**
* @notice Allows to change the `_closedAuctionSlots` if it's called by the owner
* @dev Max newClosedAuctionSlots = 65536 slots
* @param newClosedAuctionSlots new `_closedAuctionSlots`
* Events: `NewClosedAuctionSlots`
* Note: the governance could set this parameter equal to `OpenAuctionSlots`, this means that it can prevent bids
* from being made and that only the boot coordinator can forge
*/
function setClosedAuctionSlots(uint16 newClosedAuctionSlots) external;
/**
* @notice Getter of the current `_outbidding`
* @return The `_outbidding` value
*/
function getOutbidding() external view returns (uint16);
/**
* @notice Allows to change the `_outbidding` if it's called by the owner
* @dev newOutbidding between 0.00% and 655.36%
* @param newOutbidding new `_outbidding`
* Events: `NewOutbidding`
*/
function setOutbidding(uint16 newOutbidding) external;
/**
* @notice Getter of the current `_allocationRatio`
* @return The `_allocationRatio` array
*/
function getAllocationRatio() external view returns (uint16[3] memory);
/**
* @notice Allows to change the `_allocationRatio` array if it's called by the owner
* @param newAllocationRatio new `_allocationRatio` uint8[3] array
* Events: `NewAllocationRatio`
*/
function setAllocationRatio(uint16[3] memory newAllocationRatio) external;
/**
* @notice Getter of the current `_donationAddress`
* @return The `_donationAddress`
*/
function getDonationAddress() external view returns (address);
/**
* @notice Allows to change the `_donationAddress` if it's called by the owner
* @param newDonationAddress new `_donationAddress`
* Events: `NewDonationAddress`
*/
function setDonationAddress(address newDonationAddress) external;
/**
* @notice Getter of the current `_bootCoordinator`
* @return The `_bootCoordinator`
*/
function getBootCoordinator() external view returns (address);
/**
* @notice Allows to change the `_bootCoordinator` if it's called by the owner
* @param newBootCoordinator new `_bootCoordinator` uint8[3] array
* Events: `NewBootCoordinator`
*/
function setBootCoordinator(
address newBootCoordinator,
string memory newBootCoordinatorURL
) external;
/**
* @notice Allows to change the change the min bid for an slotSet if it's called by the owner.
* @dev If an slotSet has the value of 0 it's considered decentralized, so the minbid cannot be modified
* @param slotSet the slotSet to update
* @param newInitialMinBid the minBid
* Events: `NewDefaultSlotSetBid`
*/
function changeDefaultSlotSetBid(uint128 slotSet, uint128 newInitialMinBid)
external;
/**
* @notice Allows to register a new coordinator
* @dev The `msg.sender` will be considered the `bidder`, who can change the forger address and the url
* @param forger the address allowed to forger batches
* @param coordinatorURL endopoint for this coordinator
* Events: `NewCoordinator`
*/
function setCoordinator(address forger, string memory coordinatorURL)
external;
/**
* @notice Function to process a single bid
* @dev If the bytes calldata permit parameter is empty the smart contract assume that it has enough allowance to
* make the transferFrom. In case you want to use permit, you need to send the data of the permit call in bytes
* @param amount the amount of tokens that have been sent
* @param slot the slot for which the caller is bidding
* @param bidAmount the amount of the bidding
*/
function processBid(
uint128 amount,
uint128 slot,
uint128 bidAmount,
bytes calldata permit
) external;
/**
* @notice function to process a multi bid
* @dev If the bytes calldata permit parameter is empty the smart contract assume that it has enough allowance to
* make the transferFrom. In case you want to use permit, you need to send the data of the permit call in bytes
* @param amount the amount of tokens that have been sent
* @param startingSlot the first slot to bid
* @param endingSlot the last slot to bid
* @param slotSets the set of slots to which the coordinator wants to bid
* @param maxBid the maximum bid that is allowed
* @param minBid the minimum that you want to bid
*/
function processMultiBid(
uint128 amount,
uint128 startingSlot,
uint128 endingSlot,
bool[6] memory slotSets,
uint128 maxBid,
uint128 minBid,
bytes calldata permit
) external;
/**
* @notice function to process the forging
* @param forger the address of the coodirnator's forger
* Events: `NewForgeAllocated` and `NewForge`
*/
function forge(address forger) external;
/**
* @notice function to know if a certain address can forge into a certain block
* @param forger the address of the coodirnator's forger
* @param blockNumber block number to check
* @return a bool true in case it can forge, false otherwise
*/
function canForge(address forger, uint256 blockNumber)
external
view
returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.24 <0.7.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
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;
}
|
Allows to change the `_donationAddress` if it's called by the owner newDonationAddress new `_donationAddress` Events: `NewDonationAddress`/
|
function setDonationAddress(address newDonationAddress)
external
override
onlyGovernance
{
require(
newDonationAddress != address(0),
"HermezAuctionProtocol::setDonationAddress: NOT_VALID_ADDRESS"
);
_donationAddress = newDonationAddress;
emit NewDonationAddress(_donationAddress);
}
| 11,841,094 |
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import "./zksync/ReentrancyGuard.sol";
import "./zksync/Events.sol";
import "./Storage.sol";
import "./zksync/Bytes.sol";
import "./zksync/Utils.sol";
import "./zksync/SafeMath.sol";
import "./zksync/SafeCast.sol";
/// @title ZkLink periphery contract
/// @author zk.link
contract ZkLinkPeriphery is ReentrancyGuard, Storage, Events {
using SafeMath for uint256;
// =================User interface=================
/// @notice Checks if Exodus mode must be entered. If true - enters exodus mode and emits ExodusMode event.
/// @dev Exodus mode must be entered in case of current ethereum block number is higher than the oldest
/// of existed priority requests expiration block number.
function activateExodusMode() external active {
bool trigger = block.number >= priorityRequests[firstPriorityRequestId].expirationBlock &&
priorityRequests[firstPriorityRequestId].expirationBlock != 0;
if (trigger) {
exodusMode = true;
emit ExodusMode();
}
}
/// @notice Withdraws token from ZkLink to root chain in case of exodus mode. User must provide proof that he owns funds
/// @param _storedBlockInfo Last verified block
/// @param _owner Owner of the account
/// @param _accountId Id of the account in the tree
/// @param _subAccountId Id of the subAccount in the tree
/// @param _proof Proof
/// @param _tokenId The token want to withdraw
/// @param _amount Amount for owner (must be total amount, not part of it)
function performExodus(
StoredBlockInfo calldata _storedBlockInfo,
address _owner,
uint32 _accountId,
uint8 _subAccountId,
uint16 _tokenId,
uint128 _amount,
uint256[] calldata _proof
) external notActive {
// ===Checks===
// performed exodus MUST not be already exited
require(!performedExodus[_accountId][_subAccountId][_tokenId], "y0");
// incorrect stored block info
require(storedBlockHashes[totalBlocksExecuted] == hashStoredBlockInfo(_storedBlockInfo), "y1");
// exit proof MUST be correct
bool proofCorrect = verifier.verifyExitProof(_storedBlockInfo.stateHash, CHAIN_ID, _accountId, _subAccountId, _owner, _tokenId, _amount, _proof);
require(proofCorrect, "y2");
// ===Effects===
performedExodus[_accountId][_subAccountId][_tokenId] = true;
bytes22 packedBalanceKey = packAddressAndTokenId(_owner, _tokenId);
increaseBalanceToWithdraw(packedBalanceKey, _amount);
emit WithdrawalPending(_tokenId, _owner, _amount);
}
/// @notice Accrues users balances from deposit priority requests in Exodus mode
/// @dev WARNING: Only for Exodus mode
/// Canceling may take several separate transactions to be completed
/// @param _n number of requests to process
/// @param _depositsPubdata deposit details
function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] calldata _depositsPubdata) external notActive {
// ===Checks===
uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n);
require(toProcess > 0, "A0");
// ===Effects===
uint64 currentDepositIdx = 0;
for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; ++id) {
Operations.PriorityOperation memory pr = priorityRequests[id];
if (pr.opType == Operations.OpType.Deposit) {
bytes memory depositPubdata = _depositsPubdata[currentDepositIdx];
require(Utils.hashBytesToBytes20(depositPubdata) == pr.hashedPubData, "A1");
++currentDepositIdx;
Operations.Deposit memory op = Operations.readDepositPubdata(depositPubdata);
bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, op.tokenId);
increaseBalanceToWithdraw(packedBalanceKey, op.amount);
}
delete priorityRequests[id];
}
// overflow is impossible
firstPriorityRequestId += toProcess;
totalOpenPriorityRequests -= toProcess;
}
/// @notice Set data for changing pubkey hash using onchain authorization.
/// Transaction author (msg.sender) should be L2 account address
/// New pubkey hash can be reset, to do that user should send two transactions:
/// 1) First `setAuthPubkeyHash` transaction for already used `_nonce` will set timer.
/// 2) After `AUTH_FACT_RESET_TIMELOCK` time is passed second `setAuthPubkeyHash` transaction will reset pubkey hash for `_nonce`.
/// @param _pubkeyHash New pubkey hash
/// @param _nonce Nonce of the change pubkey L2 transaction
function setAuthPubkeyHash(bytes calldata _pubkeyHash, uint32 _nonce) external active {
require(_pubkeyHash.length == PUBKEY_HASH_BYTES, "B0"); // PubKeyHash should be 20 bytes.
if (authFacts[msg.sender][_nonce] == bytes32(0)) {
authFacts[msg.sender][_nonce] = keccak256(_pubkeyHash);
} else {
uint256 currentResetTimer = authFactsResetTimer[msg.sender][_nonce];
if (currentResetTimer == 0) {
authFactsResetTimer[msg.sender][_nonce] = block.timestamp;
} else {
require(block.timestamp.sub(currentResetTimer) >= AUTH_FACT_RESET_TIMELOCK, "B1"); // too early to reset auth
authFactsResetTimer[msg.sender][_nonce] = 0;
authFacts[msg.sender][_nonce] = keccak256(_pubkeyHash);
}
}
}
/// @notice Returns amount of tokens that can be withdrawn by `address` from zkLink contract
/// @param _address Address of the tokens owner
/// @param _tokenId Token id
/// @return The pending balance can be withdrawn
function getPendingBalance(address _address, uint16 _tokenId) external view returns (uint128) {
return pendingBalances[packAddressAndTokenId(_address, _tokenId)];
}
// =======================Governance interface======================
/// @notice Change current governor
/// @param _newGovernor Address of the new governor
function changeGovernor(address _newGovernor) external onlyGovernor {
require(_newGovernor != address(0), "H");
if (networkGovernor != _newGovernor) {
networkGovernor = _newGovernor;
emit NewGovernor(_newGovernor);
}
}
/// @notice Add token to the list of networks tokens
/// @param _tokenId Token id
/// @param _tokenAddress Token address
/// @param _standard If token is a standard erc20
/// @param _mappingTokenId The mapping token id at l2
function addToken(uint16 _tokenId, address _tokenAddress, bool _standard, uint16 _mappingTokenId) public onlyGovernor {
// token id MUST be in a valid range
require(_tokenId > 0 && _tokenId < MAX_AMOUNT_OF_REGISTERED_TOKENS, "I0");
// token MUST be not zero address
require(_tokenAddress != address(0), "I1");
// revert duplicate register
RegisteredToken memory rt = tokens[_tokenId];
require(!rt.registered, "I2");
require(tokenIds[_tokenAddress] == 0, "I2");
rt.registered = true;
rt.tokenAddress = _tokenAddress;
rt.standard = _standard;
rt.mappingTokenId = _mappingTokenId;
tokens[_tokenId] = rt;
tokenIds[_tokenAddress] = _tokenId;
emit NewToken(_tokenId, _tokenAddress);
}
/// @notice Add tokens to the list of networks tokens
/// @param _tokenIdList Token id list
/// @param _tokenAddressList Token address list
/// @param _standardList Token standard list
/// @param _mappingTokenList Mapping token list
function addTokens(uint16[] calldata _tokenIdList, address[] calldata _tokenAddressList, bool[] calldata _standardList, uint16[] calldata _mappingTokenList) external {
for (uint i; i < _tokenIdList.length; i++) {
addToken(_tokenIdList[i], _tokenAddressList[i], _standardList[i], _mappingTokenList[i]);
}
}
/// @notice Pause token deposits for the given token
/// @param _tokenId Token id
/// @param _tokenPaused Token paused status
function setTokenPaused(uint16 _tokenId, bool _tokenPaused) external onlyGovernor {
RegisteredToken memory rt = tokens[_tokenId];
require(rt.registered, "K");
if (rt.paused != _tokenPaused) {
rt.paused = _tokenPaused;
tokens[_tokenId] = rt;
emit TokenPausedUpdate(_tokenId, _tokenPaused);
}
}
/// @notice Change validator status (active or not active)
/// @param _validator Validator address
/// @param _active Active flag
function setValidator(address _validator, bool _active) external onlyGovernor {
if (validators[_validator] != _active) {
validators[_validator] = _active;
emit ValidatorStatusUpdate(_validator, _active);
}
}
/// @notice Add a new bridge
/// @param bridge the bridge contract
function addBridge(address bridge) external onlyGovernor {
require(bridge != address(0), "L0");
// the index of non-exist bridge is zero
require(bridgeIndex[bridge] == 0, "L1");
BridgeInfo memory info = BridgeInfo({
bridge: bridge,
enableBridgeTo: true,
enableBridgeFrom: true
});
bridges.push(info);
bridgeIndex[bridge] = bridges.length;
emit AddBridge(bridge);
}
/// @notice Update bridge info
/// @dev If we want to remove a bridge(not compromised), we should firstly set `enableBridgeTo` to false
/// and wait all messages received from this bridge and then set `enableBridgeFrom` to false.
/// But when a bridge is compromised, we must set both `enableBridgeTo` and `enableBridgeFrom` to false immediately
/// @param index the bridge info index
/// @param enableBridgeTo if set to false, bridge to will be disabled
/// @param enableBridgeFrom if set to false, bridge from will be disabled
function updateBridge(uint256 index, bool enableBridgeTo, bool enableBridgeFrom) external onlyGovernor {
require(index < bridges.length, "M");
BridgeInfo memory info = bridges[index];
info.enableBridgeTo = enableBridgeTo;
info.enableBridgeFrom = enableBridgeFrom;
bridges[index] = info;
emit UpdateBridge(index, enableBridgeTo, enableBridgeFrom);
}
function isBridgeToEnabled(address bridge) external view returns (bool) {
uint256 index = bridgeIndex[bridge] - 1;
BridgeInfo memory info = bridges[index];
return info.bridge == bridge && info.enableBridgeTo;
}
function isBridgeFromEnabled(address bridge) public view returns (bool) {
uint256 index = bridgeIndex[bridge] - 1;
BridgeInfo memory info = bridges[index];
return info.bridge == bridge && info.enableBridgeFrom;
}
// =======================Cross chain block synchronization======================
/// @notice Combine the `progress` of the other chains of a `syncHash` with self
function receiveSynchronizationProgress(bytes32 syncHash, uint256 progress) external {
require(isBridgeFromEnabled(msg.sender), "C");
synchronizedChains[syncHash] = synchronizedChains[syncHash] | progress;
}
/// @notice Get synchronized progress of current chain known
function getSynchronizedProgress(StoredBlockInfo memory _block) public view returns (uint256 progress) {
progress = synchronizedChains[_block.syncHash];
// combine the current chain if it has proven this block
if (_block.blockNumber <= totalBlocksProven &&
hashStoredBlockInfo(_block) == storedBlockHashes[_block.blockNumber]) {
progress |= CHAIN_INDEX;
} else {
// to prevent bridge from delivering a wrong progress
progress &= ~CHAIN_INDEX;
}
}
/// @notice Check if received all syncHash from other chains at the block height
function syncBlocks(StoredBlockInfo memory _block) external nonReentrant {
uint256 progress = getSynchronizedProgress(_block);
require(progress == ALL_CHAINS, "D0");
uint32 blockNumber = _block.blockNumber;
require(blockNumber > totalBlocksSynchronized, "D1");
totalBlocksSynchronized = blockNumber;
}
// =======================Fast withdraw and Accept======================
/// @notice Accepter accept a eth fast withdraw, accepter will get a fee for profit
/// @param accepter Accepter who accept a fast withdraw
/// @param accountId Account that request fast withdraw
/// @param receiver User receive token from accepter (the owner of withdraw operation)
/// @param amount The amount of withdraw operation
/// @param withdrawFeeRate Fast withdraw fee rate taken by accepter
/// @param nonce Account nonce, used to produce unique accept info
function acceptETH(address accepter,
uint32 accountId,
address payable receiver,
uint128 amount,
uint16 withdrawFeeRate,
uint32 nonce) external payable nonReentrant {
// ===Checks===
uint16 tokenId = tokenIds[ETH_ADDRESS];
(uint128 amountReceive, bytes32 hash, ) =
_checkAccept(accepter, accountId, receiver, tokenId, amount, withdrawFeeRate, nonce);
// ===Effects===
accepts[accountId][hash] = accepter;
// ===Interactions===
// make sure msg value >= amountReceive
uint256 amountReturn = msg.value.sub(amountReceive);
// do not use send or call to make more security
receiver.transfer(amountReceive);
// if send too more eth then return back to msg sender
if (amountReturn > 0) {
// it's safe to use call to msg.sender and can send all gas left to it
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = msg.sender.call{value: amountReturn}("");
require(success, "E");
}
emit Accept(accepter, accountId, receiver, tokenId, amountReceive, amountReceive);
}
/// @notice Accepter accept a erc20 token fast withdraw, accepter will get a fee for profit
/// @param accepter Accepter who accept a fast withdraw
/// @param accountId Account that request fast withdraw
/// @param receiver User receive token from accepter (the owner of withdraw operation)
/// @param tokenId Token id
/// @param amount The amount of withdraw operation
/// @param withdrawFeeRate Fast withdraw fee rate taken by accepter
/// @param nonce Account nonce, used to produce unique accept info
/// @param amountTransfer Amount that transfer from accepter to receiver
/// may be a litter larger than the amount receiver received
function acceptERC20(address accepter,
uint32 accountId,
address receiver,
uint16 tokenId,
uint128 amount,
uint16 withdrawFeeRate,
uint32 nonce,
uint128 amountTransfer) external nonReentrant {
// ===Checks===
(uint128 amountReceive, bytes32 hash, address tokenAddress) =
_checkAccept(accepter, accountId, receiver, tokenId, amount, withdrawFeeRate, nonce);
// ===Effects===
accepts[accountId][hash] = accepter;
// ===Interactions===
// stack too deep
uint128 amountSent;
{
address _accepter = accepter;
address _receiver = receiver;
uint256 receiverBalanceBefore = IERC20(tokenAddress).balanceOf(_receiver);
uint256 accepterBalanceBefore = IERC20(tokenAddress).balanceOf(_accepter);
IERC20(tokenAddress).transferFrom(_accepter, _receiver, amountTransfer);
uint256 receiverBalanceAfter = IERC20(tokenAddress).balanceOf(_receiver);
uint256 accepterBalanceAfter = IERC20(tokenAddress).balanceOf(_accepter);
uint128 receiverBalanceDiff = SafeCast.toUint128(receiverBalanceAfter.sub(receiverBalanceBefore));
require(receiverBalanceDiff >= amountReceive, "F0");
amountReceive = receiverBalanceDiff;
// amountSent may be larger than amountReceive when the token is a non standard erc20 token
amountSent = SafeCast.toUint128(accepterBalanceBefore.sub(accepterBalanceAfter));
}
if (msg.sender != accepter) {
require(brokerAllowance(tokenId, accepter, msg.sender) >= amountSent, "F1");
brokerAllowances[tokenId][accepter][msg.sender] -= amountSent;
}
emit Accept(accepter, accountId, receiver, tokenId, amountSent, amountReceive);
}
function brokerAllowance(uint16 tokenId, address owner, address spender) public view returns (uint128) {
return brokerAllowances[tokenId][owner][spender];
}
/// @notice Give allowance to spender to call accept
function brokerApprove(uint16 tokenId, address spender, uint128 amount) external returns (bool) {
require(spender != address(0), "G");
brokerAllowances[tokenId][msg.sender][spender] = amount;
emit BrokerApprove(tokenId, msg.sender, spender, amount);
return true;
}
function _checkAccept(address accepter,
uint32 accountId,
address receiver,
uint16 tokenId,
uint128 amount,
uint16 withdrawFeeRate,
uint32 nonce) internal active view returns (uint128 amountReceive, bytes32 hash, address tokenAddress) {
// accepter and receiver MUST be set and MUST not be the same
require(accepter != address(0), "H0");
require(receiver != address(0), "H1");
require(receiver != accepter, "H2");
// token MUST be registered to ZkLink
RegisteredToken memory rt = tokens[tokenId];
require(rt.registered, "H3");
tokenAddress = rt.tokenAddress;
// feeRate MUST be valid
amountReceive = amount * (MAX_ACCEPT_FEE_RATE - withdrawFeeRate) / MAX_ACCEPT_FEE_RATE;
require(amountReceive > 0 && amountReceive <= amount, "H4");
// nonce MUST not be zero
require(nonce > 0, "H5");
// accept tx may be later than block exec tx(with user withdraw op)
hash = keccak256(abi.encodePacked(receiver, tokenId, amount, withdrawFeeRate, nonce));
require(accepts[accountId][hash] == address(0), "H6");
}
}
|
Add tokens to the list of networks tokens _tokenIdList Token id list _tokenAddressList Token address list _standardList Token standard list _mappingTokenList Mapping token list
|
function addTokens(uint16[] calldata _tokenIdList, address[] calldata _tokenAddressList, bool[] calldata _standardList, uint16[] calldata _mappingTokenList) external {
for (uint i; i < _tokenIdList.length; i++) {
addToken(_tokenIdList[i], _tokenAddressList[i], _standardList[i], _mappingTokenList[i]);
}
}
| 13,005,396 |
/**
*Submitted for verification at Etherscan.io on 2021-03-25
*/
pragma solidity =0.6.6;
interface IBoxswapV2Factory {
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 IBoxswapV2Pair {
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 IBoxswapV2Router01 {
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 IBoxswapV2Router02 is IBoxswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
contract BoxswapV2Router02 is IBoxswapV2Router02 {
using SafeMath for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'BoxswapV2Router: EXPIRED');
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IBoxswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IBoxswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = BoxswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = BoxswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'BoxswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = BoxswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'BoxswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = BoxswapV2Library.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = IBoxswapV2Pair(pair).mint(to);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = BoxswapV2Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IBoxswapV2Pair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = BoxswapV2Library.pairFor(factory, tokenA, tokenB);
IBoxswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = IBoxswapV2Pair(pair).burn(to);
(address token0,) = BoxswapV2Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'BoxswapV2Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'BoxswapV2Router: INSUFFICIENT_B_AMOUNT');
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountA, uint amountB) {
address pair = BoxswapV2Library.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
IBoxswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = BoxswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IBoxswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = BoxswapV2Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
IBoxswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = BoxswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? BoxswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
IBoxswapV2Pair(BoxswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = BoxswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'BoxswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, BoxswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = BoxswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'BoxswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, BoxswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'BoxswapV2Router: INVALID_PATH');
amounts = BoxswapV2Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'BoxswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(BoxswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'BoxswapV2Router: INVALID_PATH');
amounts = BoxswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'BoxswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, BoxswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'BoxswapV2Router: INVALID_PATH');
amounts = BoxswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'BoxswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, BoxswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == WETH, 'BoxswapV2Router: INVALID_PATH');
amounts = BoxswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'BoxswapV2Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(BoxswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = BoxswapV2Library.sortTokens(input, output);
IBoxswapV2Pair pair = IBoxswapV2Pair(BoxswapV2Library.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = BoxswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? BoxswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, BoxswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'BoxswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == WETH, 'BoxswapV2Router: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(BoxswapV2Library.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'BoxswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == WETH, 'BoxswapV2Router: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, BoxswapV2Library.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'BoxswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return BoxswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return BoxswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return BoxswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return BoxswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return BoxswapV2Library.getAmountsIn(factory, amountOut, path);
}
}
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
library BoxswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'BoxswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'BoxswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'29d9c546cce82f1f6a907b2a801a3df962da69b1139b8ed95c8b67d999cf06e4' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IBoxswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'BoxswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'BoxswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'BoxswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'BoxswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(992);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'BoxswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'BoxswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(992);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'BoxswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'BoxswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
|
refund dust eth, if any
|
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = BoxswapV2Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = IBoxswapV2Pair(pair).mint(to);
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
}
| 10,838,952 |
pragma solidity ^0.4.18;
/**
* @title Owned contract with safe ownership pass.
*
* Note: all the non constant functions return false instead of throwing in case if state change
* didn't happen yet.
*/
contract Owned {
/**
* Contract owner address
*/
address public contractOwner;
/**
* Contract owner address
*/
address public pendingContractOwner;
function Owned() {
contractOwner = msg.sender;
}
/**
* @dev Owner check modifier
*/
modifier onlyContractOwner() {
if (contractOwner == msg.sender) {
_;
}
}
/**
* @dev Destroy contract and scrub a data
* @notice Only owner can call it
*/
function destroy() onlyContractOwner {
suicide(msg.sender);
}
/**
* Prepares ownership pass.
*
* Can only be called by current owner.
*
* @param _to address of the next owner. 0x0 is not allowed.
*
* @return success.
*/
function changeContractOwnership(address _to) onlyContractOwner() returns(bool) {
if (_to == 0x0) {
return false;
}
pendingContractOwner = _to;
return true;
}
/**
* Finalize ownership pass.
*
* Can only be called by pending owner.
*
* @return success.
*/
function claimContractOwnership() returns(bool) {
if (pendingContractOwner != msg.sender) {
return false;
}
contractOwner = pendingContractOwner;
delete pendingContractOwner;
return true;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/// @title Provides possibility manage holders? country limits and limits for holders.
contract DataControllerInterface {
/// @notice Checks user is holder.
/// @param _address - checking address.
/// @return `true` if _address is registered holder, `false` otherwise.
function isHolderAddress(address _address) public view returns (bool);
function allowance(address _user) public view returns (uint);
function changeAllowance(address _holder, uint _value) public returns (uint);
}
/// @title ServiceController
///
/// Base implementation
/// Serves for managing service instances
contract ServiceControllerInterface {
/// @notice Check target address is service
/// @param _address target address
/// @return `true` when an address is a service, `false` otherwise
function isService(address _address) public view returns (bool);
}
contract ATxAssetInterface {
DataControllerInterface public dataController;
ServiceControllerInterface public serviceController;
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool);
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool);
function __approve(address _spender, uint _value, address _sender) public returns (bool);
function __process(bytes /*_data*/, address /*_sender*/) payable public {
revert();
}
}
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}
contract AssetProxy is ERC20 {
bytes32 public smbl;
address public platform;
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool);
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool);
function __approve(address _spender, uint _value, address _sender) public returns (bool);
function getLatestVersion() public returns (address);
function init(address _bmcPlatform, string _symbol, string _name) public;
function proposeUpgrade(address _newVersion) public;
}
contract BasicAsset is ATxAssetInterface {
// Assigned asset proxy contract, immutable.
address public proxy;
/**
* Only assigned proxy is allowed to call.
*/
modifier onlyProxy() {
if (proxy == msg.sender) {
_;
}
}
/**
* Sets asset proxy address.
*
* Can be set only once.
*
* @param _proxy asset proxy contract address.
*
* @return success.
* @dev function is final, and must not be overridden.
*/
function init(address _proxy) public returns (bool) {
if (address(proxy) != 0x0) {
return false;
}
proxy = _proxy;
return true;
}
/**
* Passes execution into virtual function.
*
* Can only be called by assigned asset proxy.
*
* @return success.
* @dev function is final, and must not be overridden.
*/
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public onlyProxy returns (bool) {
return _transferWithReference(_to, _value, _reference, _sender);
}
/**
* Passes execution into virtual function.
*
* Can only be called by assigned asset proxy.
*
* @return success.
* @dev function is final, and must not be overridden.
*/
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public onlyProxy returns (bool) {
return _transferFromWithReference(_from, _to, _value, _reference, _sender);
}
/**
* Passes execution into virtual function.
*
* Can only be called by assigned asset proxy.
*
* @return success.
* @dev function is final, and must not be overridden.
*/
function __approve(address _spender, uint _value, address _sender) public onlyProxy returns (bool) {
return _approve(_spender, _value, _sender);
}
/**
* Calls back without modifications.
*
* @return success.
* @dev function is virtual, and meant to be overridden.
*/
function _transferWithReference(address _to, uint _value, string _reference, address _sender) internal returns (bool) {
return AssetProxy(proxy).__transferWithReference(_to, _value, _reference, _sender);
}
/**
* Calls back without modifications.
*
* @return success.
* @dev function is virtual, and meant to be overridden.
*/
function _transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) internal returns (bool) {
return AssetProxy(proxy).__transferFromWithReference(_from, _to, _value, _reference, _sender);
}
/**
* Calls back without modifications.
*
* @return success.
* @dev function is virtual, and meant to be overridden.
*/
function _approve(address _spender, uint _value, address _sender) internal returns (bool) {
return AssetProxy(proxy).__approve(_spender, _value, _sender);
}
}
/// @title ServiceAllowance.
///
/// Provides a way to delegate operation allowance decision to a service contract
contract ServiceAllowance {
function isTransferAllowed(address _from, address _to, address _sender, address _token, uint _value) public view returns (bool);
}
contract ERC20Interface {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
}
/**
* @title Generic owned destroyable contract
*/
contract Object is Owned {
/**
* Common result code. Means everything is fine.
*/
uint constant OK = 1;
uint constant OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER = 8;
function withdrawnTokens(address[] tokens, address _to) onlyContractOwner returns(uint) {
for(uint i=0;i<tokens.length;i++) {
address token = tokens[i];
uint balance = ERC20Interface(token).balanceOf(this);
if(balance != 0)
ERC20Interface(token).transfer(_to,balance);
}
return OK;
}
function checkOnlyContractOwner() internal constant returns(uint) {
if (contractOwner == msg.sender) {
return OK;
}
return OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER;
}
}
contract GroupsAccessManagerEmitter {
event UserCreated(address user);
event UserDeleted(address user);
event GroupCreated(bytes32 groupName);
event GroupActivated(bytes32 groupName);
event GroupDeactivated(bytes32 groupName);
event UserToGroupAdded(address user, bytes32 groupName);
event UserFromGroupRemoved(address user, bytes32 groupName);
}
/// @title Group Access Manager
///
/// Base implementation
/// This contract serves as group manager
contract GroupsAccessManager is Object, GroupsAccessManagerEmitter {
uint constant USER_MANAGER_SCOPE = 111000;
uint constant USER_MANAGER_MEMBER_ALREADY_EXIST = USER_MANAGER_SCOPE + 1;
uint constant USER_MANAGER_GROUP_ALREADY_EXIST = USER_MANAGER_SCOPE + 2;
uint constant USER_MANAGER_OBJECT_ALREADY_SECURED = USER_MANAGER_SCOPE + 3;
uint constant USER_MANAGER_CONFIRMATION_HAS_COMPLETED = USER_MANAGER_SCOPE + 4;
uint constant USER_MANAGER_USER_HAS_CONFIRMED = USER_MANAGER_SCOPE + 5;
uint constant USER_MANAGER_NOT_ENOUGH_GAS = USER_MANAGER_SCOPE + 6;
uint constant USER_MANAGER_INVALID_INVOCATION = USER_MANAGER_SCOPE + 7;
uint constant USER_MANAGER_DONE = USER_MANAGER_SCOPE + 11;
uint constant USER_MANAGER_CANCELLED = USER_MANAGER_SCOPE + 12;
using SafeMath for uint;
struct Member {
address addr;
uint groupsCount;
mapping(bytes32 => uint) groupName2index;
mapping(uint => uint) index2globalIndex;
}
struct Group {
bytes32 name;
uint priority;
uint membersCount;
mapping(address => uint) memberAddress2index;
mapping(uint => uint) index2globalIndex;
}
uint public membersCount;
mapping(uint => address) index2memberAddress;
mapping(address => uint) memberAddress2index;
mapping(address => Member) address2member;
uint public groupsCount;
mapping(uint => bytes32) index2groupName;
mapping(bytes32 => uint) groupName2index;
mapping(bytes32 => Group) groupName2group;
mapping(bytes32 => bool) public groupsBlocked; // if groupName => true, then couldn't be used for confirmation
function() payable public {
revert();
}
/// @notice Register user
/// Can be called only by contract owner
///
/// @param _user user address
///
/// @return code
function registerUser(address _user) external onlyContractOwner returns (uint) {
require(_user != 0x0);
if (isRegisteredUser(_user)) {
return USER_MANAGER_MEMBER_ALREADY_EXIST;
}
uint _membersCount = membersCount.add(1);
membersCount = _membersCount;
memberAddress2index[_user] = _membersCount;
index2memberAddress[_membersCount] = _user;
address2member[_user] = Member(_user, 0);
UserCreated(_user);
return OK;
}
/// @notice Discard user registration
/// Can be called only by contract owner
///
/// @param _user user address
///
/// @return code
function unregisterUser(address _user) external onlyContractOwner returns (uint) {
require(_user != 0x0);
uint _memberIndex = memberAddress2index[_user];
if (_memberIndex == 0 || address2member[_user].groupsCount != 0) {
return USER_MANAGER_INVALID_INVOCATION;
}
uint _membersCount = membersCount;
delete memberAddress2index[_user];
if (_memberIndex != _membersCount) {
address _lastUser = index2memberAddress[_membersCount];
index2memberAddress[_memberIndex] = _lastUser;
memberAddress2index[_lastUser] = _memberIndex;
}
delete address2member[_user];
delete index2memberAddress[_membersCount];
delete memberAddress2index[_user];
membersCount = _membersCount.sub(1);
UserDeleted(_user);
return OK;
}
/// @notice Create group
/// Can be called only by contract owner
///
/// @param _groupName group name
/// @param _priority group priority
///
/// @return code
function createGroup(bytes32 _groupName, uint _priority) external onlyContractOwner returns (uint) {
require(_groupName != bytes32(0));
if (isGroupExists(_groupName)) {
return USER_MANAGER_GROUP_ALREADY_EXIST;
}
uint _groupsCount = groupsCount.add(1);
groupName2index[_groupName] = _groupsCount;
index2groupName[_groupsCount] = _groupName;
groupName2group[_groupName] = Group(_groupName, _priority, 0);
groupsCount = _groupsCount;
GroupCreated(_groupName);
return OK;
}
/// @notice Change group status
/// Can be called only by contract owner
///
/// @param _groupName group name
/// @param _blocked block status
///
/// @return code
function changeGroupActiveStatus(bytes32 _groupName, bool _blocked) external onlyContractOwner returns (uint) {
require(isGroupExists(_groupName));
groupsBlocked[_groupName] = _blocked;
return OK;
}
/// @notice Add users in group
/// Can be called only by contract owner
///
/// @param _groupName group name
/// @param _users user array
///
/// @return code
function addUsersToGroup(bytes32 _groupName, address[] _users) external onlyContractOwner returns (uint) {
require(isGroupExists(_groupName));
Group storage _group = groupName2group[_groupName];
uint _groupMembersCount = _group.membersCount;
for (uint _userIdx = 0; _userIdx < _users.length; ++_userIdx) {
address _user = _users[_userIdx];
uint _memberIndex = memberAddress2index[_user];
require(_memberIndex != 0);
if (_group.memberAddress2index[_user] != 0) {
continue;
}
_groupMembersCount = _groupMembersCount.add(1);
_group.memberAddress2index[_user] = _groupMembersCount;
_group.index2globalIndex[_groupMembersCount] = _memberIndex;
_addGroupToMember(_user, _groupName);
UserToGroupAdded(_user, _groupName);
}
_group.membersCount = _groupMembersCount;
return OK;
}
/// @notice Remove users in group
/// Can be called only by contract owner
///
/// @param _groupName group name
/// @param _users user array
///
/// @return code
function removeUsersFromGroup(bytes32 _groupName, address[] _users) external onlyContractOwner returns (uint) {
require(isGroupExists(_groupName));
Group storage _group = groupName2group[_groupName];
uint _groupMembersCount = _group.membersCount;
for (uint _userIdx = 0; _userIdx < _users.length; ++_userIdx) {
address _user = _users[_userIdx];
uint _memberIndex = memberAddress2index[_user];
uint _groupMemberIndex = _group.memberAddress2index[_user];
if (_memberIndex == 0 || _groupMemberIndex == 0) {
continue;
}
if (_groupMemberIndex != _groupMembersCount) {
uint _lastUserGlobalIndex = _group.index2globalIndex[_groupMembersCount];
address _lastUser = index2memberAddress[_lastUserGlobalIndex];
_group.index2globalIndex[_groupMemberIndex] = _lastUserGlobalIndex;
_group.memberAddress2index[_lastUser] = _groupMemberIndex;
}
delete _group.memberAddress2index[_user];
delete _group.index2globalIndex[_groupMembersCount];
_groupMembersCount = _groupMembersCount.sub(1);
_removeGroupFromMember(_user, _groupName);
UserFromGroupRemoved(_user, _groupName);
}
_group.membersCount = _groupMembersCount;
return OK;
}
/// @notice Check is user registered
///
/// @param _user user address
///
/// @return status
function isRegisteredUser(address _user) public view returns (bool) {
return memberAddress2index[_user] != 0;
}
/// @notice Check is user in group
///
/// @param _groupName user array
/// @param _user user array
///
/// @return status
function isUserInGroup(bytes32 _groupName, address _user) public view returns (bool) {
return isRegisteredUser(_user) && address2member[_user].groupName2index[_groupName] != 0;
}
/// @notice Check is group exist
///
/// @param _groupName group name
///
/// @return status
function isGroupExists(bytes32 _groupName) public view returns (bool) {
return groupName2index[_groupName] != 0;
}
/// @notice Get current group names
///
/// @return group names
function getGroups() public view returns (bytes32[] _groups) {
uint _groupsCount = groupsCount;
_groups = new bytes32[](_groupsCount);
for (uint _groupIdx = 0; _groupIdx < _groupsCount; ++_groupIdx) {
_groups[_groupIdx] = index2groupName[_groupIdx + 1];
}
}
// PRIVATE
function _removeGroupFromMember(address _user, bytes32 _groupName) private {
Member storage _member = address2member[_user];
uint _memberGroupsCount = _member.groupsCount;
uint _memberGroupIndex = _member.groupName2index[_groupName];
if (_memberGroupIndex != _memberGroupsCount) {
uint _lastGroupGlobalIndex = _member.index2globalIndex[_memberGroupsCount];
bytes32 _lastGroupName = index2groupName[_lastGroupGlobalIndex];
_member.index2globalIndex[_memberGroupIndex] = _lastGroupGlobalIndex;
_member.groupName2index[_lastGroupName] = _memberGroupIndex;
}
delete _member.groupName2index[_groupName];
delete _member.index2globalIndex[_memberGroupsCount];
_member.groupsCount = _memberGroupsCount.sub(1);
}
function _addGroupToMember(address _user, bytes32 _groupName) private {
Member storage _member = address2member[_user];
uint _memberGroupsCount = _member.groupsCount.add(1);
_member.groupName2index[_groupName] = _memberGroupsCount;
_member.index2globalIndex[_memberGroupsCount] = groupName2index[_groupName];
_member.groupsCount = _memberGroupsCount;
}
}
contract PendingManagerEmitter {
event PolicyRuleAdded(bytes4 sig, address contractAddress, bytes32 key, bytes32 groupName, uint acceptLimit, uint declinesLimit);
event PolicyRuleRemoved(bytes4 sig, address contractAddress, bytes32 key, bytes32 groupName);
event ProtectionTxAdded(bytes32 key, bytes32 sig, uint blockNumber);
event ProtectionTxAccepted(bytes32 key, address indexed sender, bytes32 groupNameVoted);
event ProtectionTxDone(bytes32 key);
event ProtectionTxDeclined(bytes32 key, address indexed sender, bytes32 groupNameVoted);
event ProtectionTxCancelled(bytes32 key);
event ProtectionTxVoteRevoked(bytes32 key, address indexed sender, bytes32 groupNameVoted);
event TxDeleted(bytes32 key);
event Error(uint errorCode);
function _emitError(uint _errorCode) internal returns (uint) {
Error(_errorCode);
return _errorCode;
}
}
contract PendingManagerInterface {
function signIn(address _contract) external returns (uint);
function signOut(address _contract) external returns (uint);
function addPolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName,
uint _acceptLimit,
uint _declineLimit
)
external returns (uint);
function removePolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName
)
external returns (uint);
function addTx(bytes32 _key, bytes4 _sig, address _contract) external returns (uint);
function deleteTx(bytes32 _key) external returns (uint);
function accept(bytes32 _key, bytes32 _votingGroupName) external returns (uint);
function decline(bytes32 _key, bytes32 _votingGroupName) external returns (uint);
function revoke(bytes32 _key) external returns (uint);
function hasConfirmedRecord(bytes32 _key) public view returns (uint);
function getPolicyDetails(bytes4 _sig, address _contract) public view returns (
bytes32[] _groupNames,
uint[] _acceptLimits,
uint[] _declineLimits,
uint _totalAcceptedLimit,
uint _totalDeclinedLimit
);
}
/// @title PendingManager
///
/// Base implementation
/// This contract serves as pending manager for transaction status
contract PendingManager is Object, PendingManagerEmitter, PendingManagerInterface {
uint constant NO_RECORDS_WERE_FOUND = 4;
uint constant PENDING_MANAGER_SCOPE = 4000;
uint constant PENDING_MANAGER_INVALID_INVOCATION = PENDING_MANAGER_SCOPE + 1;
uint constant PENDING_MANAGER_HASNT_VOTED = PENDING_MANAGER_SCOPE + 2;
uint constant PENDING_DUPLICATE_TX = PENDING_MANAGER_SCOPE + 3;
uint constant PENDING_MANAGER_CONFIRMED = PENDING_MANAGER_SCOPE + 4;
uint constant PENDING_MANAGER_REJECTED = PENDING_MANAGER_SCOPE + 5;
uint constant PENDING_MANAGER_IN_PROCESS = PENDING_MANAGER_SCOPE + 6;
uint constant PENDING_MANAGER_TX_DOESNT_EXIST = PENDING_MANAGER_SCOPE + 7;
uint constant PENDING_MANAGER_TX_WAS_DECLINED = PENDING_MANAGER_SCOPE + 8;
uint constant PENDING_MANAGER_TX_WAS_NOT_CONFIRMED = PENDING_MANAGER_SCOPE + 9;
uint constant PENDING_MANAGER_INSUFFICIENT_GAS = PENDING_MANAGER_SCOPE + 10;
uint constant PENDING_MANAGER_POLICY_NOT_FOUND = PENDING_MANAGER_SCOPE + 11;
using SafeMath for uint;
enum GuardState {
Decline, Confirmed, InProcess
}
struct Requirements {
bytes32 groupName;
uint acceptLimit;
uint declineLimit;
}
struct Policy {
uint groupsCount;
mapping(uint => Requirements) participatedGroups; // index => globalGroupIndex
mapping(bytes32 => uint) groupName2index; // groupName => localIndex
uint totalAcceptedLimit;
uint totalDeclinedLimit;
uint securesCount;
mapping(uint => uint) index2txIndex;
mapping(uint => uint) txIndex2index;
}
struct Vote {
bytes32 groupName;
bool accepted;
}
struct Guard {
GuardState state;
uint basePolicyIndex;
uint alreadyAccepted;
uint alreadyDeclined;
mapping(address => Vote) votes; // member address => vote
mapping(bytes32 => uint) acceptedCount; // groupName => how many from group has already accepted
mapping(bytes32 => uint) declinedCount; // groupName => how many from group has already declined
}
address public accessManager;
mapping(address => bool) public authorized;
uint public policiesCount;
mapping(uint => bytes32) index2PolicyId; // index => policy hash
mapping(bytes32 => uint) policyId2Index; // policy hash => index
mapping(bytes32 => Policy) policyId2policy; // policy hash => policy struct
uint public txCount;
mapping(uint => bytes32) index2txKey;
mapping(bytes32 => uint) txKey2index; // tx key => index
mapping(bytes32 => Guard) txKey2guard;
/// @dev Execution is allowed only by authorized contract
modifier onlyAuthorized {
if (authorized[msg.sender] || address(this) == msg.sender) {
_;
}
}
/// @dev Pending Manager's constructor
///
/// @param _accessManager access manager's address
function PendingManager(address _accessManager) public {
require(_accessManager != 0x0);
accessManager = _accessManager;
}
function() payable public {
revert();
}
/// @notice Update access manager address
///
/// @param _accessManager access manager's address
function setAccessManager(address _accessManager) external onlyContractOwner returns (uint) {
require(_accessManager != 0x0);
accessManager = _accessManager;
return OK;
}
/// @notice Sign in contract
///
/// @param _contract contract's address
function signIn(address _contract) external onlyContractOwner returns (uint) {
require(_contract != 0x0);
authorized[_contract] = true;
return OK;
}
/// @notice Sign out contract
///
/// @param _contract contract's address
function signOut(address _contract) external onlyContractOwner returns (uint) {
require(_contract != 0x0);
delete authorized[_contract];
return OK;
}
/// @notice Register new policy rule
/// Can be called only by contract owner
///
/// @param _sig target method signature
/// @param _contract target contract address
/// @param _groupName group's name
/// @param _acceptLimit accepted vote limit
/// @param _declineLimit decline vote limit
///
/// @return code
function addPolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName,
uint _acceptLimit,
uint _declineLimit
)
onlyContractOwner
external
returns (uint)
{
require(_sig != 0x0);
require(_contract != 0x0);
require(GroupsAccessManager(accessManager).isGroupExists(_groupName));
require(_acceptLimit != 0);
require(_declineLimit != 0);
bytes32 _policyHash = keccak256(_sig, _contract);
if (policyId2Index[_policyHash] == 0) {
uint _policiesCount = policiesCount.add(1);
index2PolicyId[_policiesCount] = _policyHash;
policyId2Index[_policyHash] = _policiesCount;
policiesCount = _policiesCount;
}
Policy storage _policy = policyId2policy[_policyHash];
uint _policyGroupsCount = _policy.groupsCount;
if (_policy.groupName2index[_groupName] == 0) {
_policyGroupsCount += 1;
_policy.groupName2index[_groupName] = _policyGroupsCount;
_policy.participatedGroups[_policyGroupsCount].groupName = _groupName;
_policy.groupsCount = _policyGroupsCount;
}
uint _previousAcceptLimit = _policy.participatedGroups[_policyGroupsCount].acceptLimit;
uint _previousDeclineLimit = _policy.participatedGroups[_policyGroupsCount].declineLimit;
_policy.participatedGroups[_policyGroupsCount].acceptLimit = _acceptLimit;
_policy.participatedGroups[_policyGroupsCount].declineLimit = _declineLimit;
_policy.totalAcceptedLimit = _policy.totalAcceptedLimit.sub(_previousAcceptLimit).add(_acceptLimit);
_policy.totalDeclinedLimit = _policy.totalDeclinedLimit.sub(_previousDeclineLimit).add(_declineLimit);
PolicyRuleAdded(_sig, _contract, _policyHash, _groupName, _acceptLimit, _declineLimit);
return OK;
}
/// @notice Remove policy rule
/// Can be called only by contract owner
///
/// @param _groupName group's name
///
/// @return code
function removePolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName
)
onlyContractOwner
external
returns (uint)
{
require(_sig != bytes4(0));
require(_contract != 0x0);
require(GroupsAccessManager(accessManager).isGroupExists(_groupName));
bytes32 _policyHash = keccak256(_sig, _contract);
Policy storage _policy = policyId2policy[_policyHash];
uint _policyGroupNameIndex = _policy.groupName2index[_groupName];
if (_policyGroupNameIndex == 0) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
uint _policyGroupsCount = _policy.groupsCount;
if (_policyGroupNameIndex != _policyGroupsCount) {
Requirements storage _requirements = _policy.participatedGroups[_policyGroupsCount];
_policy.participatedGroups[_policyGroupNameIndex] = _requirements;
_policy.groupName2index[_requirements.groupName] = _policyGroupNameIndex;
}
_policy.totalAcceptedLimit = _policy.totalAcceptedLimit.sub(_policy.participatedGroups[_policyGroupsCount].acceptLimit);
_policy.totalDeclinedLimit = _policy.totalDeclinedLimit.sub(_policy.participatedGroups[_policyGroupsCount].declineLimit);
delete _policy.groupName2index[_groupName];
delete _policy.participatedGroups[_policyGroupsCount];
_policy.groupsCount = _policyGroupsCount.sub(1);
PolicyRuleRemoved(_sig, _contract, _policyHash, _groupName);
return OK;
}
/// @notice Add transaction
///
/// @param _key transaction id
///
/// @return code
function addTx(bytes32 _key, bytes4 _sig, address _contract) external onlyAuthorized returns (uint) {
require(_key != bytes32(0));
require(_sig != bytes4(0));
require(_contract != 0x0);
bytes32 _policyHash = keccak256(_sig, _contract);
require(isPolicyExist(_policyHash));
if (isTxExist(_key)) {
return _emitError(PENDING_DUPLICATE_TX);
}
if (_policyHash == bytes32(0)) {
return _emitError(PENDING_MANAGER_POLICY_NOT_FOUND);
}
uint _index = txCount.add(1);
txCount = _index;
index2txKey[_index] = _key;
txKey2index[_key] = _index;
Guard storage _guard = txKey2guard[_key];
_guard.basePolicyIndex = policyId2Index[_policyHash];
_guard.state = GuardState.InProcess;
Policy storage _policy = policyId2policy[_policyHash];
uint _counter = _policy.securesCount.add(1);
_policy.securesCount = _counter;
_policy.index2txIndex[_counter] = _index;
_policy.txIndex2index[_index] = _counter;
ProtectionTxAdded(_key, _policyHash, block.number);
return OK;
}
/// @notice Delete transaction
/// @param _key transaction id
/// @return code
function deleteTx(bytes32 _key) external onlyContractOwner returns (uint) {
require(_key != bytes32(0));
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
uint _txsCount = txCount;
uint _txIndex = txKey2index[_key];
if (_txIndex != _txsCount) {
bytes32 _last = index2txKey[txCount];
index2txKey[_txIndex] = _last;
txKey2index[_last] = _txIndex;
}
delete txKey2index[_key];
delete index2txKey[_txsCount];
txCount = _txsCount.sub(1);
uint _basePolicyIndex = txKey2guard[_key].basePolicyIndex;
Policy storage _policy = policyId2policy[index2PolicyId[_basePolicyIndex]];
uint _counter = _policy.securesCount;
uint _policyTxIndex = _policy.txIndex2index[_txIndex];
if (_policyTxIndex != _counter) {
uint _movedTxIndex = _policy.index2txIndex[_counter];
_policy.index2txIndex[_policyTxIndex] = _movedTxIndex;
_policy.txIndex2index[_movedTxIndex] = _policyTxIndex;
}
delete _policy.index2txIndex[_counter];
delete _policy.txIndex2index[_txIndex];
_policy.securesCount = _counter.sub(1);
TxDeleted(_key);
return OK;
}
/// @notice Accept transaction
/// Can be called only by registered user in GroupsAccessManager
///
/// @param _key transaction id
///
/// @return code
function accept(bytes32 _key, bytes32 _votingGroupName) external returns (uint) {
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
if (!GroupsAccessManager(accessManager).isUserInGroup(_votingGroupName, msg.sender)) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Guard storage _guard = txKey2guard[_key];
if (_guard.state != GuardState.InProcess) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
if (_guard.votes[msg.sender].groupName != bytes32(0) && _guard.votes[msg.sender].accepted) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Policy storage _policy = policyId2policy[index2PolicyId[_guard.basePolicyIndex]];
uint _policyGroupIndex = _policy.groupName2index[_votingGroupName];
uint _groupAcceptedVotesCount = _guard.acceptedCount[_votingGroupName];
if (_groupAcceptedVotesCount == _policy.participatedGroups[_policyGroupIndex].acceptLimit) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
_guard.votes[msg.sender] = Vote(_votingGroupName, true);
_guard.acceptedCount[_votingGroupName] = _groupAcceptedVotesCount + 1;
uint _alreadyAcceptedCount = _guard.alreadyAccepted + 1;
_guard.alreadyAccepted = _alreadyAcceptedCount;
ProtectionTxAccepted(_key, msg.sender, _votingGroupName);
if (_alreadyAcceptedCount == _policy.totalAcceptedLimit) {
_guard.state = GuardState.Confirmed;
ProtectionTxDone(_key);
}
return OK;
}
/// @notice Decline transaction
/// Can be called only by registered user in GroupsAccessManager
///
/// @param _key transaction id
///
/// @return code
function decline(bytes32 _key, bytes32 _votingGroupName) external returns (uint) {
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
if (!GroupsAccessManager(accessManager).isUserInGroup(_votingGroupName, msg.sender)) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Guard storage _guard = txKey2guard[_key];
if (_guard.state != GuardState.InProcess) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
if (_guard.votes[msg.sender].groupName != bytes32(0) && !_guard.votes[msg.sender].accepted) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Policy storage _policy = policyId2policy[index2PolicyId[_guard.basePolicyIndex]];
uint _policyGroupIndex = _policy.groupName2index[_votingGroupName];
uint _groupDeclinedVotesCount = _guard.declinedCount[_votingGroupName];
if (_groupDeclinedVotesCount == _policy.participatedGroups[_policyGroupIndex].declineLimit) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
_guard.votes[msg.sender] = Vote(_votingGroupName, false);
_guard.declinedCount[_votingGroupName] = _groupDeclinedVotesCount + 1;
uint _alreadyDeclinedCount = _guard.alreadyDeclined + 1;
_guard.alreadyDeclined = _alreadyDeclinedCount;
ProtectionTxDeclined(_key, msg.sender, _votingGroupName);
if (_alreadyDeclinedCount == _policy.totalDeclinedLimit) {
_guard.state = GuardState.Decline;
ProtectionTxCancelled(_key);
}
return OK;
}
/// @notice Revoke user votes for transaction
/// Can be called only by contract owner
///
/// @param _key transaction id
/// @param _user target user address
///
/// @return code
function forceRejectVotes(bytes32 _key, address _user) external onlyContractOwner returns (uint) {
return _revoke(_key, _user);
}
/// @notice Revoke vote for transaction
/// Can be called only by authorized user
/// @param _key transaction id
/// @return code
function revoke(bytes32 _key) external returns (uint) {
return _revoke(_key, msg.sender);
}
/// @notice Check transaction status
/// @param _key transaction id
/// @return code
function hasConfirmedRecord(bytes32 _key) public view returns (uint) {
require(_key != bytes32(0));
if (!isTxExist(_key)) {
return NO_RECORDS_WERE_FOUND;
}
Guard storage _guard = txKey2guard[_key];
return _guard.state == GuardState.InProcess
? PENDING_MANAGER_IN_PROCESS
: _guard.state == GuardState.Confirmed
? OK
: PENDING_MANAGER_REJECTED;
}
/// @notice Check policy details
///
/// @return _groupNames group names included in policies
/// @return _acceptLimits accept limit for group
/// @return _declineLimits decline limit for group
function getPolicyDetails(bytes4 _sig, address _contract)
public
view
returns (
bytes32[] _groupNames,
uint[] _acceptLimits,
uint[] _declineLimits,
uint _totalAcceptedLimit,
uint _totalDeclinedLimit
) {
require(_sig != bytes4(0));
require(_contract != 0x0);
bytes32 _policyHash = keccak256(_sig, _contract);
uint _policyIdx = policyId2Index[_policyHash];
if (_policyIdx == 0) {
return;
}
Policy storage _policy = policyId2policy[_policyHash];
uint _policyGroupsCount = _policy.groupsCount;
_groupNames = new bytes32[](_policyGroupsCount);
_acceptLimits = new uint[](_policyGroupsCount);
_declineLimits = new uint[](_policyGroupsCount);
for (uint _idx = 0; _idx < _policyGroupsCount; ++_idx) {
Requirements storage _requirements = _policy.participatedGroups[_idx + 1];
_groupNames[_idx] = _requirements.groupName;
_acceptLimits[_idx] = _requirements.acceptLimit;
_declineLimits[_idx] = _requirements.declineLimit;
}
(_totalAcceptedLimit, _totalDeclinedLimit) = (_policy.totalAcceptedLimit, _policy.totalDeclinedLimit);
}
/// @notice Check policy include target group
/// @param _policyHash policy hash (sig, contract address)
/// @param _groupName group id
/// @return bool
function isGroupInPolicy(bytes32 _policyHash, bytes32 _groupName) public view returns (bool) {
Policy storage _policy = policyId2policy[_policyHash];
return _policy.groupName2index[_groupName] != 0;
}
/// @notice Check is policy exist
/// @param _policyHash policy hash (sig, contract address)
/// @return bool
function isPolicyExist(bytes32 _policyHash) public view returns (bool) {
return policyId2Index[_policyHash] != 0;
}
/// @notice Check is transaction exist
/// @param _key transaction id
/// @return bool
function isTxExist(bytes32 _key) public view returns (bool){
return txKey2index[_key] != 0;
}
function _updateTxState(Policy storage _policy, Guard storage _guard, uint confirmedAmount, uint declineAmount) private {
if (declineAmount != 0 && _guard.state != GuardState.Decline) {
_guard.state = GuardState.Decline;
} else if (confirmedAmount >= _policy.groupsCount && _guard.state != GuardState.Confirmed) {
_guard.state = GuardState.Confirmed;
} else if (_guard.state != GuardState.InProcess) {
_guard.state = GuardState.InProcess;
}
}
function _revoke(bytes32 _key, address _user) private returns (uint) {
require(_key != bytes32(0));
require(_user != 0x0);
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
Guard storage _guard = txKey2guard[_key];
if (_guard.state != GuardState.InProcess) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
bytes32 _votedGroupName = _guard.votes[_user].groupName;
if (_votedGroupName == bytes32(0)) {
return _emitError(PENDING_MANAGER_HASNT_VOTED);
}
bool isAcceptedVote = _guard.votes[_user].accepted;
if (isAcceptedVote) {
_guard.acceptedCount[_votedGroupName] = _guard.acceptedCount[_votedGroupName].sub(1);
_guard.alreadyAccepted = _guard.alreadyAccepted.sub(1);
} else {
_guard.declinedCount[_votedGroupName] = _guard.declinedCount[_votedGroupName].sub(1);
_guard.alreadyDeclined = _guard.alreadyDeclined.sub(1);
}
delete _guard.votes[_user];
ProtectionTxVoteRevoked(_key, _user, _votedGroupName);
return OK;
}
}
/// @title MultiSigAdapter
///
/// Abstract implementation
/// This contract serves as transaction signer
contract MultiSigAdapter is Object {
uint constant MULTISIG_ADDED = 3;
uint constant NO_RECORDS_WERE_FOUND = 4;
modifier isAuthorized {
if (msg.sender == contractOwner || msg.sender == getPendingManager()) {
_;
}
}
/// @notice Get pending address
/// @dev abstract. Needs child implementation
///
/// @return pending address
function getPendingManager() public view returns (address);
/// @notice Sign current transaction and add it to transaction pending queue
///
/// @return code
function _multisig(bytes32 _args, uint _block) internal returns (uint _code) {
bytes32 _txHash = _getKey(_args, _block);
address _manager = getPendingManager();
_code = PendingManager(_manager).hasConfirmedRecord(_txHash);
if (_code != NO_RECORDS_WERE_FOUND) {
return _code;
}
if (OK != PendingManager(_manager).addTx(_txHash, msg.sig, address(this))) {
revert();
}
return MULTISIG_ADDED;
}
function _isTxExistWithArgs(bytes32 _args, uint _block) internal view returns (bool) {
bytes32 _txHash = _getKey(_args, _block);
address _manager = getPendingManager();
return PendingManager(_manager).isTxExist(_txHash);
}
function _getKey(bytes32 _args, uint _block) private view returns (bytes32 _txHash) {
_block = _block != 0 ? _block : block.number;
_txHash = keccak256(msg.sig, _args, _block);
}
}
/// @title ServiceController
///
/// Base implementation
/// Serves for managing service instances
contract ServiceController is MultiSigAdapter {
event Error(uint _errorCode);
uint constant SERVICE_CONTROLLER = 350000;
uint constant SERVICE_CONTROLLER_EMISSION_EXIST = SERVICE_CONTROLLER + 1;
uint constant SERVICE_CONTROLLER_BURNING_MAN_EXIST = SERVICE_CONTROLLER + 2;
uint constant SERVICE_CONTROLLER_ALREADY_INITIALIZED = SERVICE_CONTROLLER + 3;
uint constant SERVICE_CONTROLLER_SERVICE_EXIST = SERVICE_CONTROLLER + 4;
address public profiterole;
address public treasury;
address public pendingManager;
address public proxy;
uint public sideServicesCount;
mapping(uint => address) public index2sideService;
mapping(address => uint) public sideService2index;
mapping(address => bool) public sideServices;
uint public emissionProvidersCount;
mapping(uint => address) public index2emissionProvider;
mapping(address => uint) public emissionProvider2index;
mapping(address => bool) public emissionProviders;
uint public burningMansCount;
mapping(uint => address) public index2burningMan;
mapping(address => uint) public burningMan2index;
mapping(address => bool) public burningMans;
/// @notice Default ServiceController's constructor
///
/// @param _pendingManager pending manager address
/// @param _proxy ERC20 proxy address
/// @param _profiterole profiterole address
/// @param _treasury treasury address
function ServiceController(address _pendingManager, address _proxy, address _profiterole, address _treasury) public {
require(_pendingManager != 0x0);
require(_proxy != 0x0);
require(_profiterole != 0x0);
require(_treasury != 0x0);
pendingManager = _pendingManager;
proxy = _proxy;
profiterole = _profiterole;
treasury = _treasury;
}
/// @notice Return pending manager address
///
/// @return code
function getPendingManager() public view returns (address) {
return pendingManager;
}
/// @notice Add emission provider
///
/// @param _provider emission provider address
///
/// @return code
function addEmissionProvider(address _provider, uint _block) public returns (uint _code) {
if (emissionProviders[_provider]) {
return _emitError(SERVICE_CONTROLLER_EMISSION_EXIST);
}
_code = _multisig(keccak256(_provider), _block);
if (OK != _code) {
return _code;
}
emissionProviders[_provider] = true;
uint _count = emissionProvidersCount + 1;
index2emissionProvider[_count] = _provider;
emissionProvider2index[_provider] = _count;
emissionProvidersCount = _count;
return OK;
}
/// @notice Remove emission provider
///
/// @param _provider emission provider address
///
/// @return code
function removeEmissionProvider(address _provider, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_provider), _block);
if (OK != _code) {
return _code;
}
uint _idx = emissionProvider2index[_provider];
uint _lastIdx = emissionProvidersCount;
if (_idx != 0) {
if (_idx != _lastIdx) {
address _lastEmissionProvider = index2emissionProvider[_lastIdx];
index2emissionProvider[_idx] = _lastEmissionProvider;
emissionProvider2index[_lastEmissionProvider] = _idx;
}
delete emissionProvider2index[_provider];
delete index2emissionProvider[_lastIdx];
delete emissionProviders[_provider];
emissionProvidersCount = _lastIdx - 1;
}
return OK;
}
/// @notice Add burning man
///
/// @param _burningMan burning man address
///
/// @return code
function addBurningMan(address _burningMan, uint _block) public returns (uint _code) {
if (burningMans[_burningMan]) {
return _emitError(SERVICE_CONTROLLER_BURNING_MAN_EXIST);
}
_code = _multisig(keccak256(_burningMan), _block);
if (OK != _code) {
return _code;
}
burningMans[_burningMan] = true;
uint _count = burningMansCount + 1;
index2burningMan[_count] = _burningMan;
burningMan2index[_burningMan] = _count;
burningMansCount = _count;
return OK;
}
/// @notice Remove burning man
///
/// @param _burningMan burning man address
///
/// @return code
function removeBurningMan(address _burningMan, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_burningMan), _block);
if (OK != _code) {
return _code;
}
uint _idx = burningMan2index[_burningMan];
uint _lastIdx = burningMansCount;
if (_idx != 0) {
if (_idx != _lastIdx) {
address _lastBurningMan = index2burningMan[_lastIdx];
index2burningMan[_idx] = _lastBurningMan;
burningMan2index[_lastBurningMan] = _idx;
}
delete burningMan2index[_burningMan];
delete index2burningMan[_lastIdx];
delete burningMans[_burningMan];
burningMansCount = _lastIdx - 1;
}
return OK;
}
/// @notice Update a profiterole address
///
/// @param _profiterole profiterole address
///
/// @return result code of an operation
function updateProfiterole(address _profiterole, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_profiterole), _block);
if (OK != _code) {
return _code;
}
profiterole = _profiterole;
return OK;
}
/// @notice Update a treasury address
///
/// @param _treasury treasury address
///
/// @return result code of an operation
function updateTreasury(address _treasury, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_treasury), _block);
if (OK != _code) {
return _code;
}
treasury = _treasury;
return OK;
}
/// @notice Update pending manager address
///
/// @param _pendingManager pending manager address
///
/// @return result code of an operation
function updatePendingManager(address _pendingManager, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_pendingManager), _block);
if (OK != _code) {
return _code;
}
pendingManager = _pendingManager;
return OK;
}
function addSideService(address _service, uint _block) public returns (uint _code) {
if (sideServices[_service]) {
return SERVICE_CONTROLLER_SERVICE_EXIST;
}
_code = _multisig(keccak256(_service), _block);
if (OK != _code) {
return _code;
}
sideServices[_service] = true;
uint _count = sideServicesCount + 1;
index2sideService[_count] = _service;
sideService2index[_service] = _count;
sideServicesCount = _count;
return OK;
}
function removeSideService(address _service, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_service), _block);
if (OK != _code) {
return _code;
}
uint _idx = sideService2index[_service];
uint _lastIdx = sideServicesCount;
if (_idx != 0) {
if (_idx != _lastIdx) {
address _lastSideService = index2sideService[_lastIdx];
index2sideService[_idx] = _lastSideService;
sideService2index[_lastSideService] = _idx;
}
delete sideService2index[_service];
delete index2sideService[_lastIdx];
delete sideServices[_service];
sideServicesCount = _lastIdx - 1;
}
return OK;
}
function getEmissionProviders()
public
view
returns (address[] _emissionProviders)
{
_emissionProviders = new address[](emissionProvidersCount);
for (uint _idx = 0; _idx < _emissionProviders.length; ++_idx) {
_emissionProviders[_idx] = index2emissionProvider[_idx + 1];
}
}
function getBurningMans()
public
view
returns (address[] _burningMans)
{
_burningMans = new address[](burningMansCount);
for (uint _idx = 0; _idx < _burningMans.length; ++_idx) {
_burningMans[_idx] = index2burningMan[_idx + 1];
}
}
function getSideServices()
public
view
returns (address[] _sideServices)
{
_sideServices = new address[](sideServicesCount);
for (uint _idx = 0; _idx < _sideServices.length; ++_idx) {
_sideServices[_idx] = index2sideService[_idx + 1];
}
}
/// @notice Check target address is service
///
/// @param _address target address
///
/// @return `true` when an address is a service, `false` otherwise
function isService(address _address) public view returns (bool check) {
return _address == profiterole ||
_address == treasury ||
_address == proxy ||
_address == pendingManager ||
emissionProviders[_address] ||
burningMans[_address] ||
sideServices[_address];
}
function _emitError(uint _errorCode) internal returns (uint) {
Error(_errorCode);
return _errorCode;
}
}
contract OracleMethodAdapter is Object {
event OracleAdded(bytes4 _sig, address _oracle);
event OracleRemoved(bytes4 _sig, address _oracle);
mapping(bytes4 => mapping(address => bool)) public oracles;
/// @dev Allow access only for oracle
modifier onlyOracle {
if (oracles[msg.sig][msg.sender]) {
_;
}
}
modifier onlyOracleOrOwner {
if (oracles[msg.sig][msg.sender] || msg.sender == contractOwner) {
_;
}
}
function addOracles(
bytes4[] _signatures,
address[] _oracles
)
onlyContractOwner
external
returns (uint)
{
require(_signatures.length == _oracles.length);
bytes4 _sig;
address _oracle;
for (uint _idx = 0; _idx < _signatures.length; ++_idx) {
(_sig, _oracle) = (_signatures[_idx], _oracles[_idx]);
if (_oracle != 0x0
&& _sig != bytes4(0)
&& !oracles[_sig][_oracle]
) {
oracles[_sig][_oracle] = true;
_emitOracleAdded(_sig, _oracle);
}
}
return OK;
}
function removeOracles(
bytes4[] _signatures,
address[] _oracles
)
onlyContractOwner
external
returns (uint)
{
require(_signatures.length == _oracles.length);
bytes4 _sig;
address _oracle;
for (uint _idx = 0; _idx < _signatures.length; ++_idx) {
(_sig, _oracle) = (_signatures[_idx], _oracles[_idx]);
if (_oracle != 0x0
&& _sig != bytes4(0)
&& oracles[_sig][_oracle]
) {
delete oracles[_sig][_oracle];
_emitOracleRemoved(_sig, _oracle);
}
}
return OK;
}
function _emitOracleAdded(bytes4 _sig, address _oracle) internal {
OracleAdded(_sig, _oracle);
}
function _emitOracleRemoved(bytes4 _sig, address _oracle) internal {
OracleRemoved(_sig, _oracle);
}
}
contract Platform {
mapping(bytes32 => address) public proxies;
function name(bytes32 _symbol) public view returns (string);
function setProxy(address _address, bytes32 _symbol) public returns (uint errorCode);
function isOwner(address _owner, bytes32 _symbol) public view returns (bool);
function totalSupply(bytes32 _symbol) public view returns (uint);
function balanceOf(address _holder, bytes32 _symbol) public view returns (uint);
function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint);
function baseUnit(bytes32 _symbol) public view returns (uint8);
function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode);
function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode);
function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public returns (uint errorCode);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) public returns (uint errorCode);
function reissueAsset(bytes32 _symbol, uint _value) public returns (uint errorCode);
function revokeAsset(bytes32 _symbol, uint _value) public returns (uint errorCode);
function isReissuable(bytes32 _symbol) public view returns (bool);
function changeOwnership(bytes32 _symbol, address _newOwner) public returns (uint errorCode);
}
contract ATxAssetProxy is ERC20, Object, ServiceAllowance {
using SafeMath for uint;
/**
* Indicates an upgrade freeze-time start, and the next asset implementation contract.
*/
event UpgradeProposal(address newVersion);
// Current asset implementation contract address.
address latestVersion;
// Assigned platform, immutable.
Platform public platform;
// Assigned symbol, immutable.
bytes32 public smbl;
// Assigned name, immutable.
string public name;
/**
* Only platform is allowed to call.
*/
modifier onlyPlatform() {
if (msg.sender == address(platform)) {
_;
}
}
/**
* Only current asset owner is allowed to call.
*/
modifier onlyAssetOwner() {
if (platform.isOwner(msg.sender, smbl)) {
_;
}
}
/**
* Only asset implementation contract assigned to sender is allowed to call.
*/
modifier onlyAccess(address _sender) {
if (getLatestVersion() == msg.sender) {
_;
}
}
/**
* Resolves asset implementation contract for the caller and forwards there transaction data,
* along with the value. This allows for proxy interface growth.
*/
function() public payable {
_getAsset().__process.value(msg.value)(msg.data, msg.sender);
}
/**
* Sets platform address, assigns symbol and name.
*
* Can be set only once.
*
* @param _platform platform contract address.
* @param _symbol assigned symbol.
* @param _name assigned name.
*
* @return success.
*/
function init(Platform _platform, string _symbol, string _name) public returns (bool) {
if (address(platform) != 0x0) {
return false;
}
platform = _platform;
symbol = _symbol;
smbl = stringToBytes32(_symbol);
name = _name;
return true;
}
/**
* Returns asset total supply.
*
* @return asset total supply.
*/
function totalSupply() public view returns (uint) {
return platform.totalSupply(smbl);
}
/**
* Returns asset balance for a particular holder.
*
* @param _owner holder address.
*
* @return holder balance.
*/
function balanceOf(address _owner) public view returns (uint) {
return platform.balanceOf(_owner, smbl);
}
/**
* Returns asset allowance from one holder to another.
*
* @param _from holder that allowed spending.
* @param _spender holder that is allowed to spend.
*
* @return holder to spender allowance.
*/
function allowance(address _from, address _spender) public view returns (uint) {
return platform.allowance(_from, _spender, smbl);
}
/**
* Returns asset decimals.
*
* @return asset decimals.
*/
function decimals() public view returns (uint8) {
return platform.baseUnit(smbl);
}
/**
* Transfers asset balance from the caller to specified receiver.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
*
* @return success.
*/
function transfer(address _to, uint _value) public returns (bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, "");
}
else {
return false;
}
}
/**
* Transfers asset balance from the caller to specified receiver adding specified comment.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
*
* @return success.
*/
function transferWithReference(address _to, uint _value, string _reference) public returns (bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, _reference);
}
else {
return false;
}
}
/**
* Performs transfer call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
* @param _sender initial caller.
*
* @return success.
*/
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK;
}
/**
* Prforms allowance transfer of asset balance between holders.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
*
* @return success.
*/
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
if (_to != 0x0) {
return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender);
}
else {
return false;
}
}
/**
* Performs allowance transfer call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _from holder address to take from.
* @param _to holder address to give to.
* @param _value amount to transfer.
* @param _reference transfer comment to be included in a platform's Transfer event.
* @param _sender initial caller.
*
* @return success.
*/
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK;
}
/**
* Sets asset spending allowance for a specified spender.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
*
* @return success.
*/
function approve(address _spender, uint _value) public returns (bool) {
if (_spender != 0x0) {
return _getAsset().__approve(_spender, _value, msg.sender);
}
else {
return false;
}
}
/**
* Performs allowance setting call on the platform by the name of specified sender.
*
* Can only be called by asset implementation contract assigned to sender.
*
* @param _spender holder address to set allowance to.
* @param _value amount to allow.
* @param _sender initial caller.
*
* @return success.
*/
function __approve(address _spender, uint _value, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyApprove(_spender, _value, smbl, _sender) == OK;
}
/**
* Emits ERC20 Transfer event on this contract.
*
* Can only be, and, called by assigned platform when asset transfer happens.
*/
function emitTransfer(address _from, address _to, uint _value) public onlyPlatform() {
Transfer(_from, _to, _value);
}
/**
* Emits ERC20 Approval event on this contract.
*
* Can only be, and, called by assigned platform when asset allowance set happens.
*/
function emitApprove(address _from, address _spender, uint _value) public onlyPlatform() {
Approval(_from, _spender, _value);
}
/**
* Returns current asset implementation contract address.
*
* @return asset implementation contract address.
*/
function getLatestVersion() public view returns (address) {
return latestVersion;
}
/**
* Propose next asset implementation contract address.
*
* Can only be called by current asset owner.
*
* Note: freeze-time should not be applied for the initial setup.
*
* @param _newVersion asset implementation contract address.
*
* @return success.
*/
function proposeUpgrade(address _newVersion) public onlyAssetOwner returns (bool) {
// New version address should be other than 0x0.
if (_newVersion == 0x0) {
return false;
}
latestVersion = _newVersion;
UpgradeProposal(_newVersion);
return true;
}
function isTransferAllowed(address, address, address, address, uint) public view returns (bool) {
return true;
}
/**
* Returns asset implementation contract for current caller.
*
* @return asset implementation contract.
*/
function _getAsset() internal view returns (ATxAssetInterface) {
return ATxAssetInterface(getLatestVersion());
}
/**
* Resolves asset implementation contract for the caller and forwards there arguments along with
* the caller address.
*
* @return success.
*/
function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) {
return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender);
}
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
}
contract DataControllerEmitter {
event CountryCodeAdded(uint _countryCode, uint _countryId, uint _maxHolderCount);
event CountryCodeChanged(uint _countryCode, uint _countryId, uint _maxHolderCount);
event HolderRegistered(bytes32 _externalHolderId, uint _accessIndex, uint _countryCode);
event HolderAddressAdded(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex);
event HolderAddressRemoved(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex);
event HolderOperationalChanged(bytes32 _externalHolderId, bool _operational);
event DayLimitChanged(bytes32 _externalHolderId, uint _from, uint _to);
event MonthLimitChanged(bytes32 _externalHolderId, uint _from, uint _to);
event Error(uint _errorCode);
function _emitHolderAddressAdded(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex) internal {
HolderAddressAdded(_externalHolderId, _holderPrototype, _accessIndex);
}
function _emitHolderAddressRemoved(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex) internal {
HolderAddressRemoved(_externalHolderId, _holderPrototype, _accessIndex);
}
function _emitHolderRegistered(bytes32 _externalHolderId, uint _accessIndex, uint _countryCode) internal {
HolderRegistered(_externalHolderId, _accessIndex, _countryCode);
}
function _emitHolderOperationalChanged(bytes32 _externalHolderId, bool _operational) internal {
HolderOperationalChanged(_externalHolderId, _operational);
}
function _emitCountryCodeAdded(uint _countryCode, uint _countryId, uint _maxHolderCount) internal {
CountryCodeAdded(_countryCode, _countryId, _maxHolderCount);
}
function _emitCountryCodeChanged(uint _countryCode, uint _countryId, uint _maxHolderCount) internal {
CountryCodeChanged(_countryCode, _countryId, _maxHolderCount);
}
function _emitDayLimitChanged(bytes32 _externalHolderId, uint _from, uint _to) internal {
DayLimitChanged(_externalHolderId, _from, _to);
}
function _emitMonthLimitChanged(bytes32 _externalHolderId, uint _from, uint _to) internal {
MonthLimitChanged(_externalHolderId, _from, _to);
}
function _emitError(uint _errorCode) internal returns (uint) {
Error(_errorCode);
return _errorCode;
}
}
/// @title Provides possibility manage holders? country limits and limits for holders.
contract DataController is OracleMethodAdapter, DataControllerEmitter {
/* CONSTANTS */
uint constant DATA_CONTROLLER = 109000;
uint constant DATA_CONTROLLER_ERROR = DATA_CONTROLLER + 1;
uint constant DATA_CONTROLLER_CURRENT_WRONG_LIMIT = DATA_CONTROLLER + 2;
uint constant DATA_CONTROLLER_WRONG_ALLOWANCE = DATA_CONTROLLER + 3;
uint constant DATA_CONTROLLER_COUNTRY_CODE_ALREADY_EXISTS = DATA_CONTROLLER + 4;
uint constant MAX_TOKEN_HOLDER_NUMBER = 2 ** 256 - 1;
using SafeMath for uint;
/* STRUCTS */
/// @title HoldersData couldn't be public because of internal structures, so needed to provide getters for different parts of _holderData
struct HoldersData {
uint countryCode;
uint sendLimPerDay;
uint sendLimPerMonth;
bool operational;
bytes text;
uint holderAddressCount;
mapping(uint => address) index2Address;
mapping(address => uint) address2Index;
}
struct CountryLimits {
uint countryCode;
uint maxTokenHolderNumber;
uint currentTokenHolderNumber;
}
/* FIELDS */
address public withdrawal;
address assetAddress;
address public serviceController;
mapping(address => uint) public allowance;
// Iterable mapping pattern is used for holders.
/// @dev This is an access address mapping. Many addresses may have access to a single holder.
uint public holdersCount;
mapping(uint => HoldersData) holders;
mapping(address => bytes32) holderAddress2Id;
mapping(bytes32 => uint) public holderIndex;
// This is an access address mapping. Many addresses may have access to a single holder.
uint public countriesCount;
mapping(uint => CountryLimits) countryLimitsList;
mapping(uint => uint) countryIndex;
/* MODIFIERS */
modifier onlyWithdrawal {
if (msg.sender != withdrawal) {
revert();
}
_;
}
modifier onlyAsset {
if (msg.sender == _getATxToken().getLatestVersion()) {
_;
}
}
modifier onlyContractOwner {
if (msg.sender == contractOwner) {
_;
}
}
/// @notice Constructor for _holderData controller.
/// @param _serviceController service controller
function DataController(address _serviceController) public {
require(_serviceController != 0x0);
serviceController = _serviceController;
}
function() payable public {
revert();
}
function setWithdraw(address _withdrawal) onlyContractOwner external returns (uint) {
require(_withdrawal != 0x0);
withdrawal = _withdrawal;
return OK;
}
function setServiceController(address _serviceController)
onlyContractOwner
external
returns (uint)
{
require(_serviceController != 0x0);
serviceController = _serviceController;
return OK;
}
function getPendingManager() public view returns (address) {
return ServiceController(serviceController).getPendingManager();
}
function getHolderInfo(bytes32 _externalHolderId) public view returns (
uint _countryCode,
uint _limPerDay,
uint _limPerMonth,
bool _operational,
bytes _text
) {
HoldersData storage _data = holders[holderIndex[_externalHolderId]];
return (_data.countryCode, _data.sendLimPerDay, _data.sendLimPerMonth, _data.operational, _data.text);
}
function getHolderAddresses(bytes32 _externalHolderId) public view returns (address[] _addresses) {
HoldersData storage _holderData = holders[holderIndex[_externalHolderId]];
uint _addressesCount = _holderData.holderAddressCount;
_addresses = new address[](_addressesCount);
for (uint _holderAddressIdx = 0; _holderAddressIdx < _addressesCount; ++_holderAddressIdx) {
_addresses[_holderAddressIdx] = _holderData.index2Address[_holderAddressIdx + 1];
}
}
function getHolderCountryCode(bytes32 _externalHolderId) public view returns (uint) {
return holders[holderIndex[_externalHolderId]].countryCode;
}
function getHolderExternalIdByAddress(address _address) public view returns (bytes32) {
return holderAddress2Id[_address];
}
/// @notice Checks user is holder.
/// @param _address checking address.
/// @return `true` if _address is registered holder, `false` otherwise.
function isRegisteredAddress(address _address) public view returns (bool) {
return holderIndex[holderAddress2Id[_address]] != 0;
}
function isHolderOwnAddress(
bytes32 _externalHolderId,
address _address
)
public
view
returns (bool)
{
uint _holderIndex = holderIndex[_externalHolderId];
if (_holderIndex == 0) {
return false;
}
return holders[_holderIndex].address2Index[_address] != 0;
}
function getCountryInfo(uint _countryCode)
public
view
returns (
uint _maxHolderNumber,
uint _currentHolderCount
) {
CountryLimits storage _data = countryLimitsList[countryIndex[_countryCode]];
return (_data.maxTokenHolderNumber, _data.currentTokenHolderNumber);
}
function getCountryLimit(uint _countryCode) public view returns (uint limit) {
uint _index = countryIndex[_countryCode];
require(_index != 0);
return countryLimitsList[_index].maxTokenHolderNumber;
}
function addCountryCode(uint _countryCode) onlyContractOwner public returns (uint) {
var (,_created) = _createCountryId(_countryCode);
if (!_created) {
return _emitError(DATA_CONTROLLER_COUNTRY_CODE_ALREADY_EXISTS);
}
return OK;
}
/// @notice Returns holder id for the specified address, creates it if needed.
/// @param _externalHolderId holder address.
/// @param _countryCode country code.
/// @return error code.
function registerHolder(
bytes32 _externalHolderId,
address _holderAddress,
uint _countryCode
)
onlyOracleOrOwner
external
returns (uint)
{
require(_holderAddress != 0x0);
require(holderIndex[_externalHolderId] == 0);
uint _holderIndex = holderIndex[holderAddress2Id[_holderAddress]];
require(_holderIndex == 0);
_createCountryId(_countryCode);
_holderIndex = holdersCount.add(1);
holdersCount = _holderIndex;
HoldersData storage _holderData = holders[_holderIndex];
_holderData.countryCode = _countryCode;
_holderData.operational = true;
_holderData.sendLimPerDay = MAX_TOKEN_HOLDER_NUMBER;
_holderData.sendLimPerMonth = MAX_TOKEN_HOLDER_NUMBER;
uint _firstAddressIndex = 1;
_holderData.holderAddressCount = _firstAddressIndex;
_holderData.address2Index[_holderAddress] = _firstAddressIndex;
_holderData.index2Address[_firstAddressIndex] = _holderAddress;
holderIndex[_externalHolderId] = _holderIndex;
holderAddress2Id[_holderAddress] = _externalHolderId;
_emitHolderRegistered(_externalHolderId, _holderIndex, _countryCode);
return OK;
}
/// @notice Adds new address equivalent to holder.
/// @param _externalHolderId external holder identifier.
/// @param _newAddress adding address.
/// @return error code.
function addHolderAddress(
bytes32 _externalHolderId,
address _newAddress
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
uint _newAddressId = holderIndex[holderAddress2Id[_newAddress]];
require(_newAddressId == 0);
HoldersData storage _holderData = holders[_holderIndex];
if (_holderData.address2Index[_newAddress] == 0) {
_holderData.holderAddressCount = _holderData.holderAddressCount.add(1);
_holderData.address2Index[_newAddress] = _holderData.holderAddressCount;
_holderData.index2Address[_holderData.holderAddressCount] = _newAddress;
}
holderAddress2Id[_newAddress] = _externalHolderId;
_emitHolderAddressAdded(_externalHolderId, _newAddress, _holderIndex);
return OK;
}
/// @notice Remove an address owned by a holder.
/// @param _externalHolderId external holder identifier.
/// @param _address removing address.
/// @return error code.
function removeHolderAddress(
bytes32 _externalHolderId,
address _address
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
HoldersData storage _holderData = holders[_holderIndex];
uint _tempIndex = _holderData.address2Index[_address];
require(_tempIndex != 0);
address _lastAddress = _holderData.index2Address[_holderData.holderAddressCount];
_holderData.address2Index[_lastAddress] = _tempIndex;
_holderData.index2Address[_tempIndex] = _lastAddress;
delete _holderData.address2Index[_address];
_holderData.holderAddressCount = _holderData.holderAddressCount.sub(1);
delete holderAddress2Id[_address];
_emitHolderAddressRemoved(_externalHolderId, _address, _holderIndex);
return OK;
}
/// @notice Change operational status for holder.
/// Can be accessed by contract owner or oracle only.
///
/// @param _externalHolderId external holder identifier.
/// @param _operational operational status.
///
/// @return result code.
function changeOperational(
bytes32 _externalHolderId,
bool _operational
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
holders[_holderIndex].operational = _operational;
_emitHolderOperationalChanged(_externalHolderId, _operational);
return OK;
}
/// @notice Changes text for holder.
/// Can be accessed by contract owner or oracle only.
///
/// @param _externalHolderId external holder identifier.
/// @param _text changing text.
///
/// @return result code.
function updateTextForHolder(
bytes32 _externalHolderId,
bytes _text
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
holders[_holderIndex].text = _text;
return OK;
}
/// @notice Updates limit per day for holder.
///
/// Can be accessed by contract owner only.
///
/// @param _externalHolderId external holder identifier.
/// @param _limit limit value.
///
/// @return result code.
function updateLimitPerDay(
bytes32 _externalHolderId,
uint _limit
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
uint _currentLimit = holders[_holderIndex].sendLimPerDay;
holders[_holderIndex].sendLimPerDay = _limit;
_emitDayLimitChanged(_externalHolderId, _currentLimit, _limit);
return OK;
}
/// @notice Updates limit per month for holder.
/// Can be accessed by contract owner or oracle only.
///
/// @param _externalHolderId external holder identifier.
/// @param _limit limit value.
///
/// @return result code.
function updateLimitPerMonth(
bytes32 _externalHolderId,
uint _limit
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
uint _currentLimit = holders[_holderIndex].sendLimPerDay;
holders[_holderIndex].sendLimPerMonth = _limit;
_emitMonthLimitChanged(_externalHolderId, _currentLimit, _limit);
return OK;
}
/// @notice Change country limits.
/// Can be accessed by contract owner or oracle only.
///
/// @param _countryCode country code.
/// @param _limit limit value.
///
/// @return result code.
function changeCountryLimit(
uint _countryCode,
uint _limit
)
onlyOracleOrOwner
external
returns (uint)
{
uint _countryIndex = countryIndex[_countryCode];
require(_countryIndex != 0);
uint _currentTokenHolderNumber = countryLimitsList[_countryIndex].currentTokenHolderNumber;
if (_currentTokenHolderNumber > _limit) {
return _emitError(DATA_CONTROLLER_CURRENT_WRONG_LIMIT);
}
countryLimitsList[_countryIndex].maxTokenHolderNumber = _limit;
_emitCountryCodeChanged(_countryIndex, _countryCode, _limit);
return OK;
}
function withdrawFrom(
address _holderAddress,
uint _value
)
onlyAsset
public
returns (uint)
{
bytes32 _externalHolderId = holderAddress2Id[_holderAddress];
HoldersData storage _holderData = holders[holderIndex[_externalHolderId]];
_holderData.sendLimPerDay = _holderData.sendLimPerDay.sub(_value);
_holderData.sendLimPerMonth = _holderData.sendLimPerMonth.sub(_value);
return OK;
}
function depositTo(
address _holderAddress,
uint _value
)
onlyAsset
public
returns (uint)
{
bytes32 _externalHolderId = holderAddress2Id[_holderAddress];
HoldersData storage _holderData = holders[holderIndex[_externalHolderId]];
_holderData.sendLimPerDay = _holderData.sendLimPerDay.add(_value);
_holderData.sendLimPerMonth = _holderData.sendLimPerMonth.add(_value);
return OK;
}
function updateCountryHoldersCount(
uint _countryCode,
uint _updatedHolderCount
)
public
onlyAsset
returns (uint)
{
CountryLimits storage _data = countryLimitsList[countryIndex[_countryCode]];
assert(_data.maxTokenHolderNumber >= _updatedHolderCount);
_data.currentTokenHolderNumber = _updatedHolderCount;
return OK;
}
function changeAllowance(address _from, uint _value) public onlyWithdrawal returns (uint) {
ATxAssetProxy token = _getATxToken();
if (token.balanceOf(_from) < _value) {
return _emitError(DATA_CONTROLLER_WRONG_ALLOWANCE);
}
allowance[_from] = _value;
return OK;
}
function _createCountryId(uint _countryCode) internal returns (uint, bool _created) {
uint countryId = countryIndex[_countryCode];
if (countryId == 0) {
uint _countriesCount = countriesCount;
countryId = _countriesCount.add(1);
countriesCount = countryId;
CountryLimits storage limits = countryLimitsList[countryId];
limits.countryCode = _countryCode;
limits.maxTokenHolderNumber = MAX_TOKEN_HOLDER_NUMBER;
countryIndex[_countryCode] = countryId;
_emitCountryCodeAdded(countryIndex[_countryCode], _countryCode, MAX_TOKEN_HOLDER_NUMBER);
_created = true;
}
return (countryId, _created);
}
function _getATxToken() private view returns (ATxAssetProxy) {
ServiceController _serviceController = ServiceController(serviceController);
return ATxAssetProxy(_serviceController.proxy());
}
}
/// @title Contract that will work with ERC223 tokens.
interface ERC223ReceivingInterface {
/// @notice Standard ERC223 function that will handle incoming token transfers.
/// @param _from Token sender address.
/// @param _value Amount of tokens.
/// @param _data Transaction metadata.
function tokenFallback(address _from, uint _value, bytes _data) external;
}
contract ATxProxy is ERC20 {
bytes32 public smbl;
address public platform;
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool);
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool);
function __approve(address _spender, uint _value, address _sender) public returns (bool);
function getLatestVersion() public returns (address);
function init(address _bmcPlatform, string _symbol, string _name) public;
function proposeUpgrade(address _newVersion) public;
}
/// @title ATx Asset implementation contract.
///
/// Basic asset implementation contract, without any additional logic.
/// Every other asset implementation contracts should derive from this one.
/// Receives calls from the proxy, and calls back immediately without arguments modification.
///
/// Note: all the non constant functions return false instead of throwing in case if state change
/// didn't happen yet.
contract ATxAsset is BasicAsset, Owned {
uint public constant OK = 1;
using SafeMath for uint;
enum Roles {
Holder,
Service,
Other
}
ServiceController public serviceController;
DataController public dataController;
uint public lockupDate;
/// @notice Default constructor for ATxAsset.
function ATxAsset() public {
}
function() payable public {
revert();
}
/// @notice Init function for ATxAsset.
///
/// @param _proxy - atx asset proxy.
/// @param _serviceController - service controoler.
/// @param _dataController - data controller.
/// @param _lockupDate - th lockup date.
function initAtx(
address _proxy,
address _serviceController,
address _dataController,
uint _lockupDate
)
onlyContractOwner
public
returns (bool)
{
require(_serviceController != 0x0);
require(_dataController != 0x0);
require(_proxy != 0x0);
require(_lockupDate > now || _lockupDate == 0);
if (!super.init(ATxProxy(_proxy))) {
return false;
}
serviceController = ServiceController(_serviceController);
dataController = DataController(_dataController);
lockupDate = _lockupDate;
return true;
}
/// @notice Performs transfer call on the platform by the name of specified sender.
///
/// @dev Can only be called by proxy asset.
///
/// @param _to holder address to give to.
/// @param _value amount to transfer.
/// @param _reference transfer comment to be included in a platform's Transfer event.
/// @param _sender initial caller.
///
/// @return success.
function __transferWithReference(
address _to,
uint _value,
string _reference,
address _sender
)
onlyProxy
public
returns (bool)
{
var (_fromRole, _toRole) = _getParticipantRoles(_sender, _to);
if (!_checkTransferAllowance(_to, _toRole, _value, _sender, _fromRole)) {
return false;
}
if (!_isValidCountryLimits(_to, _toRole, _value, _sender, _fromRole)) {
return false;
}
if (!super.__transferWithReference(_to, _value, _reference, _sender)) {
return false;
}
_updateTransferLimits(_to, _toRole, _value, _sender, _fromRole);
_contractFallbackERC223(_sender, _to, _value);
return true;
}
/// @notice Performs allowance transfer call on the platform by the name of specified sender.
///
/// @dev Can only be called by proxy asset.
///
/// @param _from holder address to take from.
/// @param _to holder address to give to.
/// @param _value amount to transfer.
/// @param _reference transfer comment to be included in a platform's Transfer event.
/// @param _sender initial caller.
///
/// @return success.
function __transferFromWithReference(
address _from,
address _to,
uint _value,
string _reference,
address _sender
)
public
onlyProxy
returns (bool)
{
var (_fromRole, _toRole) = _getParticipantRoles(_from, _to);
// @note Special check for operational withdraw.
bool _isTransferFromHolderToContractOwner = (_fromRole == Roles.Holder) &&
(contractOwner == _to) &&
(dataController.allowance(_from) >= _value) &&
super.__transferFromWithReference(_from, _to, _value, _reference, _sender);
if (_isTransferFromHolderToContractOwner) {
return true;
}
if (!_checkTransferAllowanceFrom(_to, _toRole, _value, _from, _fromRole, _sender)) {
return false;
}
if (!_isValidCountryLimits(_to, _toRole, _value, _from, _fromRole)) {
return false;
}
if (!super.__transferFromWithReference(_from, _to, _value, _reference, _sender)) {
return false;
}
_updateTransferLimits(_to, _toRole, _value, _from, _fromRole);
_contractFallbackERC223(_from, _to, _value);
return true;
}
/* INTERNAL */
function _contractFallbackERC223(address _from, address _to, uint _value) internal {
uint _codeLength;
assembly {
_codeLength := extcodesize(_to)
}
if (_codeLength > 0) {
ERC223ReceivingInterface _receiver = ERC223ReceivingInterface(_to);
bytes memory _empty;
_receiver.tokenFallback(_from, _value, _empty);
}
}
function _isTokenActive() internal view returns (bool) {
return now > lockupDate;
}
function _checkTransferAllowance(address _to, Roles _toRole, uint _value, address _from, Roles _fromRole) internal view returns (bool) {
if (_to == proxy) {
return false;
}
bool _canTransferFromService = _fromRole == Roles.Service && ServiceAllowance(_from).isTransferAllowed(_from, _to, _from, proxy, _value);
bool _canTransferToService = _toRole == Roles.Service && ServiceAllowance(_to).isTransferAllowed(_from, _to, _from, proxy, _value);
bool _canTransferToHolder = _toRole == Roles.Holder && _couldDepositToHolder(_to, _value);
bool _canTransferFromHolder;
if (_isTokenActive()) {
_canTransferFromHolder = _fromRole == Roles.Holder && _couldWithdrawFromHolder(_from, _value);
} else {
_canTransferFromHolder = _fromRole == Roles.Holder && _couldWithdrawFromHolder(_from, _value) && _from == contractOwner;
}
return (_canTransferFromHolder || _canTransferFromService) && (_canTransferToHolder || _canTransferToService);
}
function _checkTransferAllowanceFrom(
address _to,
Roles _toRole,
uint _value,
address _from,
Roles _fromRole,
address
)
internal
view
returns (bool)
{
return _checkTransferAllowance(_to, _toRole, _value, _from, _fromRole);
}
function _isValidWithdrawLimits(uint _sendLimPerDay, uint _sendLimPerMonth, uint _value) internal pure returns (bool) {
return !(_value > _sendLimPerDay || _value > _sendLimPerMonth);
}
function _isValidDepositCountry(
uint _value,
uint _withdrawCountryCode,
uint _withdrawBalance,
uint _countryCode,
uint _balance,
uint _currentHolderCount,
uint _maxHolderNumber
)
internal
pure
returns (bool)
{
return _isNoNeedInCountryLimitChange(_value, _withdrawCountryCode, _withdrawBalance, _countryCode, _balance, _currentHolderCount, _maxHolderNumber)
? true
: _isValidDepositCountry(_balance, _currentHolderCount, _maxHolderNumber);
}
function _isNoNeedInCountryLimitChange(
uint _value,
uint _withdrawCountryCode,
uint _withdrawBalance,
uint _countryCode,
uint _balance,
uint _currentHolderCount,
uint _maxHolderNumber
)
internal
pure
returns (bool)
{
bool _needToIncrementCountryHolderCount = _balance == 0;
bool _needToDecrementCountryHolderCount = _withdrawBalance == _value;
bool _shouldOverflowCountryHolderCount = _currentHolderCount == _maxHolderNumber;
return _withdrawCountryCode == _countryCode && _needToDecrementCountryHolderCount && _needToIncrementCountryHolderCount && _shouldOverflowCountryHolderCount;
}
function _updateCountries(
uint _value,
uint _withdrawCountryCode,
uint _withdrawBalance,
uint _withdrawCurrentHolderCount,
uint _countryCode,
uint _balance,
uint _currentHolderCount,
uint _maxHolderNumber
)
internal
{
if (_isNoNeedInCountryLimitChange(_value, _withdrawCountryCode, _withdrawBalance, _countryCode, _balance, _currentHolderCount, _maxHolderNumber)) {
return;
}
_updateWithdrawCountry(_value, _withdrawCountryCode, _withdrawBalance, _withdrawCurrentHolderCount);
_updateDepositCountry(_countryCode, _balance, _currentHolderCount);
}
function _updateWithdrawCountry(
uint _value,
uint _countryCode,
uint _balance,
uint _currentHolderCount
)
internal
{
if (_value == _balance && OK != dataController.updateCountryHoldersCount(_countryCode, _currentHolderCount.sub(1))) {
revert();
}
}
function _updateDepositCountry(
uint _countryCode,
uint _balance,
uint _currentHolderCount
)
internal
{
if (_balance == 0 && OK != dataController.updateCountryHoldersCount(_countryCode, _currentHolderCount.add(1))) {
revert();
}
}
function _getParticipantRoles(address _from, address _to) private view returns (Roles _fromRole, Roles _toRole) {
_fromRole = dataController.isRegisteredAddress(_from) ? Roles.Holder : (serviceController.isService(_from) ? Roles.Service : Roles.Other);
_toRole = dataController.isRegisteredAddress(_to) ? Roles.Holder : (serviceController.isService(_to) ? Roles.Service : Roles.Other);
}
function _couldWithdrawFromHolder(address _holder, uint _value) private view returns (bool) {
bytes32 _holderId = dataController.getHolderExternalIdByAddress(_holder);
var (, _limPerDay, _limPerMonth, _operational,) = dataController.getHolderInfo(_holderId);
return _operational ? _isValidWithdrawLimits(_limPerDay, _limPerMonth, _value) : false;
}
function _couldDepositToHolder(address _holder, uint) private view returns (bool) {
bytes32 _holderId = dataController.getHolderExternalIdByAddress(_holder);
var (,,, _operational,) = dataController.getHolderInfo(_holderId);
return _operational;
}
//TODO need additional check: not clear check of country limit:
function _isValidDepositCountry(uint _balance, uint _currentHolderCount, uint _maxHolderNumber) private pure returns (bool) {
return !(_balance == 0 && _currentHolderCount == _maxHolderNumber);
}
function _getHoldersInfo(address _to, Roles _toRole, uint, address _from, Roles _fromRole)
private
view
returns (
uint _fromCountryCode,
uint _fromBalance,
uint _toCountryCode,
uint _toCountryCurrentHolderCount,
uint _toCountryMaxHolderNumber,
uint _toBalance
) {
bytes32 _holderId;
if (_toRole == Roles.Holder) {
_holderId = dataController.getHolderExternalIdByAddress(_to);
_toCountryCode = dataController.getHolderCountryCode(_holderId);
(_toCountryCurrentHolderCount, _toCountryMaxHolderNumber) = dataController.getCountryInfo(_toCountryCode);
_toBalance = ERC20Interface(proxy).balanceOf(_to);
}
if (_fromRole == Roles.Holder) {
_holderId = dataController.getHolderExternalIdByAddress(_from);
_fromCountryCode = dataController.getHolderCountryCode(_holderId);
_fromBalance = ERC20Interface(proxy).balanceOf(_from);
}
}
function _isValidCountryLimits(address _to, Roles _toRole, uint _value, address _from, Roles _fromRole) private view returns (bool) {
var (
_fromCountryCode,
_fromBalance,
_toCountryCode,
_toCountryCurrentHolderCount,
_toCountryMaxHolderNumber,
_toBalance
) = _getHoldersInfo(_to, _toRole, _value, _from, _fromRole);
//TODO not clear for which case this check
bool _isValidLimitFromHolder = _fromRole == _toRole && _fromRole == Roles.Holder && !_isValidDepositCountry(_value, _fromCountryCode, _fromBalance, _toCountryCode, _toBalance, _toCountryCurrentHolderCount, _toCountryMaxHolderNumber);
bool _isValidLimitsToHolder = _toRole == Roles.Holder && !_isValidDepositCountry(_toBalance, _toCountryCurrentHolderCount, _toCountryMaxHolderNumber);
return !(_isValidLimitFromHolder || _isValidLimitsToHolder);
}
function _updateTransferLimits(address _to, Roles _toRole, uint _value, address _from, Roles _fromRole) private {
var (
_fromCountryCode,
_fromBalance,
_toCountryCode,
_toCountryCurrentHolderCount,
_toCountryMaxHolderNumber,
_toBalance
) = _getHoldersInfo(_to, _toRole, _value, _from, _fromRole);
if (_fromRole == Roles.Holder && OK != dataController.withdrawFrom(_from, _value)) {
revert();
}
if (_toRole == Roles.Holder && OK != dataController.depositTo(_from, _value)) {
revert();
}
uint _fromCountryCurrentHolderCount;
if (_fromRole == Roles.Holder && _fromRole == _toRole) {
(_fromCountryCurrentHolderCount,) = dataController.getCountryInfo(_fromCountryCode);
_updateCountries(
_value,
_fromCountryCode,
_fromBalance,
_fromCountryCurrentHolderCount,
_toCountryCode,
_toBalance,
_toCountryCurrentHolderCount,
_toCountryMaxHolderNumber
);
} else if (_fromRole == Roles.Holder) {
(_fromCountryCurrentHolderCount,) = dataController.getCountryInfo(_fromCountryCode);
_updateWithdrawCountry(_value, _fromCountryCode, _fromBalance, _fromCountryCurrentHolderCount);
} else if (_toRole == Roles.Holder) {
_updateDepositCountry(_toCountryCode, _toBalance, _toCountryCurrentHolderCount);
}
}
}
/// @title ATx Asset implementation contract.
///
/// Basic asset implementation contract, without any additional logic.
/// Every other asset implementation contracts should derive from this one.
/// Receives calls from the proxy, and calls back immediately without arguments modification.
///
/// Note: all the non constant functions return false instead of throwing in case if state change
/// didn't happen yet.
contract Asset is ATxAsset {
}
|
Passes execution into virtual function. Can only be called by assigned asset proxy. return success. function is final, and must not be overridden./
|
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public onlyProxy returns (bool) {
return _transferWithReference(_to, _value, _reference, _sender);
}
| 1,265,313 |
./full_match/8453/0x34bE60b50DdC8a8521dd8b2FF138Dfb635c17681/sources/contracts/quest/Quest.sol
|
Safely transfer ERC20 token. _tokenAddress Token contract address _recipient Recipient's address _amount Amount to transfer _gasLimit Gas limit for the transfer call return (success, reason) Some tokens do not revert when transfer fails, and some tokens do not return true. This function is able to handle such tokens correctly. - Note that this does not return false if the given token contract address is not in fact a contract address. It is possible to check whether an address is a contract address by checking the extcodesize, but it does not do so due to the high gas overhead (700+). - Also ensure that the gasLimit provided is reasonably large to accommodate typical transfers, but not too large that a broken contract will consume a large amount of gas unnecessarilly./
|
function safeTransferERC20(
address _tokenAddress,
address _recipient,
uint256 _amount,
uint256 _gasLimit
) internal returns (bool, bytes memory) {
bytes memory data = abi.encodeWithSelector(
bytes4(keccak256("transfer(address,uint256)")),
_recipient,
_amount
);
(bool success, bytes memory response) = _tokenAddress.call{
gas: _gasLimit
}(data);
if (success) {
if (response.length > 0 && !abi.decode(response, (bool))) {
return (false, "false returned");
}
return (true, "");
}
return (false, response);
}
| 11,535,638 |
pragma solidity 0.4.24;
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: openzeppelin-solidity/contracts/ownership/HasNoEther.sol
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <remco@2π.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this Ether.
* @notice Ether can still be sent to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
constructor() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by setting a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
owner.transfer(address(this).balance);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
// File: openzeppelin-solidity/contracts/ownership/CanReclaimToken.sol
/**
* @title Contracts that should be able to recover tokens
* @author SylTi
* @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner.
* This will prevent any accidental loss of tokens.
*/
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param _token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic _token) external onlyOwner {
uint256 balance = _token.balanceOf(this);
_token.safeTransfer(owner, balance);
}
}
// File: openzeppelin-solidity/contracts/ownership/HasNoTokens.sol
/**
* @title Contracts that should not own Tokens
* @author Remco Bloemen <remco@2π.com>
* @dev This blocks incoming ERC223 tokens to prevent accidental loss of tokens.
* Should tokens (any ERC20Basic compatible) end up in the contract, it allows the
* owner to reclaim the tokens.
*/
contract HasNoTokens is CanReclaimToken {
/**
* @dev Reject all ERC223 compatible tokens
* @param _from address The address that is transferring the tokens
* @param _value uint256 the amount of the specified token
* @param _data Bytes The data passed from the caller.
*/
function tokenFallback(
address _from,
uint256 _value,
bytes _data
)
external
pure
{
_from;
_value;
_data;
revert();
}
}
// File: openzeppelin-solidity/contracts/ownership/HasNoContracts.sol
/**
* @title Contracts that should not own Contracts
* @author Remco Bloemen <remco@2π.com>
* @dev Should contracts (anything Ownable) end up being owned by this contract, it allows the owner
* of this contract to reclaim ownership of the contracts.
*/
contract HasNoContracts is Ownable {
/**
* @dev Reclaim ownership of Ownable contracts
* @param _contractAddr The address of the Ownable to be reclaimed.
*/
function reclaimContract(address _contractAddr) external onlyOwner {
Ownable contractInst = Ownable(_contractAddr);
contractInst.transferOwnership(owner);
}
}
// File: openzeppelin-solidity/contracts/ownership/NoOwner.sol
/**
* @title Base contract for contracts that should not own things.
* @author Remco Bloemen <remco@2π.com>
* @dev Solves a class of errors where a contract accidentally becomes owner of Ether, Tokens or
* Owned contracts. See respective base contracts for details.
*/
contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts {
}
// File: openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol
/**
* @title DetailedERC20 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 DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardBurnableToken.sol
/**
* @title Standard Burnable Token
* @dev Adds burnFrom method to ERC20 implementations
*/
contract StandardBurnableToken is BurnableToken, StandardToken {
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param _from address The address which you want to send tokens from
* @param _value uint256 The amount of token to be burned
*/
function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
}
// File: contracts/lifecycle/Finalizable.sol
/**
* @title Finalizable contract
* @dev Lifecycle extension where an owner can do extra work after finishing.
*/
contract Finalizable is Ownable {
using SafeMath for uint256;
/// @dev Throws if called before the contract is finalized.
modifier onlyFinalized() {
require(isFinalized, "Contract not finalized.");
_;
}
/// @dev Throws if called after the contract is finalized.
modifier onlyNotFinalized() {
require(!isFinalized, "Contract already finalized.");
_;
}
bool public isFinalized = false;
event Finalized();
/**
* @dev Called by owner to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() public onlyOwner onlyNotFinalized {
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
// override
}
}
// File: contracts/token/ERC20/SafeStandardToken.sol
/**
* @title SafeStandardToken
* @dev An ERC20 token implementation which disallows transfers to this contract.
*/
contract SafeStandardToken is StandardToken {
/// @dev Throws if destination address is not valid.
modifier onlyValidDestination(address _to) {
require(_to != address(this), "Transfering tokens to this contract address is not allowed.");
_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value)
public
onlyValidDestination(_to)
returns (bool)
{
return super.transfer(_to, _value);
}
/**
* @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
onlyValidDestination(_to)
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
}
// File: contracts/TolarToken.sol
/**
* @title TolarToken
* @dev ERC20 Tolar Token (TOL)
*
* TOL Tokens are divisible by 1e18 (1 000 000 000 000 000 000) base.
*
* TOL are displayed using 18 decimal places of precision.
*
* 1 TOL is equivalent to:
* 1 000 000 000 000 000 000 == 1 * 10**18 == 1e18
*
* 1 Billion TOL (total supply) is equivalent to:
* 1000000000 * 10**18 == 1e27
*
* @notice All tokens are pre-assigned to the creator. Note they can later distribute these
* tokens as they wish using `transfer` and other `StandardToken` functions.
* This is a BurnableToken where users can burn tokens when the burning functionality is
* enabled (contract is finalized) by the owner.
*/
contract TolarToken is NoOwner, Finalizable, DetailedERC20, SafeStandardToken, StandardBurnableToken {
string public constant NAME = "Tolar Token";
string public constant SYMBOL = "TOL";
uint8 public constant DECIMALS = 18;
uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(DECIMALS));
/// @dev Throws if called before the contract is finalized.
modifier onlyFinalizedOrOwner() {
require(isFinalized || msg.sender == owner, "Contract not finalized or sender not owner.");
_;
}
/// @dev Constructor that gives msg.sender all of existing tokens.
constructor() public DetailedERC20(NAME, SYMBOL, DECIMALS) {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(address(0), msg.sender, INITIAL_SUPPLY);
}
/**
* @dev Overrides StandardToken._burn in order for burn and burnFrom to be disabled
* when the contract is paused.
*/
function _burn(address _who, uint256 _value) internal onlyFinalizedOrOwner {
super._burn(_who, _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(address _from, address _to, uint256 _value)
public
onlyValidDestination(_to)
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
| 12,600,904 |
pragma solidity ^0.6.6;
pragma experimental ABIEncoderV2;
import "./Address.sol";
import "./IACOPool2.sol";
/**
* @title ACOPoolFactory
* @dev The contract is the implementation for the ACOProxy.
*/
contract ACOPoolFactory2 {
/**
* @dev Struct to store the ACO pool basic data.
*/
struct ACOPoolBasicData {
/**
* @dev Address of the underlying asset (0x0 for Ethereum).
*/
address underlying;
/**
* @dev Address of the strike asset (0x0 for Ethereum).
*/
address strikeAsset;
/**
* @dev True if the type is CALL, false for PUT.
*/
bool isCall;
}
/**
* @dev Emitted when the factory admin address has been changed.
* @param previousFactoryAdmin Address of the previous factory admin.
* @param newFactoryAdmin Address of the new factory admin.
*/
event SetFactoryAdmin(address indexed previousFactoryAdmin, address indexed newFactoryAdmin);
/**
* @dev Emitted when the ACO pool implementation has been changed.
* @param previousAcoPoolImplementation Address of the previous ACO pool implementation.
* @param previousAcoPoolImplementation Address of the new ACO pool implementation.
*/
event SetAcoPoolImplementation(address indexed previousAcoPoolImplementation, address indexed newAcoPoolImplementation);
/**
* @dev Emitted when the ACO factory has been changed.
* @param previousAcoFactory Address of the previous ACO factory.
* @param newAcoFactory Address of the new ACO factory.
*/
event SetAcoFactory(address indexed previousAcoFactory, address indexed newAcoFactory);
/**
* @dev Emitted when the Chi Token has been changed.
* @param previousChiToken Address of the previous Chi Token.
* @param newChiToken Address of the new Chi Token.
*/
event SetChiToken(address indexed previousChiToken, address indexed newChiToken);
/**
* @dev Emitted when the asset converter helper has been changed.
* @param previousAssetConverterHelper Address of the previous asset converter helper.
* @param newAssetConverterHelper Address of the new asset converter helper.
*/
event SetAssetConverterHelper(address indexed previousAssetConverterHelper, address indexed newAssetConverterHelper);
/**
* @dev Emitted when the ACO Pool fee has been changed.
* @param previousAcoFee Value of the previous ACO Pool fee.
* @param newAcoFee Value of the new ACO Pool fee.
*/
event SetAcoPoolFee(uint256 indexed previousAcoFee, uint256 indexed newAcoFee);
/**
* @dev Emitted when the ACO Pool fee destination address has been changed.
* @param previousAcoPoolFeeDestination Address of the previous ACO Pool fee destination.
* @param newAcoPoolFeeDestination Address of the new ACO Pool fee destination.
*/
event SetAcoPoolFeeDestination(address indexed previousAcoPoolFeeDestination, address indexed newAcoPoolFeeDestination);
/**
* @dev Emitted when the ACO Pool penalty percentage on withdrawing open positions has been changed.
* @param previousWithdrawOpenPositionPenalty Value of the previous penalty percentage on withdrawing open positions.
* @param newWithdrawOpenPositionPenalty Value of the new penalty percentage on withdrawing open positions.
*/
event SetAcoPoolWithdrawOpenPositionPenalty(uint256 indexed previousWithdrawOpenPositionPenalty, uint256 indexed newWithdrawOpenPositionPenalty);
/**
* @dev Emitted when the ACO Pool underlying price percentage adjust has been changed.
* @param previousUnderlyingPriceAdjustPercentage Value of the previous ACO Pool underlying price percentage adjust.
* @param newUnderlyingPriceAdjustPercentage Value of the new ACO Pool underlying price percentage adjust.
*/
event SetAcoPoolUnderlyingPriceAdjustPercentage(uint256 indexed previousUnderlyingPriceAdjustPercentage, uint256 indexed newUnderlyingPriceAdjustPercentage);
/**
* @dev Emitted when the ACO Pool maximum number of open ACOs allowed has been changed.
* @param previousMaximumOpenAco Value of the previous ACO Pool maximum number of open ACOs allowed.
* @param newMaximumOpenAco Value of the new ACO Pool maximum number of open ACOs allowed.
*/
event SetAcoPoolMaximumOpenAco(uint256 indexed previousMaximumOpenAco, uint256 indexed newMaximumOpenAco);
/**
* @dev Emitted when permission for an ACO pool admin has been changed.
* @param poolAdmin Address of the ACO pool admin.
* @param previousPermission The previous permission situation.
* @param newPermission The new permission situation.
*/
event SetAcoPoolPermission(address indexed poolAdmin, bool indexed previousPermission, bool indexed newPermission);
/**
* @dev Emitted when a strategy permission has been changed.
* @param strategy Address of the strategy.
* @param previousPermission The previous strategy permission.
* @param newPermission The new strategy permission.
*/
event SetStrategyPermission(address indexed strategy, bool indexed previousPermission, bool newPermission);
/**
* @dev Emitted when a new ACO pool has been created.
* @param underlying Address of the underlying asset (0x0 for Ethereum).
* @param strikeAsset Address of the strike asset (0x0 for Ethereum).
* @param isCall True if the type is CALL, false for PUT.
* @param acoPool Address of the new ACO pool created.
* @param acoPoolImplementation Address of the ACO pool implementation used on creation.
*/
event NewAcoPool(address indexed underlying, address indexed strikeAsset, bool indexed isCall, address acoPool, address acoPoolImplementation);
/**
* @dev The factory admin address.
*/
address public factoryAdmin;
/**
* @dev The ACO pool implementation address.
*/
address public acoPoolImplementation;
/**
* @dev The ACO factory address.
*/
address public acoFactory;
/**
* @dev The ACO asset converter helper.
*/
address public assetConverterHelper;
/**
* @dev The Chi Token address.
*/
address public chiToken;
/**
* @dev The ACO Pool fee value.
* It is a percentage value (100000 is 100%).
*/
uint256 public acoPoolFee;
/**
* @dev The ACO Pool fee destination address.
*/
address public acoPoolFeeDestination;
/**
* @dev The ACO Pool penalty percentage on withdrawing open positions.
*/
uint256 public acoPoolWithdrawOpenPositionPenalty;
/**
* @dev The ACO Pool underlying price percentage adjust.
*/
uint256 public acoPoolUnderlyingPriceAdjustPercentage;
/**
* @dev The ACO Pool maximum number of open ACOs allowed.
*/
uint256 public acoPoolMaximumOpenAco;
/**
* @dev The ACO pool admin permissions.
*/
mapping(address => bool) public poolAdminPermission;
/**
* @dev The strategies permitted.
*/
mapping(address => bool) public strategyPermitted;
/**
* @dev The ACO pool basic data.
*/
mapping(address => ACOPoolBasicData) public acoPoolBasicData;
/**
* @dev Modifier to check if the `msg.sender` is the factory admin.
* Only factory admin address can execute.
*/
modifier onlyFactoryAdmin() {
require(msg.sender == factoryAdmin, "ACOPoolFactory::onlyFactoryAdmin");
_;
}
/**
* @dev Modifier to check if the `msg.sender` is a pool admin.
* Only a pool admin address can execute.
*/
modifier onlyPoolAdmin() {
require(poolAdminPermission[msg.sender], "ACOPoolFactory::onlyPoolAdmin");
_;
}
/**
* @dev Function to initialize the contract.
* It should be called through the `data` argument when creating the proxy.
* It must be called only once. The first `require` is to guarantee that behavior.
* @param _factoryAdmin Address of the factory admin.
* @param _acoPoolImplementation Address of the ACO pool implementation.
* @param _acoFactory Address of the ACO token factory.
* @param _assetConverterHelper Address of the asset converter helper.
* @param _chiToken Address of the Chi token.
* @param _acoPoolFee ACO pool fee percentage.
* @param _acoPoolFeeDestination ACO pool fee destination.
* @param _acoPoolWithdrawOpenPositionPenalty ACO pool penalty percentage on withdrawing open positions.
* @param _acoPoolUnderlyingPriceAdjustPercentage ACO pool underlying price percentage adjust.
* @param _acoPoolMaximumOpenAco ACO pool maximum number of open ACOs allowed.
*/
function init(
address _factoryAdmin,
address _acoPoolImplementation,
address _acoFactory,
address _assetConverterHelper,
address _chiToken,
uint256 _acoPoolFee,
address _acoPoolFeeDestination,
uint256 _acoPoolWithdrawOpenPositionPenalty,
uint256 _acoPoolUnderlyingPriceAdjustPercentage,
uint256 _acoPoolMaximumOpenAco
) public {
require(factoryAdmin == address(0) && acoPoolImplementation == address(0), "ACOPoolFactory::init: Contract already initialized.");
_setFactoryAdmin(_factoryAdmin);
_setAcoPoolImplementation(_acoPoolImplementation);
_setAcoFactory(_acoFactory);
_setAssetConverterHelper(_assetConverterHelper);
_setChiToken(_chiToken);
_setAcoPoolFee(_acoPoolFee);
_setAcoPoolFeeDestination(_acoPoolFeeDestination);
_setAcoPoolWithdrawOpenPositionPenalty(_acoPoolWithdrawOpenPositionPenalty);
_setAcoPoolUnderlyingPriceAdjustPercentage(_acoPoolUnderlyingPriceAdjustPercentage);
_setAcoPoolMaximumOpenAco(_acoPoolMaximumOpenAco);
_setAcoPoolPermission(_factoryAdmin, true);
}
/**
* @dev Function to guarantee that the contract will not receive ether.
*/
receive() external payable virtual {
revert();
}
/**
* @dev Function to create a new ACO pool.
* It deploys a minimal proxy for the ACO pool implementation address.
* @param underlying Address of the underlying asset (0x0 for Ethereum).
* @param strikeAsset Address of the strike asset (0x0 for Ethereum).
* @param isCall True if the type is CALL, false for PUT.
* @param tolerancePriceBelow The below tolerance price percentage for ACO tokens.
* @param tolerancePriceAbove The above tolerance price percentage for ACO tokens.
* @param minExpiration The minimum expiration seconds after the current time for ACO tokens.
* @param maxExpiration The maximum expiration seconds after the current time for ACO tokens.
* @param strategy Address of the pool strategy to be used.
* @param baseVolatility The base volatility for the pool starts. It is a percentage value (100000 is 100%).
* @return The created ACO pool address.
*/
function createAcoPool(
address underlying,
address strikeAsset,
bool isCall,
uint256 tolerancePriceBelow,
uint256 tolerancePriceAbove,
uint256 minExpiration,
uint256 maxExpiration,
address strategy,
uint256 baseVolatility
) onlyFactoryAdmin external virtual returns(address) {
_validateStrategy(strategy);
return _createAcoPool(IACOPool2.InitData(
acoFactory,
chiToken,
underlying,
strikeAsset,
isCall,
assetConverterHelper,
acoPoolFee,
acoPoolFeeDestination,
acoPoolWithdrawOpenPositionPenalty,
acoPoolUnderlyingPriceAdjustPercentage,
acoPoolMaximumOpenAco,
tolerancePriceBelow,
tolerancePriceAbove,
minExpiration,
maxExpiration,
strategy,
baseVolatility
));
}
/**
* @dev Function to set the factory admin address.
* Only can be called by the factory admin.
* @param newFactoryAdmin Address of the new factory admin.
*/
function setFactoryAdmin(address newFactoryAdmin) onlyFactoryAdmin external virtual {
_setFactoryAdmin(newFactoryAdmin);
}
/**
* @dev Function to set the ACO pool implementation address.
* Only can be called by the factory admin.
* @param newAcoPoolImplementation Address of the new ACO pool implementation.
*/
function setAcoPoolImplementation(address newAcoPoolImplementation) onlyFactoryAdmin external virtual {
_setAcoPoolImplementation(newAcoPoolImplementation);
}
/**
* @dev Function to set the ACO factory address.
* Only can be called by the factory admin.
* @param newAcoFactory Address of the ACO token factory.
*/
function setAcoFactory(address newAcoFactory) onlyFactoryAdmin external virtual {
_setAcoFactory(newAcoFactory);
}
/**
* @dev Function to set the Chi Token address.
* Only can be called by the factory admin.
* @param newChiToken Address of the new Chi Token.
*/
function setChiToken(address newChiToken) onlyFactoryAdmin external virtual {
_setChiToken(newChiToken);
}
/**
* @dev Function to set the asset converter helper address.
* Only can be called by the factory admin.
* @param newAssetConverterHelper Address of the new asset converter helper.
*/
function setAssetConverterHelper(address newAssetConverterHelper) onlyFactoryAdmin external virtual {
_setAssetConverterHelper(newAssetConverterHelper);
}
/**
* @dev Function to set the ACO Pool fee.
* Only can be called by the factory admin.
* @param newAcoPoolFee Value of the new ACO Pool fee. It is a percentage value (100000 is 100%).
*/
function setAcoPoolFee(uint256 newAcoPoolFee) onlyFactoryAdmin external virtual {
_setAcoPoolFee(newAcoPoolFee);
}
/**
* @dev Function to set the ACO Pool destination address.
* Only can be called by the factory admin.
* @param newAcoPoolFeeDestination Address of the new ACO Pool destination.
*/
function setAcoPoolFeeDestination(address newAcoPoolFeeDestination) onlyFactoryAdmin external virtual {
_setAcoPoolFeeDestination(newAcoPoolFeeDestination);
}
/**
* @dev Function to set the ACO Pool penalty percentage on withdrawing open positions.
* Only can be called by the factory admin.
* @param newWithdrawOpenPositionPenalty Value of the new ACO Pool penalty percentage on withdrawing open positions. It is a percentage value (100000 is 100%).
*/
function setAcoPoolWithdrawOpenPositionPenalty(uint256 newWithdrawOpenPositionPenalty) onlyFactoryAdmin external virtual {
_setAcoPoolWithdrawOpenPositionPenalty(newWithdrawOpenPositionPenalty);
}
/**
* @dev Function to set the ACO Pool underlying price percentage adjust.
* Only can be called by the factory admin.
* @param newUnderlyingPriceAdjustPercentage Value of the new ACO Pool underlying price percentage adjust. It is a percentage value (100000 is 100%).
*/
function setAcoPoolUnderlyingPriceAdjustPercentage(uint256 newUnderlyingPriceAdjustPercentage) onlyFactoryAdmin external virtual {
_setAcoPoolUnderlyingPriceAdjustPercentage(newUnderlyingPriceAdjustPercentage);
}
/**
* @dev Function to set the ACO Pool maximum number of open ACOs allowed.
* Only can be called by the factory admin.
* @param newMaximumOpenAco Value of the new ACO Pool maximum number of open ACOs allowed.
*/
function setAcoPoolMaximumOpenAco(uint256 newMaximumOpenAco) onlyFactoryAdmin external virtual {
_setAcoPoolMaximumOpenAco(newMaximumOpenAco);
}
/**
* @dev Function to set the ACO pool permission.
* Only can be called by the factory admin.
* @param poolAdmin Address of the pool admin.
* @param newPermission The permission to be set.
*/
function setAcoPoolPermission(address poolAdmin, bool newPermission) onlyFactoryAdmin external virtual {
_setAcoPoolPermission(poolAdmin, newPermission);
}
/**
* @dev Function to set the ACO pool strategies permitted.
* Only can be called by the factory admin.
* @param strategy Address of the strategy.
* @param newPermission The permission to be set.
*/
function setAcoPoolStrategyPermission(address strategy, bool newPermission) onlyFactoryAdmin external virtual {
_setAcoPoolStrategyPermission(strategy, newPermission);
}
/**
* @dev Function to change the ACO pools strategy.
* Only can be called by a pool admin.
* @param strategy Address of the strategy to be set.
* @param acoPools Array of ACO pools addresses.
*/
function setStrategyOnAcoPool(address strategy, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setStrategyOnAcoPool(strategy, acoPools);
}
/**
* @dev Function to change the ACO pools base volatilities.
* Only can be called by a pool admin.
* @param baseVolatilities Array of the base volatilities to be set.
* @param acoPools Array of ACO pools addresses.
*/
function setBaseVolatilityOnAcoPool(uint256[] calldata baseVolatilities, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setAcoPoolUint256Data(IACOPool2.setBaseVolatility.selector, baseVolatilities, acoPools);
}
/**
* @dev Function to change the ACO pools penalties percentages on withdrawing open positions.
* Only can be called by a pool admin.
* @param withdrawOpenPositionPenalties Array of the penalties percentages on withdrawing open positions to be set.
* @param acoPools Array of ACO pools addresses.
*/
function setWithdrawOpenPositionPenaltyOnAcoPool(uint256[] calldata withdrawOpenPositionPenalties, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setAcoPoolUint256Data(IACOPool2.setWithdrawOpenPositionPenalty.selector, withdrawOpenPositionPenalties, acoPools);
}
/**
* @dev Function to change the ACO pools underlying prices percentages adjust.
* Only can be called by a pool admin.
* @param underlyingPriceAdjustPercentages Array of the underlying prices percentages to be set.
* @param acoPools Array of ACO pools addresses.
*/
function setUnderlyingPriceAdjustPercentageOnAcoPool(uint256[] calldata underlyingPriceAdjustPercentages, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setAcoPoolUint256Data(IACOPool2.setUnderlyingPriceAdjustPercentage.selector, underlyingPriceAdjustPercentages, acoPools);
}
/**
* @dev Function to change the ACO pools maximum number of open ACOs allowed.
* Only can be called by a pool admin.
* @param maximumOpenAcos Array of the maximum number of open ACOs allowed.
* @param acoPools Array of ACO pools addresses.
*/
function setMaximumOpenAcoOnAcoPool(uint256[] calldata maximumOpenAcos, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setAcoPoolUint256Data(IACOPool2.setMaximumOpenAco.selector, maximumOpenAcos, acoPools);
}
/**
* @dev Function to change the ACO pools below tolerance prices percentages.
* Only can be called by a pool admin.
* @param tolerancePricesBelow Array of the below tolerance prices percentages to be set.
* @param acoPools Array of ACO pools addresses.
*/
function setTolerancePriceBelowOnAcoPool(uint256[] calldata tolerancePricesBelow, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setAcoPoolUint256Data(IACOPool2.setTolerancePriceBelow.selector, tolerancePricesBelow, acoPools);
}
/**
* @dev Function to change the ACO pools above tolerance prices percentages.
* Only can be called by a pool admin.
* @param tolerancePricesAbove Array of the above tolerance prices percentages to be set.
* @param acoPools Array of ACO pools addresses.
*/
function setTolerancePriceAboveOnAcoPool(uint256[] calldata tolerancePricesAbove, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setAcoPoolUint256Data(IACOPool2.setTolerancePriceAbove.selector, tolerancePricesAbove, acoPools);
}
/**
* @dev Function to change the ACO pools minimum expirations.
* Only can be called by a pool admin.
* @param minExpirations Array of the minimum expirations.
* @param acoPools Array of ACO pools addresses.
*/
function setMinExpirationOnAcoPool(uint256[] calldata minExpirations, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setAcoPoolUint256Data(IACOPool2.setMinExpiration.selector, minExpirations, acoPools);
}
/**
* @dev Function to change the ACO pools maximum expirations.
* Only can be called by a pool admin.
* @param maxExpirations Array of the maximum expirations to be set.
* @param acoPools Array of ACO pools addresses.
*/
function setMaxExpirationOnAcoPool(uint256[] calldata maxExpirations, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setAcoPoolUint256Data(IACOPool2.setMaxExpiration.selector, maxExpirations, acoPools);
}
/**
* @dev Function to change the ACO pools fee.
* Only can be called by a pool admin.
* @param fees Array of the fees.
* @param acoPools Array of ACO pools addresses.
*/
function setFeeOnAcoPool(uint256[] calldata fees, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setAcoPoolUint256Data(IACOPool2.setFee.selector, fees, acoPools);
}
/**
* @dev Function to change the ACO pools fee destinations.
* Only can be called by a pool admin.
* @param feeDestinations Array of the fee destinations.
* @param acoPools Array of ACO pools addresses.
*/
function setFeeDestinationOnAcoPool(address[] calldata feeDestinations, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setAcoPoolAddressData(IACOPool2.setFeeDestination.selector, feeDestinations, acoPools);
}
/**
* @dev Function to change the ACO pools asset converters.
* Only can be called by a pool admin.
* @param assetConverters Array of the asset converters.
* @param acoPools Array of ACO pools addresses.
*/
function setAssetConverterOnAcoPool(address[] calldata assetConverters, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setAcoPoolAddressData(IACOPool2.setAssetConverter.selector, assetConverters, acoPools);
}
/**
* @dev Function to change the ACO pools ACO creator permission.
* Only can be called by a pool admin.
* @param acoCreator Address of the ACO creator.
* @param permission Permission situation.
* @param acoPools Array of ACO pools addresses.
*/
function setValidAcoCreatorOnAcoPool(address acoCreator, bool permission, address[] calldata acoPools) onlyPoolAdmin external virtual {
_setValidAcoCreatorOnAcoPool(acoCreator, permission, acoPools);
}
/**
* @dev Function to withdraw the ACO pools stucked asset.
* @param asset Address of the asset.
* @param destination Address of the destination.
* @param acoPools Array of ACO pools addresses.
*/
function withdrawStuckAssetOnAcoPool(address asset, address destination, address[] calldata acoPools) onlyPoolAdmin external virtual {
_withdrawStuckAssetOnAcoPool(asset, destination, acoPools);
}
/**
* @dev Internal function to set the factory admin address.
* @param newFactoryAdmin Address of the new factory admin.
*/
function _setFactoryAdmin(address newFactoryAdmin) internal virtual {
require(newFactoryAdmin != address(0), "ACOPoolFactory::_setFactoryAdmin: Invalid factory admin");
emit SetFactoryAdmin(factoryAdmin, newFactoryAdmin);
factoryAdmin = newFactoryAdmin;
}
/**
* @dev Internal function to set the ACO pool implementation address.
* @param newAcoPoolImplementation Address of the new ACO pool implementation.
*/
function _setAcoPoolImplementation(address newAcoPoolImplementation) internal virtual {
require(Address.isContract(newAcoPoolImplementation), "ACOPoolFactory::_setAcoPoolImplementation: Invalid ACO pool implementation");
emit SetAcoPoolImplementation(acoPoolImplementation, newAcoPoolImplementation);
acoPoolImplementation = newAcoPoolImplementation;
}
/**
* @dev Internal function to set the ACO factory address.
* @param newAcoFactory Address of the new ACO token factory.
*/
function _setAcoFactory(address newAcoFactory) internal virtual {
require(Address.isContract(newAcoFactory), "ACOPoolFactory::_setAcoFactory: Invalid ACO factory");
emit SetAcoFactory(acoFactory, newAcoFactory);
acoFactory = newAcoFactory;
}
/**
* @dev Internal function to set the asset converter helper address.
* @param newAssetConverterHelper Address of the new asset converter helper.
*/
function _setAssetConverterHelper(address newAssetConverterHelper) internal virtual {
require(Address.isContract(newAssetConverterHelper), "ACOPoolFactory::_setAssetConverterHelper: Invalid asset converter helper");
emit SetAssetConverterHelper(assetConverterHelper, newAssetConverterHelper);
assetConverterHelper = newAssetConverterHelper;
}
/**
* @dev Internal function to set the Chi Token address.
* @param newChiToken Address of the new Chi Token.
*/
function _setChiToken(address newChiToken) internal virtual {
require(Address.isContract(newChiToken), "ACOPoolFactory::_setChiToken: Invalid Chi Token");
emit SetChiToken(chiToken, newChiToken);
chiToken = newChiToken;
}
/**
* @dev Internal function to set the ACO Pool fee.
* @param newAcoPoolFee Value of the new ACO Pool fee. It is a percentage value (100000 is 100%).
*/
function _setAcoPoolFee(uint256 newAcoPoolFee) internal virtual {
emit SetAcoPoolFee(acoPoolFee, newAcoPoolFee);
acoPoolFee = newAcoPoolFee;
}
/**
* @dev Internal function to set the ACO Pool destination address.
* @param newAcoPoolFeeDestination Address of the new ACO Pool destination.
*/
function _setAcoPoolFeeDestination(address newAcoPoolFeeDestination) internal virtual {
require(newAcoPoolFeeDestination != address(0), "ACOFactory::_setAcoPoolFeeDestination: Invalid ACO Pool fee destination");
emit SetAcoPoolFeeDestination(acoPoolFeeDestination, newAcoPoolFeeDestination);
acoPoolFeeDestination = newAcoPoolFeeDestination;
}
/**
* @dev Internal function to set the ACO Pool penalty percentage on withdrawing open positions.
* @param newWithdrawOpenPositionPenalty Value of the new ACO Pool penalty percentage on withdrawing open positions. It is a percentage value (100000 is 100%).
*/
function _setAcoPoolWithdrawOpenPositionPenalty(uint256 newWithdrawOpenPositionPenalty) internal virtual {
emit SetAcoPoolWithdrawOpenPositionPenalty(acoPoolWithdrawOpenPositionPenalty, newWithdrawOpenPositionPenalty);
acoPoolWithdrawOpenPositionPenalty = newWithdrawOpenPositionPenalty;
}
/**
* @dev Internal function to set the ACO Pool underlying price percentage adjust.
* @param newUnderlyingPriceAdjustPercentage Value of the new ACO Pool underlying price percentage adjust. It is a percentage value (100000 is 100%).
*/
function _setAcoPoolUnderlyingPriceAdjustPercentage(uint256 newUnderlyingPriceAdjustPercentage) internal virtual {
emit SetAcoPoolUnderlyingPriceAdjustPercentage(acoPoolUnderlyingPriceAdjustPercentage, newUnderlyingPriceAdjustPercentage);
acoPoolUnderlyingPriceAdjustPercentage = newUnderlyingPriceAdjustPercentage;
}
/**
* @dev Internal function to set the ACO Pool maximum number of open ACOs allowed.
* @param newMaximumOpenAco Value of the new ACO Pool maximum number of open ACOs allowed.
*/
function _setAcoPoolMaximumOpenAco(uint256 newMaximumOpenAco) internal virtual {
emit SetAcoPoolMaximumOpenAco(acoPoolMaximumOpenAco, newMaximumOpenAco);
acoPoolMaximumOpenAco = newMaximumOpenAco;
}
/**
* @dev Internal function to set the ACO pool permission.
* @param poolAdmin Address of the pool admin.
* @param newPermission The permission to be set.
*/
function _setAcoPoolPermission(address poolAdmin, bool newPermission) internal virtual {
emit SetAcoPoolPermission(poolAdmin, poolAdminPermission[poolAdmin], newPermission);
poolAdminPermission[poolAdmin] = newPermission;
}
/**
* @dev Internal function to set the ACO pool strategies permitted.
* @param strategy Address of the strategy.
* @param newPermission The permission to be set.
*/
function _setAcoPoolStrategyPermission(address strategy, bool newPermission) internal virtual {
require(Address.isContract(strategy), "ACOPoolFactory::_setAcoPoolStrategy: Invalid strategy");
emit SetStrategyPermission(strategy, strategyPermitted[strategy], newPermission);
strategyPermitted[strategy] = newPermission;
}
/**
* @dev Internal function to validate strategy.
* @param strategy Address of the strategy.
*/
function _validateStrategy(address strategy) view internal virtual {
require(strategyPermitted[strategy], "ACOPoolFactory::_validateStrategy: Invalid strategy");
}
/**
* @dev Internal function to change the ACO pools strategy.
* @param strategy Address of the strategy to be set.
* @param acoPools Array of ACO pools addresses.
*/
function _setStrategyOnAcoPool(address strategy, address[] memory acoPools) internal virtual {
_validateStrategy(strategy);
for (uint256 i = 0; i < acoPools.length; ++i) {
IACOPool2(acoPools[i]).setStrategy(strategy);
}
}
/**
* @dev Internal function to change the ACO pools ACO creator permission.
* @param acoCreator Address of the ACO creator.
* @param permission Permission situation.
* @param acoPools Array of ACO pools addresses.
*/
function _setValidAcoCreatorOnAcoPool(address acoCreator, bool permission, address[] memory acoPools) internal virtual {
for (uint256 i = 0; i < acoPools.length; ++i) {
IACOPool2(acoPools[i]).setValidAcoCreator(acoCreator, permission);
}
}
/**
* @dev Internal function to withdraw the ACO pools stucked asset.
* @param asset Address of the asset.
* @param destination Address of the destination.
* @param acoPools Array of ACO pools addresses.
*/
function _withdrawStuckAssetOnAcoPool(address asset, address destination, address[] memory acoPools) internal virtual {
for (uint256 i = 0; i < acoPools.length; ++i) {
IACOPool2(acoPools[i]).withdrawStuckToken(asset, destination);
}
}
/**
* @dev Internal function to change the ACO pools an uint256 data.
* @param selector Function selector to be called on the ACO pool.
* @param numbers Array of the numbers to be set.
* @param acoPools Array of ACO pools addresses.
*/
function _setAcoPoolUint256Data(bytes4 selector, uint256[] memory numbers, address[] memory acoPools) internal virtual {
require(numbers.length == acoPools.length, "ACOPoolFactory::_setAcoPoolUint256Data: Invalid arguments");
for (uint256 i = 0; i < acoPools.length; ++i) {
(bool success,) = acoPools[i].call(abi.encodeWithSelector(selector, numbers[i]));
require(success, "ACOPoolFactory::_setAcoPoolUint256Data");
}
}
/**
* @dev Internal function to change the ACO pools an address data.
* @param selector Function selector to be called on the ACO pool.
* @param addresses Array of the addresses to be set.
* @param acoPools Array of ACO pools addresses.
*/
function _setAcoPoolAddressData(bytes4 selector, address[] memory addresses, address[] memory acoPools) internal virtual {
require(addresses.length == acoPools.length, "ACOPoolFactory::_setAcoPoolAddressData: Invalid arguments");
for (uint256 i = 0; i < acoPools.length; ++i) {
(bool success,) = acoPools[i].call(abi.encodeWithSelector(selector, addresses[i]));
require(success, "ACOPoolFactory::_setAcoPoolAddressData");
}
}
/**
* @dev Internal function to create a new ACO pool.
* @param initData Data to initialize o ACO Pool.
* @return Address of the new minimal proxy deployed for the ACO pool.
*/
function _createAcoPool(IACOPool2.InitData memory initData) internal virtual returns(address) {
address acoPool = _deployAcoPool(initData);
acoPoolBasicData[acoPool] = ACOPoolBasicData(initData.underlying, initData.strikeAsset, initData.isCall);
emit NewAcoPool(
initData.underlying,
initData.strikeAsset,
initData.isCall,
acoPool,
acoPoolImplementation
);
return acoPool;
}
/**
* @dev Internal function to deploy a minimal proxy using ACO pool implementation.
* @param initData Data to initialize o ACO Pool.
* @return Address of the new minimal proxy deployed for the ACO pool.
*/
function _deployAcoPool(IACOPool2.InitData memory initData) internal virtual returns(address) {
bytes20 implentationBytes = bytes20(acoPoolImplementation);
address proxy;
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), implentationBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
proxy := create(0, clone, 0x37)
}
IACOPool2(proxy).init(initData);
return proxy;
}
}
|
Internal function to create a new ACO pool. initData Data to initialize o ACO Pool. return Address of the new minimal proxy deployed for the ACO pool./
|
function _createAcoPool(IACOPool2.InitData memory initData) internal virtual returns(address) {
address acoPool = _deployAcoPool(initData);
acoPoolBasicData[acoPool] = ACOPoolBasicData(initData.underlying, initData.strikeAsset, initData.isCall);
emit NewAcoPool(
initData.underlying,
initData.strikeAsset,
initData.isCall,
acoPool,
acoPoolImplementation
);
return acoPool;
}
| 128,908 |
./full_match/137/0x7eF2460D6643f37d317B9AA274cF76e4D9f24071/sources/contracts/erc20-bep20-trc20-token-template/ERC20Token.sol
|
set the presenter of the token to decide transfer functionality _presenter address of presenter/
|
function setPresenter(address _presenter) onlyOwner public {
presenter = _presenter;
}
| 4,675,091 |
./partial_match/1/0x0C736ED2B5fA80A0cd4Bb2956131598CbF13736C/sources/FUCKFUCKFUCK.sol
|
See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`./
|
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
| 3,965,498 |
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/controller/Reputation.sol
/**
* @title Reputation system
* @dev A DAO has Reputation System which allows peers to rate other peers in order to build trust .
* A reputation is use to assign influence measure to a DAO'S peers.
* Reputation is similar to regular tokens but with one crucial difference: It is non-transferable.
* The Reputation contract maintain a map of address to reputation value.
* It provides an onlyOwner functions to mint and burn reputation _to (or _from) a specific address.
*/
contract Reputation is Ownable {
using SafeMath for uint;
mapping (address => uint256) public balances;
uint256 public totalSupply;
uint public decimals = 18;
// Event indicating minting of reputation to an address.
event Mint(address indexed _to, uint256 _amount);
// Event indicating burning of reputation for an address.
event Burn(address indexed _from, uint256 _amount);
/**
* @dev return the reputation amount of a given owner
* @param _owner an address of the owner which we want to get his reputation
*/
function reputationOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Generates `_amount` of reputation that are assigned to `_to`
* @param _to The address that will be assigned the new reputation
* @param _amount The quantity of reputation to be generated
* @return True if the reputation are generated correctly
*/
function mint(address _to, uint _amount)
public
onlyOwner
returns (bool)
{
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
return true;
}
/**
* @dev Burns `_amount` of reputation from `_from`
* if _amount tokens to burn > balances[_from] the balance of _from will turn to zero.
* @param _from The address that will lose the reputation
* @param _amount The quantity of reputation to burn
* @return True if the reputation are burned correctly
*/
function burn(address _from, uint _amount)
public
onlyOwner
returns (bool)
{
uint amountMinted = _amount;
if (balances[_from] < _amount) {
amountMinted = balances[_from];
}
totalSupply = totalSupply.sub(amountMinted);
balances[_from] = balances[_from].sub(amountMinted);
emit Burn(_from, amountMinted);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: contracts/token/ERC827/ERC827.sol
/**
* @title ERC827 interface, an extension of ERC20 token standard
*
* @dev Interface of a ERC827 token, following the ERC20 standard with extra
* methods to transfer value and data and execute calls in transfers and
* approvals.
*/
contract ERC827 is ERC20 {
function approveAndCall(address _spender,uint256 _value,bytes _data) public payable returns(bool);
function transferAndCall(address _to,uint256 _value,bytes _data) public payable returns(bool);
function transferFromAndCall(address _from,address _to,uint256 _value,bytes _data) public payable returns(bool);
}
// File: contracts/token/ERC827/ERC827Token.sol
/* solium-disable security/no-low-level-calls */
pragma solidity ^0.4.24;
/**
* @title ERC827, an extension of ERC20 token standard
*
* @dev Implementation the ERC827, following the ERC20 standard with extra
* methods to transfer value and data and execute calls in transfers and
* approvals. Uses OpenZeppelin StandardToken.
*/
contract ERC827Token is ERC827, StandardToken {
/**
* @dev Addition to ERC20 token methods. It allows to
* approve the transfer of value and execute a call with the sent data.
* Beware that changing an allowance with this method brings the risk that
* someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race condition
* is to first reduce the spender's allowance to 0 and set the desired value
* afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address that will spend the funds.
* @param _value The amount of tokens to be spent.
* @param _data ABI-encoded contract call to call `_spender` address.
* @return true if the call function was executed successfully
*/
function approveAndCall(
address _spender,
uint256 _value,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.approve(_spender, _value);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens to a specified
* address and execute a call with the sent data on the same transaction
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
* @param _data ABI-encoded contract call to call `_to` address.
* @return true if the call function was executed successfully
*/
function transferAndCall(
address _to,
uint256 _value,
bytes _data
)
public
payable
returns (bool)
{
require(_to != address(this));
super.transfer(_to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens from one address to
* another and make a contract call on the same transaction
* @param _from The address which you want to send tokens from
* @param _to The address which you want to transfer to
* @param _value The amout of tokens to be transferred
* @param _data ABI-encoded contract call to call `_to` address.
* @return true if the call function was executed successfully
*/
function transferFromAndCall(
address _from,
address _to,
uint256 _value,
bytes _data
)
public payable returns (bool)
{
require(_to != address(this));
super.transferFrom(_from, _to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Increase the amount of tokens that
* an owner allowed to a spender and execute a call with the sent data.
* 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.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function increaseApprovalAndCall(
address _spender,
uint _addedValue,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.increaseApproval(_spender, _addedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Decrease the amount of tokens that
* an owner allowed to a spender and execute a call with the sent data.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function decreaseApprovalAndCall(
address _spender,
uint _subtractedValue,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.decreaseApproval(_spender, _subtractedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
}
// File: contracts/controller/DAOToken.sol
/**
* @title DAOToken, base on zeppelin contract.
* @dev ERC20 compatible token. It is a mintable, destructible, burnable token.
*/
contract DAOToken is ERC827Token,MintableToken,BurnableToken {
string public name;
string public symbol;
// solium-disable-next-line uppercase
uint8 public constant decimals = 18;
uint public cap;
/**
* @dev Constructor
* @param _name - token name
* @param _symbol - token symbol
* @param _cap - token cap - 0 value means no cap
*/
constructor(string _name, string _symbol,uint _cap) public {
name = _name;
symbol = _symbol;
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) {
if (cap > 0)
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
// File: contracts/controller/Avatar.sol
/**
* @title An Avatar holds tokens, reputation and ether for a controller
*/
contract Avatar is Ownable {
bytes32 public orgName;
DAOToken public nativeToken;
Reputation public nativeReputation;
event GenericAction(address indexed _action, bytes32[] _params);
event SendEther(uint _amountInWei, address indexed _to);
event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint _value);
event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint _value);
event ExternalTokenIncreaseApproval(StandardToken indexed _externalToken, address _spender, uint _addedValue);
event ExternalTokenDecreaseApproval(StandardToken indexed _externalToken, address _spender, uint _subtractedValue);
event ReceiveEther(address indexed _sender, uint _value);
/**
* @dev the constructor takes organization name, native token and reputation system
and creates an avatar for a controller
*/
constructor(bytes32 _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
/**
* @dev enables an avatar to receive ethers
*/
function() public payable {
emit ReceiveEther(msg.sender, msg.value);
}
/**
* @dev perform a generic call to an arbitrary contract
* @param _contract the contract's address to call
* @param _data ABI-encoded contract call to call `_contract` address.
* @return the return bytes of the called contract's function.
*/
function genericCall(address _contract,bytes _data) public onlyOwner {
// solium-disable-next-line security/no-low-level-calls
bool result = _contract.call(_data);
// solium-disable-next-line security/no-inline-assembly
assembly {
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// call returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev send ethers from the avatar's wallet
* @param _amountInWei amount to send in Wei units
* @param _to send the ethers to this address
* @return bool which represents success
*/
function sendEther(uint _amountInWei, address _to) public onlyOwner returns(bool) {
_to.transfer(_amountInWei);
emit SendEther(_amountInWei, _to);
return true;
}
/**
* @dev external token transfer
* @param _externalToken the token contract
* @param _to the destination address
* @param _value the amount of tokens to transfer
* @return bool which represents success
*/
function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value)
public onlyOwner returns(bool)
{
_externalToken.transfer(_to, _value);
emit ExternalTokenTransfer(_externalToken, _to, _value);
return true;
}
/**
* @dev external token transfer from a specific account
* @param _externalToken the token contract
* @param _from the account to spend token from
* @param _to the destination address
* @param _value the amount of tokens to transfer
* @return bool which represents success
*/
function externalTokenTransferFrom(
StandardToken _externalToken,
address _from,
address _to,
uint _value
)
public onlyOwner returns(bool)
{
_externalToken.transferFrom(_from, _to, _value);
emit ExternalTokenTransferFrom(_externalToken, _from, _to, _value);
return true;
}
/**
* @dev increase approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _addedValue the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue)
public onlyOwner returns(bool)
{
_externalToken.increaseApproval(_spender, _addedValue);
emit ExternalTokenIncreaseApproval(_externalToken, _spender, _addedValue);
return true;
}
/**
* @dev decrease approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _subtractedValue the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue )
public onlyOwner returns(bool)
{
_externalToken.decreaseApproval(_spender, _subtractedValue);
emit ExternalTokenDecreaseApproval(_externalToken,_spender, _subtractedValue);
return true;
}
}
// File: contracts/globalConstraints/GlobalConstraintInterface.sol
contract GlobalConstraintInterface {
enum CallPhase { Pre, Post,PreAndPost }
function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
/**
* @dev when return if this globalConstraints is pre, post or both.
* @return CallPhase enum indication Pre, Post or PreAndPost.
*/
function when() public returns(CallPhase);
}
// File: contracts/controller/ControllerInterface.sol
/**
* @title Controller contract
* @dev A controller controls the organizations tokens ,reputation and avatar.
* It is subject to a set of schemes and constraints that determine its behavior.
* Each scheme has it own parameters and operation permissions.
*/
interface ControllerInterface {
/**
* @dev Mint `_amount` of reputation that are assigned to `_to` .
* @param _amount amount of reputation to mint
* @param _to beneficiary address
* @return bool which represents a success
*/
function mintReputation(uint256 _amount, address _to,address _avatar)
external
returns(bool);
/**
* @dev Burns `_amount` of reputation from `_from`
* @param _amount amount of reputation to burn
* @param _from The address that will lose the reputation
* @return bool which represents a success
*/
function burnReputation(uint256 _amount, address _from,address _avatar)
external
returns(bool);
/**
* @dev mint tokens .
* @param _amount amount of token to mint
* @param _beneficiary beneficiary address
* @param _avatar address
* @return bool which represents a success
*/
function mintTokens(uint256 _amount, address _beneficiary,address _avatar)
external
returns(bool);
/**
* @dev register or update a scheme
* @param _scheme the address of the scheme
* @param _paramsHash a hashed configuration of the usage of the scheme
* @param _permissions the permissions the new scheme will have
* @param _avatar address
* @return bool which represents a success
*/
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions,address _avatar)
external
returns(bool);
/**
* @dev unregister a scheme
* @param _avatar address
* @param _scheme the address of the scheme
* @return bool which represents a success
*/
function unregisterScheme(address _scheme,address _avatar)
external
returns(bool);
/**
* @dev unregister the caller's scheme
* @param _avatar address
* @return bool which represents a success
*/
function unregisterSelf(address _avatar) external returns(bool);
function isSchemeRegistered( address _scheme,address _avatar) external view returns(bool);
function getSchemeParameters(address _scheme,address _avatar) external view returns(bytes32);
function getGlobalConstraintParameters(address _globalConstraint,address _avatar) external view returns(bytes32);
function getSchemePermissions(address _scheme,address _avatar) external view returns(bytes4);
/**
* @dev globalConstraintsCount return the global constraint pre and post count
* @return uint globalConstraintsPre count.
* @return uint globalConstraintsPost count.
*/
function globalConstraintsCount(address _avatar) external view returns(uint,uint);
function isGlobalConstraintRegistered(address _globalConstraint,address _avatar) external view returns(bool);
/**
* @dev add or update Global Constraint
* @param _globalConstraint the address of the global constraint to be added.
* @param _params the constraint parameters hash.
* @param _avatar the avatar of the organization
* @return bool which represents a success
*/
function addGlobalConstraint(address _globalConstraint, bytes32 _params,address _avatar)
external returns(bool);
/**
* @dev remove Global Constraint
* @param _globalConstraint the address of the global constraint to be remove.
* @param _avatar the organization avatar.
* @return bool which represents a success
*/
function removeGlobalConstraint (address _globalConstraint,address _avatar)
external returns(bool);
/**
* @dev upgrade the Controller
* The function will trigger an event 'UpgradeController'.
* @param _newController the address of the new controller.
* @param _avatar address
* @return bool which represents a success
*/
function upgradeController(address _newController,address _avatar)
external returns(bool);
/**
* @dev perform a generic call to an arbitrary contract
* @param _contract the contract's address to call
* @param _data ABI-encoded contract call to call `_contract` address.
* @param _avatar the controller's avatar address
* @return bytes32 - the return value of the called _contract's function.
*/
function genericCall(address _contract,bytes _data,address _avatar)
external
returns(bytes32);
/**
* @dev send some ether
* @param _amountInWei the amount of ether (in Wei) to send
* @param _to address of the beneficiary
* @param _avatar address
* @return bool which represents a success
*/
function sendEther(uint _amountInWei, address _to,address _avatar)
external returns(bool);
/**
* @dev send some amount of arbitrary ERC20 Tokens
* @param _externalToken the address of the Token Contract
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @param _avatar address
* @return bool which represents a success
*/
function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value,address _avatar)
external
returns(bool);
/**
* @dev transfer token "from" address "to" address
* One must to approve the amount of tokens which can be spend from the
* "from" account.This can be done using externalTokenApprove.
* @param _externalToken the address of the Token Contract
* @param _from address of the account to send from
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @param _avatar address
* @return bool which represents a success
*/
function externalTokenTransferFrom(StandardToken _externalToken, address _from, address _to, uint _value,address _avatar)
external
returns(bool);
/**
* @dev increase approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _addedValue the amount of ether (in Wei) which the approval is referring to.
* @param _avatar address
* @return bool which represents a success
*/
function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue,address _avatar)
external
returns(bool);
/**
* @dev decrease approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _subtractedValue the amount of ether (in Wei) which the approval is referring to.
* @param _avatar address
* @return bool which represents a success
*/
function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue,address _avatar)
external
returns(bool);
/**
* @dev getNativeReputation
* @param _avatar the organization avatar.
* @return organization native reputation
*/
function getNativeReputation(address _avatar)
external
view
returns(address);
}
// File: contracts/controller/Controller.sol
/**
* @title Controller contract
* @dev A controller controls the organizations tokens,reputation and avatar.
* It is subject to a set of schemes and constraints that determine its behavior.
* Each scheme has it own parameters and operation permissions.
*/
contract Controller is ControllerInterface {
struct Scheme {
bytes32 paramsHash; // a hash "configuration" of the scheme
bytes4 permissions; // A bitwise flags of permissions,
// All 0: Not registered,
// 1st bit: Flag if the scheme is registered,
// 2nd bit: Scheme can register other schemes
// 3rd bit: Scheme can add/remove global constraints
// 4th bit: Scheme can upgrade the controller
// 5th bit: Scheme can call genericCall on behalf of
// the organization avatar
}
struct GlobalConstraint {
address gcAddress;
bytes32 params;
}
struct GlobalConstraintRegister {
bool isRegistered; //is registered
uint index; //index at globalConstraints
}
mapping(address=>Scheme) public schemes;
Avatar public avatar;
DAOToken public nativeToken;
Reputation public nativeReputation;
// newController will point to the new controller after the present controller is upgraded
address public newController;
// globalConstraintsPre that determine pre conditions for all actions on the controller
GlobalConstraint[] public globalConstraintsPre;
// globalConstraintsPost that determine post conditions for all actions on the controller
GlobalConstraint[] public globalConstraintsPost;
// globalConstraintsRegisterPre indicate if a globalConstraints is registered as a pre global constraint
mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPre;
// globalConstraintsRegisterPost indicate if a globalConstraints is registered as a post global constraint
mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPost;
event MintReputation (address indexed _sender, address indexed _to, uint256 _amount);
event BurnReputation (address indexed _sender, address indexed _from, uint256 _amount);
event MintTokens (address indexed _sender, address indexed _beneficiary, uint256 _amount);
event RegisterScheme (address indexed _sender, address indexed _scheme);
event UnregisterScheme (address indexed _sender, address indexed _scheme);
event GenericAction (address indexed _sender, bytes32[] _params);
event SendEther (address indexed _sender, uint _amountInWei, address indexed _to);
event ExternalTokenTransfer (address indexed _sender, address indexed _externalToken, address indexed _to, uint _value);
event ExternalTokenTransferFrom (address indexed _sender, address indexed _externalToken, address _from, address _to, uint _value);
event ExternalTokenIncreaseApproval (address indexed _sender, StandardToken indexed _externalToken, address _spender, uint _value);
event ExternalTokenDecreaseApproval (address indexed _sender, StandardToken indexed _externalToken, address _spender, uint _value);
event UpgradeController(address indexed _oldController,address _newController);
event AddGlobalConstraint(address indexed _globalConstraint, bytes32 _params,GlobalConstraintInterface.CallPhase _when);
event RemoveGlobalConstraint(address indexed _globalConstraint ,uint256 _index,bool _isPre);
event GenericCall(address indexed _contract,bytes _data);
constructor( Avatar _avatar) public
{
avatar = _avatar;
nativeToken = avatar.nativeToken();
nativeReputation = avatar.nativeReputation();
schemes[msg.sender] = Scheme({paramsHash: bytes32(0),permissions: bytes4(0x1F)});
}
// Do not allow mistaken calls:
function() external {
revert();
}
// Modifiers:
modifier onlyRegisteredScheme() {
require(schemes[msg.sender].permissions&bytes4(1) == bytes4(1));
_;
}
modifier onlyRegisteringSchemes() {
require(schemes[msg.sender].permissions&bytes4(2) == bytes4(2));
_;
}
modifier onlyGlobalConstraintsScheme() {
require(schemes[msg.sender].permissions&bytes4(4) == bytes4(4));
_;
}
modifier onlyUpgradingScheme() {
require(schemes[msg.sender].permissions&bytes4(8) == bytes4(8));
_;
}
modifier onlyGenericCallScheme() {
require(schemes[msg.sender].permissions&bytes4(16) == bytes4(16));
_;
}
modifier onlySubjectToConstraint(bytes32 func) {
uint idx;
for (idx = 0;idx<globalConstraintsPre.length;idx++) {
require((GlobalConstraintInterface(globalConstraintsPre[idx].gcAddress)).pre(msg.sender,globalConstraintsPre[idx].params,func));
}
_;
for (idx = 0;idx<globalConstraintsPost.length;idx++) {
require((GlobalConstraintInterface(globalConstraintsPost[idx].gcAddress)).post(msg.sender,globalConstraintsPost[idx].params,func));
}
}
modifier isAvatarValid(address _avatar) {
require(_avatar == address(avatar));
_;
}
/**
* @dev Mint `_amount` of reputation that are assigned to `_to` .
* @param _amount amount of reputation to mint
* @param _to beneficiary address
* @return bool which represents a success
*/
function mintReputation(uint256 _amount, address _to,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("mintReputation")
isAvatarValid(_avatar)
returns(bool)
{
emit MintReputation(msg.sender, _to, _amount);
return nativeReputation.mint(_to, _amount);
}
/**
* @dev Burns `_amount` of reputation from `_from`
* @param _amount amount of reputation to burn
* @param _from The address that will lose the reputation
* @return bool which represents a success
*/
function burnReputation(uint256 _amount, address _from,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("burnReputation")
isAvatarValid(_avatar)
returns(bool)
{
emit BurnReputation(msg.sender, _from, _amount);
return nativeReputation.burn(_from, _amount);
}
/**
* @dev mint tokens .
* @param _amount amount of token to mint
* @param _beneficiary beneficiary address
* @return bool which represents a success
*/
function mintTokens(uint256 _amount, address _beneficiary,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("mintTokens")
isAvatarValid(_avatar)
returns(bool)
{
emit MintTokens(msg.sender, _beneficiary, _amount);
return nativeToken.mint(_beneficiary, _amount);
}
/**
* @dev register a scheme
* @param _scheme the address of the scheme
* @param _paramsHash a hashed configuration of the usage of the scheme
* @param _permissions the permissions the new scheme will have
* @return bool which represents a success
*/
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions,address _avatar)
external
onlyRegisteringSchemes
onlySubjectToConstraint("registerScheme")
isAvatarValid(_avatar)
returns(bool)
{
Scheme memory scheme = schemes[_scheme];
// Check scheme has at least the permissions it is changing, and at least the current permissions:
// Implementation is a bit messy. One must recall logic-circuits ^^
// produces non-zero if sender does not have all of the perms that are changing between old and new
require(bytes4(0x1F)&(_permissions^scheme.permissions)&(~schemes[msg.sender].permissions) == bytes4(0));
// produces non-zero if sender does not have all of the perms in the old scheme
require(bytes4(0x1F)&(scheme.permissions&(~schemes[msg.sender].permissions)) == bytes4(0));
// Add or change the scheme:
schemes[_scheme].paramsHash = _paramsHash;
schemes[_scheme].permissions = _permissions|bytes4(1);
emit RegisterScheme(msg.sender, _scheme);
return true;
}
/**
* @dev unregister a scheme
* @param _scheme the address of the scheme
* @return bool which represents a success
*/
function unregisterScheme( address _scheme,address _avatar)
external
onlyRegisteringSchemes
onlySubjectToConstraint("unregisterScheme")
isAvatarValid(_avatar)
returns(bool)
{
//check if the scheme is registered
if (schemes[_scheme].permissions&bytes4(1) == bytes4(0)) {
return false;
}
// Check the unregistering scheme has enough permissions:
require(bytes4(0x1F)&(schemes[_scheme].permissions&(~schemes[msg.sender].permissions)) == bytes4(0));
// Unregister:
emit UnregisterScheme(msg.sender, _scheme);
delete schemes[_scheme];
return true;
}
/**
* @dev unregister the caller's scheme
* @return bool which represents a success
*/
function unregisterSelf(address _avatar) external isAvatarValid(_avatar) returns(bool) {
if (_isSchemeRegistered(msg.sender,_avatar) == false) {
return false;
}
delete schemes[msg.sender];
emit UnregisterScheme(msg.sender, msg.sender);
return true;
}
function isSchemeRegistered(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bool) {
return _isSchemeRegistered(_scheme,_avatar);
}
function getSchemeParameters(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bytes32) {
return schemes[_scheme].paramsHash;
}
function getSchemePermissions(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bytes4) {
return schemes[_scheme].permissions;
}
function getGlobalConstraintParameters(address _globalConstraint,address) external view returns(bytes32) {
GlobalConstraintRegister memory register = globalConstraintsRegisterPre[_globalConstraint];
if (register.isRegistered) {
return globalConstraintsPre[register.index].params;
}
register = globalConstraintsRegisterPost[_globalConstraint];
if (register.isRegistered) {
return globalConstraintsPost[register.index].params;
}
}
/**
* @dev globalConstraintsCount return the global constraint pre and post count
* @return uint globalConstraintsPre count.
* @return uint globalConstraintsPost count.
*/
function globalConstraintsCount(address _avatar)
external
isAvatarValid(_avatar)
view
returns(uint,uint)
{
return (globalConstraintsPre.length,globalConstraintsPost.length);
}
function isGlobalConstraintRegistered(address _globalConstraint,address _avatar)
external
isAvatarValid(_avatar)
view
returns(bool)
{
return (globalConstraintsRegisterPre[_globalConstraint].isRegistered || globalConstraintsRegisterPost[_globalConstraint].isRegistered);
}
/**
* @dev add or update Global Constraint
* @param _globalConstraint the address of the global constraint to be added.
* @param _params the constraint parameters hash.
* @return bool which represents a success
*/
function addGlobalConstraint(address _globalConstraint, bytes32 _params,address _avatar)
external
onlyGlobalConstraintsScheme
isAvatarValid(_avatar)
returns(bool)
{
GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when();
if ((when == GlobalConstraintInterface.CallPhase.Pre)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
if (!globalConstraintsRegisterPre[_globalConstraint].isRegistered) {
globalConstraintsPre.push(GlobalConstraint(_globalConstraint,_params));
globalConstraintsRegisterPre[_globalConstraint] = GlobalConstraintRegister(true,globalConstraintsPre.length-1);
}else {
globalConstraintsPre[globalConstraintsRegisterPre[_globalConstraint].index].params = _params;
}
}
if ((when == GlobalConstraintInterface.CallPhase.Post)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
if (!globalConstraintsRegisterPost[_globalConstraint].isRegistered) {
globalConstraintsPost.push(GlobalConstraint(_globalConstraint,_params));
globalConstraintsRegisterPost[_globalConstraint] = GlobalConstraintRegister(true,globalConstraintsPost.length-1);
}else {
globalConstraintsPost[globalConstraintsRegisterPost[_globalConstraint].index].params = _params;
}
}
emit AddGlobalConstraint(_globalConstraint, _params,when);
return true;
}
/**
* @dev remove Global Constraint
* @param _globalConstraint the address of the global constraint to be remove.
* @return bool which represents a success
*/
function removeGlobalConstraint (address _globalConstraint,address _avatar)
external
onlyGlobalConstraintsScheme
isAvatarValid(_avatar)
returns(bool)
{
GlobalConstraintRegister memory globalConstraintRegister;
GlobalConstraint memory globalConstraint;
GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when();
bool retVal = false;
if ((when == GlobalConstraintInterface.CallPhase.Pre)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint];
if (globalConstraintRegister.isRegistered) {
if (globalConstraintRegister.index < globalConstraintsPre.length-1) {
globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1];
globalConstraintsPre[globalConstraintRegister.index] = globalConstraint;
globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index;
}
globalConstraintsPre.length--;
delete globalConstraintsRegisterPre[_globalConstraint];
retVal = true;
}
}
if ((when == GlobalConstraintInterface.CallPhase.Post)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint];
if (globalConstraintRegister.isRegistered) {
if (globalConstraintRegister.index < globalConstraintsPost.length-1) {
globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1];
globalConstraintsPost[globalConstraintRegister.index] = globalConstraint;
globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index;
}
globalConstraintsPost.length--;
delete globalConstraintsRegisterPost[_globalConstraint];
retVal = true;
}
}
if (retVal) {
emit RemoveGlobalConstraint(_globalConstraint,globalConstraintRegister.index,when == GlobalConstraintInterface.CallPhase.Pre);
}
return retVal;
}
/**
* @dev upgrade the Controller
* The function will trigger an event 'UpgradeController'.
* @param _newController the address of the new controller.
* @return bool which represents a success
*/
function upgradeController(address _newController,address _avatar)
external
onlyUpgradingScheme
isAvatarValid(_avatar)
returns(bool)
{
require(newController == address(0)); // so the upgrade could be done once for a contract.
require(_newController != address(0));
newController = _newController;
avatar.transferOwnership(_newController);
require(avatar.owner()==_newController);
if (nativeToken.owner() == address(this)) {
nativeToken.transferOwnership(_newController);
require(nativeToken.owner()==_newController);
}
if (nativeReputation.owner() == address(this)) {
nativeReputation.transferOwnership(_newController);
require(nativeReputation.owner()==_newController);
}
emit UpgradeController(this,newController);
return true;
}
/**
* @dev perform a generic call to an arbitrary contract
* @param _contract the contract's address to call
* @param _data ABI-encoded contract call to call `_contract` address.
* @param _avatar the controller's avatar address
* @return bytes32 - the return value of the called _contract's function.
*/
function genericCall(address _contract,bytes _data,address _avatar)
external
onlyGenericCallScheme
onlySubjectToConstraint("genericCall")
isAvatarValid(_avatar)
returns (bytes32)
{
emit GenericCall(_contract, _data);
avatar.genericCall(_contract, _data);
// solium-disable-next-line security/no-inline-assembly
assembly {
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
return(0, returndatasize)
}
}
/**
* @dev send some ether
* @param _amountInWei the amount of ether (in Wei) to send
* @param _to address of the beneficiary
* @return bool which represents a success
*/
function sendEther(uint _amountInWei, address _to,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("sendEther")
isAvatarValid(_avatar)
returns(bool)
{
emit SendEther(msg.sender, _amountInWei, _to);
return avatar.sendEther(_amountInWei, _to);
}
/**
* @dev send some amount of arbitrary ERC20 Tokens
* @param _externalToken the address of the Token Contract
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @return bool which represents a success
*/
function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenTransfer")
isAvatarValid(_avatar)
returns(bool)
{
emit ExternalTokenTransfer(msg.sender, _externalToken, _to, _value);
return avatar.externalTokenTransfer(_externalToken, _to, _value);
}
/**
* @dev transfer token "from" address "to" address
* One must to approve the amount of tokens which can be spend from the
* "from" account.This can be done using externalTokenApprove.
* @param _externalToken the address of the Token Contract
* @param _from address of the account to send from
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @return bool which represents a success
*/
function externalTokenTransferFrom(StandardToken _externalToken, address _from, address _to, uint _value,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenTransferFrom")
isAvatarValid(_avatar)
returns(bool)
{
emit ExternalTokenTransferFrom(msg.sender, _externalToken, _from, _to, _value);
return avatar.externalTokenTransferFrom(_externalToken, _from, _to, _value);
}
/**
* @dev increase approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _addedValue the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenIncreaseApproval")
isAvatarValid(_avatar)
returns(bool)
{
emit ExternalTokenIncreaseApproval(msg.sender,_externalToken,_spender,_addedValue);
return avatar.externalTokenIncreaseApproval(_externalToken, _spender, _addedValue);
}
/**
* @dev decrease approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _subtractedValue the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenDecreaseApproval")
isAvatarValid(_avatar)
returns(bool)
{
emit ExternalTokenDecreaseApproval(msg.sender,_externalToken,_spender,_subtractedValue);
return avatar.externalTokenDecreaseApproval(_externalToken, _spender, _subtractedValue);
}
/**
* @dev getNativeReputation
* @param _avatar the organization avatar.
* @return organization native reputation
*/
function getNativeReputation(address _avatar) external isAvatarValid(_avatar) view returns(address) {
return address(nativeReputation);
}
function _isSchemeRegistered(address _scheme,address _avatar) private isAvatarValid(_avatar) view returns(bool) {
return (schemes[_scheme].permissions&bytes4(1) != bytes4(0));
}
}
// File: contracts/universalSchemes/ExecutableInterface.sol
contract ExecutableInterface {
function execute(bytes32 _proposalId, address _avatar, int _param) public returns(bool);
}
// File: contracts/VotingMachines/IntVoteInterface.sol
interface IntVoteInterface {
//When implementing this interface please do not only override function and modifier,
//but also to keep the modifiers on the overridden functions.
modifier onlyProposalOwner(bytes32 _proposalId) {revert(); _;}
modifier votable(bytes32 _proposalId) {revert(); _;}
event NewProposal(bytes32 indexed _proposalId, address indexed _avatar, uint _numOfChoices, address _proposer, bytes32 _paramsHash);
event ExecuteProposal(bytes32 indexed _proposalId, address indexed _avatar, uint _decision, uint _totalReputation);
event VoteProposal(bytes32 indexed _proposalId, address indexed _avatar, address indexed _voter, uint _vote, uint _reputation);
event CancelProposal(bytes32 indexed _proposalId, address indexed _avatar );
event CancelVoting(bytes32 indexed _proposalId, address indexed _avatar, address indexed _voter);
/**
* @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being
* generated by calculating keccak256 of a incremented counter.
* @param _numOfChoices number of voting choices
* @param _proposalParameters defines the parameters of the voting machine used for this proposal
* @param _avatar an address to be sent as the payload to the _executable contract.
* @param _executable This contract will be executed when vote is over.
* @param _proposer address
* @return proposal's id.
*/
function propose(
uint _numOfChoices,
bytes32 _proposalParameters,
address _avatar,
ExecutableInterface _executable,
address _proposer
) external returns(bytes32);
// Only owned proposals and only the owner:
function cancelProposal(bytes32 _proposalId) external returns(bool);
// Only owned proposals and only the owner:
function ownerVote(bytes32 _proposalId, uint _vote, address _voter) external returns(bool);
function vote(bytes32 _proposalId, uint _vote) external returns(bool);
function voteWithSpecifiedAmounts(
bytes32 _proposalId,
uint _vote,
uint _rep,
uint _token) external returns(bool);
function cancelVote(bytes32 _proposalId) external;
//@dev execute check if the proposal has been decided, and if so, execute the proposal
//@param _proposalId the id of the proposal
//@return bool true - the proposal has been executed
// false - otherwise.
function execute(bytes32 _proposalId) external returns(bool);
function getNumberOfChoices(bytes32 _proposalId) external view returns(uint);
function isVotable(bytes32 _proposalId) external view returns(bool);
/**
* @dev voteStatus returns the reputation voted for a proposal for a specific voting choice.
* @param _proposalId the ID of the proposal
* @param _choice the index in the
* @return voted reputation for the given choice
*/
function voteStatus(bytes32 _proposalId,uint _choice) external view returns(uint);
/**
* @dev isAbstainAllow returns if the voting machine allow abstain (0)
* @return bool true or false
*/
function isAbstainAllow() external pure returns(bool);
/**
* @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine.
* @return min - minimum number of choices
max - maximum number of choices
*/
function getAllowedRangeOfChoices() external pure returns(uint min,uint max);
}
// File: contracts/universalSchemes/UniversalSchemeInterface.sol
contract UniversalSchemeInterface {
function updateParameters(bytes32 _hashedParameters) public;
function getParametersFromController(Avatar _avatar) internal view returns(bytes32);
}
// File: contracts/universalSchemes/UniversalScheme.sol
contract UniversalScheme is Ownable, UniversalSchemeInterface {
bytes32 public hashedParameters; // For other parameters.
function updateParameters(
bytes32 _hashedParameters
)
public
onlyOwner
{
hashedParameters = _hashedParameters;
}
/**
* @dev get the parameters for the current scheme from the controller
*/
function getParametersFromController(Avatar _avatar) internal view returns(bytes32) {
return ControllerInterface(_avatar.owner()).getSchemeParameters(this,address(_avatar));
}
}
// File: contracts/libs/RealMath.sol
/**
* RealMath: fixed-point math library, based on fractional and integer parts.
* Using int256 as real216x40, which isn't in Solidity yet.
* 40 fractional bits gets us down to 1E-12 precision, while still letting us
* go up to galaxy scale counting in meters.
* Internally uses the wider int256 for some math.
*
* Note that for addition, subtraction, and mod (%), you should just use the
* built-in Solidity operators. Functions for these operations are not provided.
*
* Note that the fancy functions like sqrt, atan2, etc. aren't as accurate as
* they should be. They are (hopefully) Good Enough for doing orbital mechanics
* on block timescales in a game context, but they may not be good enough for
* other applications.
*/
library RealMath {
/**
* How many total bits are there?
*/
int256 constant REAL_BITS = 256;
/**
* How many fractional bits are there?
*/
int256 constant REAL_FBITS = 40;
/**
* How many integer bits are there?
*/
int256 constant REAL_IBITS = REAL_BITS - REAL_FBITS;
/**
* What's the first non-fractional bit
*/
int256 constant REAL_ONE = int256(1) << REAL_FBITS;
/**
* What's the last fractional bit?
*/
int256 constant REAL_HALF = REAL_ONE >> 1;
/**
* What's two? Two is pretty useful.
*/
int256 constant REAL_TWO = REAL_ONE << 1;
/**
* And our logarithms are based on ln(2).
*/
int256 constant REAL_LN_TWO = 762123384786;
/**
* It is also useful to have Pi around.
*/
int256 constant REAL_PI = 3454217652358;
/**
* And half Pi, to save on divides.
* TODO: That might not be how the compiler handles constants.
*/
int256 constant REAL_HALF_PI = 1727108826179;
/**
* And two pi, which happens to be odd in its most accurate representation.
*/
int256 constant REAL_TWO_PI = 6908435304715;
/**
* What's the sign bit?
*/
int256 constant SIGN_MASK = int256(1) << 255;
/**
* Convert an integer to a real. Preserves sign.
*/
function toReal(int216 ipart) internal pure returns (int256) {
return int256(ipart) * REAL_ONE;
}
/**
* Convert a real to an integer. Preserves sign.
*/
function fromReal(int256 realValue) internal pure returns (int216) {
return int216(realValue / REAL_ONE);
}
/**
* Round a real to the nearest integral real value.
*/
function round(int256 realValue) internal pure returns (int256) {
// First, truncate.
int216 ipart = fromReal(realValue);
if ((fractionalBits(realValue) & (uint40(1) << (REAL_FBITS - 1))) > 0) {
// High fractional bit is set. Round up.
if (realValue < int256(0)) {
// Rounding up for a negative number is rounding down.
ipart -= 1;
} else {
ipart += 1;
}
}
return toReal(ipart);
}
/**
* Get the absolute value of a real. Just the same as abs on a normal int256.
*/
function abs(int256 realValue) internal pure returns (int256) {
if (realValue > 0) {
return realValue;
} else {
return -realValue;
}
}
/**
* Returns the fractional bits of a real. Ignores the sign of the real.
*/
function fractionalBits(int256 realValue) internal pure returns (uint40) {
return uint40(abs(realValue) % REAL_ONE);
}
/**
* Get the fractional part of a real, as a real. Ignores sign (so fpart(-0.5) is 0.5).
*/
function fpart(int256 realValue) internal pure returns (int256) {
// This gets the fractional part but strips the sign
return abs(realValue) % REAL_ONE;
}
/**
* Get the fractional part of a real, as a real. Respects sign (so fpartSigned(-0.5) is -0.5).
*/
function fpartSigned(int256 realValue) internal pure returns (int256) {
// This gets the fractional part but strips the sign
int256 fractional = fpart(realValue);
if (realValue < 0) {
// Add the negative sign back in.
return -fractional;
} else {
return fractional;
}
}
/**
* Get the integer part of a fixed point value.
*/
function ipart(int256 realValue) internal pure returns (int256) {
// Subtract out the fractional part to get the real part.
return realValue - fpartSigned(realValue);
}
/**
* Multiply one real by another. Truncates overflows.
*/
function mul(int256 realA, int256 realB) internal pure returns (int256) {
// When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format.
// So we just have to clip off the extra REAL_FBITS fractional bits.
return int256((int256(realA) * int256(realB)) >> REAL_FBITS);
}
/**
* Divide one real by another real. Truncates overflows.
*/
function div(int256 realNumerator, int256 realDenominator) internal pure returns (int256) {
// We use the reverse of the multiplication trick: convert numerator from
// x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point.
return int256((int256(realNumerator) * REAL_ONE) / int256(realDenominator));
}
/**
* Create a real from a rational fraction.
*/
function fraction(int216 numerator, int216 denominator) internal pure returns (int256) {
return div(toReal(numerator), toReal(denominator));
}
// Now we have some fancy math things (like pow and trig stuff). This isn't
// in the RealMath that was deployed with the original Macroverse
// deployment, so it needs to be linked into your contract statically.
/**
* Raise a number to a positive integer power in O(log power) time.
* See <https://stackoverflow.com/a/101613>
*/
function ipow(int256 realBase, int216 exponent) internal pure returns (int256) {
if (exponent < 0) {
// Negative powers are not allowed here.
revert();
}
int256 tempRealBase = realBase;
int256 tempExponent = exponent;
// Start with the 0th power
int256 realResult = REAL_ONE;
while (tempExponent != 0) {
// While there are still bits set
if ((tempExponent & 0x1) == 0x1) {
// If the low bit is set, multiply in the (many-times-squared) base
realResult = mul(realResult, tempRealBase);
}
// Shift off the low bit
tempExponent = tempExponent >> 1;
// Do the squaring
tempRealBase = mul(tempRealBase, tempRealBase);
}
// Return the final result.
return realResult;
}
/**
* Zero all but the highest set bit of a number.
* See <https://stackoverflow.com/a/53184>
*/
function hibit(uint256 _val) internal pure returns (uint256) {
// Set all the bits below the highest set bit
uint256 val = _val;
val |= (val >> 1);
val |= (val >> 2);
val |= (val >> 4);
val |= (val >> 8);
val |= (val >> 16);
val |= (val >> 32);
val |= (val >> 64);
val |= (val >> 128);
return val ^ (val >> 1);
}
/**
* Given a number with one bit set, finds the index of that bit.
*/
function findbit(uint256 val) internal pure returns (uint8 index) {
index = 0;
// We and the value with alternating bit patters of various pitches to find it.
if (val & 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA != 0) {
// Picth 1
index |= 1;
}
if (val & 0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC != 0) {
// Pitch 2
index |= 2;
}
if (val & 0xF0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0 != 0) {
// Pitch 4
index |= 4;
}
if (val & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00 != 0) {
// Pitch 8
index |= 8;
}
if (val & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000 != 0) {
// Pitch 16
index |= 16;
}
if (val & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000 != 0) {
// Pitch 32
index |= 32;
}
if (val & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000 != 0) {
// Pitch 64
index |= 64;
}
if (val & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000 != 0) {
// Pitch 128
index |= 128;
}
}
/**
* Shift realArg left or right until it is between 1 and 2. Return the
* rescaled value, and the number of bits of right shift applied. Shift may be negative.
*
* Expresses realArg as realScaled * 2^shift, setting shift to put realArg between [1 and 2).
*
* Rejects 0 or negative arguments.
*/
function rescale(int256 realArg) internal pure returns (int256 realScaled, int216 shift) {
if (realArg <= 0) {
// Not in domain!
revert();
}
// Find the high bit
int216 highBit = findbit(hibit(uint256(realArg)));
// We'll shift so the high bit is the lowest non-fractional bit.
shift = highBit - int216(REAL_FBITS);
if (shift < 0) {
// Shift left
realScaled = realArg << -shift;
} else if (shift >= 0) {
// Shift right
realScaled = realArg >> shift;
}
}
/**
* Calculate the natural log of a number. Rescales the input value and uses
* the algorithm outlined at <https://math.stackexchange.com/a/977836> and
* the ipow implementation.
*
* Lets you artificially limit the number of iterations.
*
* Note that it is potentially possible to get an un-converged value; lack
* of convergence does not throw.
*/
function lnLimited(int256 realArg, int maxIterations) internal pure returns (int256) {
if (realArg <= 0) {
// Outside of acceptable domain
revert();
}
if (realArg == REAL_ONE) {
// Handle this case specially because people will want exactly 0 and
// not ~2^-39 ish.
return 0;
}
// We know it's positive, so rescale it to be between [1 and 2)
int256 realRescaled;
int216 shift;
(realRescaled, shift) = rescale(realArg);
// Compute the argument to iterate on
int256 realSeriesArg = div(realRescaled - REAL_ONE, realRescaled + REAL_ONE);
// We will accumulate the result here
int256 realSeriesResult = 0;
for (int216 n = 0; n < maxIterations; n++) {
// Compute term n of the series
int256 realTerm = div(ipow(realSeriesArg, 2 * n + 1), toReal(2 * n + 1));
// And add it in
realSeriesResult += realTerm;
if (realTerm == 0) {
// We must have converged. Next term is too small to represent.
break;
}
// If we somehow never converge I guess we will run out of gas
}
// Double it to account for the factor of 2 outside the sum
realSeriesResult = mul(realSeriesResult, REAL_TWO);
// Now compute and return the overall result
return mul(toReal(shift), REAL_LN_TWO) + realSeriesResult;
}
/**
* Calculate a natural logarithm with a sensible maximum iteration count to
* wait until convergence. Note that it is potentially possible to get an
* un-converged value; lack of convergence does not throw.
*/
function ln(int256 realArg) internal pure returns (int256) {
return lnLimited(realArg, 100);
}
/**
* Calculate e^x. Uses the series given at
* <http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html>.
*
* Lets you artificially limit the number of iterations.
*
* Note that it is potentially possible to get an un-converged value; lack
* of convergence does not throw.
*/
function expLimited(int256 realArg, int maxIterations) internal pure returns (int256) {
// We will accumulate the result here
int256 realResult = 0;
// We use this to save work computing terms
int256 realTerm = REAL_ONE;
for (int216 n = 0; n < maxIterations; n++) {
// Add in the term
realResult += realTerm;
// Compute the next term
realTerm = mul(realTerm, div(realArg, toReal(n + 1)));
if (realTerm == 0) {
// We must have converged. Next term is too small to represent.
break;
}
// If we somehow never converge I guess we will run out of gas
}
// Return the result
return realResult;
}
/**
* Calculate e^x with a sensible maximum iteration count to wait until
* convergence. Note that it is potentially possible to get an un-converged
* value; lack of convergence does not throw.
*/
function exp(int256 realArg) internal pure returns (int256) {
return expLimited(realArg, 100);
}
/**
* Raise any number to any power, except for negative bases to fractional powers.
*/
function pow(int256 realBase, int256 realExponent) internal pure returns (int256) {
if (realExponent == 0) {
// Anything to the 0 is 1
return REAL_ONE;
}
if (realBase == 0) {
if (realExponent < 0) {
// Outside of domain!
revert();
}
// Otherwise it's 0
return 0;
}
if (fpart(realExponent) == 0) {
// Anything (even a negative base) is super easy to do to an integer power.
if (realExponent > 0) {
// Positive integer power is easy
return ipow(realBase, fromReal(realExponent));
} else {
// Negative integer power is harder
return div(REAL_ONE, ipow(realBase, fromReal(-realExponent)));
}
}
if (realBase < 0) {
// It's a negative base to a non-integer power.
// In general pow(-x^y) is undefined, unless y is an int or some
// weird rational-number-based relationship holds.
revert();
}
// If it's not a special case, actually do it.
return exp(mul(realExponent, ln(realBase)));
}
/**
* Compute the square root of a number.
*/
function sqrt(int256 realArg) internal pure returns (int256) {
return pow(realArg, REAL_HALF);
}
/**
* Compute the sin of a number to a certain number of Taylor series terms.
*/
function sinLimited(int256 _realArg, int216 maxIterations) internal pure returns (int256) {
// First bring the number into 0 to 2 pi
// TODO: This will introduce an error for very large numbers, because the error in our Pi will compound.
// But for actual reasonable angle values we should be fine.
int256 realArg = _realArg;
realArg = realArg % REAL_TWO_PI;
int256 accumulator = REAL_ONE;
// We sum from large to small iteration so that we can have higher powers in later terms
for (int216 iteration = maxIterations - 1; iteration >= 0; iteration--) {
accumulator = REAL_ONE - mul(div(mul(realArg, realArg), toReal((2 * iteration + 2) * (2 * iteration + 3))), accumulator);
// We can't stop early; we need to make it to the first term.
}
return mul(realArg, accumulator);
}
/**
* Calculate sin(x) with a sensible maximum iteration count to wait until
* convergence.
*/
function sin(int256 realArg) internal pure returns (int256) {
return sinLimited(realArg, 15);
}
/**
* Calculate cos(x).
*/
function cos(int256 realArg) internal pure returns (int256) {
return sin(realArg + REAL_HALF_PI);
}
/**
* Calculate tan(x). May overflow for large results. May throw if tan(x)
* would be infinite, or return an approximation, or overflow.
*/
function tan(int256 realArg) internal pure returns (int256) {
return div(sin(realArg), cos(realArg));
}
}
// File: openzeppelin-solidity/contracts/ECRecovery.sol
/**
* @title Eliptic curve signature operations
*
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
*
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*
*/
library ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* @dev and hash the result
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(
"\x19Ethereum Signed Message:\n32",
hash
);
}
}
// File: contracts/libs/OrderStatisticTree.sol
library OrderStatisticTree {
struct Node {
mapping (bool => uint) children; // a mapping of left(false) child and right(true) child nodes
uint parent; // parent node
bool side; // side of the node on the tree (left or right)
uint height; //Height of this node
uint count; //Number of tree nodes below this node (including this one)
uint dupes; //Number of duplicates values for this node
}
struct Tree {
// a mapping between node value(uint) to Node
// the tree's root is always at node 0 ,which points to the "real" tree
// as its right child.this is done to eliminate the need to update the tree
// root in the case of rotation.(saving gas).
mapping(uint => Node) nodes;
}
/**
* @dev rank - find the rank of a value in the tree,
* i.e. its index in the sorted list of elements of the tree
* @param _tree the tree
* @param _value the input value to find its rank.
* @return smaller - the number of elements in the tree which their value is
* less than the input value.
*/
function rank(Tree storage _tree,uint _value) internal view returns (uint smaller) {
if (_value != 0) {
smaller = _tree.nodes[0].dupes;
uint cur = _tree.nodes[0].children[true];
Node storage currentNode = _tree.nodes[cur];
while (true) {
if (cur <= _value) {
if (cur<_value) {
smaller = smaller + 1+currentNode.dupes;
}
uint leftChild = currentNode.children[false];
if (leftChild!=0) {
smaller = smaller + _tree.nodes[leftChild].count;
}
}
if (cur == _value) {
break;
}
cur = currentNode.children[cur<_value];
if (cur == 0) {
break;
}
currentNode = _tree.nodes[cur];
}
}
}
function count(Tree storage _tree) internal view returns (uint) {
Node storage root = _tree.nodes[0];
Node memory child = _tree.nodes[root.children[true]];
return root.dupes+child.count;
}
function updateCount(Tree storage _tree,uint _value) private {
Node storage n = _tree.nodes[_value];
n.count = 1+_tree.nodes[n.children[false]].count+_tree.nodes[n.children[true]].count+n.dupes;
}
function updateCounts(Tree storage _tree,uint _value) private {
uint parent = _tree.nodes[_value].parent;
while (parent!=0) {
updateCount(_tree,parent);
parent = _tree.nodes[parent].parent;
}
}
function updateHeight(Tree storage _tree,uint _value) private {
Node storage n = _tree.nodes[_value];
uint heightLeft = _tree.nodes[n.children[false]].height;
uint heightRight = _tree.nodes[n.children[true]].height;
if (heightLeft > heightRight)
n.height = heightLeft+1;
else
n.height = heightRight+1;
}
function balanceFactor(Tree storage _tree,uint _value) private view returns (int bf) {
Node storage n = _tree.nodes[_value];
return int(_tree.nodes[n.children[false]].height)-int(_tree.nodes[n.children[true]].height);
}
function rotate(Tree storage _tree,uint _value,bool dir) private {
bool otherDir = !dir;
Node storage n = _tree.nodes[_value];
bool side = n.side;
uint parent = n.parent;
uint valueNew = n.children[otherDir];
Node storage nNew = _tree.nodes[valueNew];
uint orphan = nNew.children[dir];
Node storage p = _tree.nodes[parent];
Node storage o = _tree.nodes[orphan];
p.children[side] = valueNew;
nNew.side = side;
nNew.parent = parent;
nNew.children[dir] = _value;
n.parent = valueNew;
n.side = dir;
n.children[otherDir] = orphan;
o.parent = _value;
o.side = otherDir;
updateHeight(_tree,_value);
updateHeight(_tree,valueNew);
updateCount(_tree,_value);
updateCount(_tree,valueNew);
}
function rebalanceInsert(Tree storage _tree,uint _nValue) private {
updateHeight(_tree,_nValue);
Node storage n = _tree.nodes[_nValue];
uint pValue = n.parent;
if (pValue!=0) {
int pBf = balanceFactor(_tree,pValue);
bool side = n.side;
int sign;
if (side)
sign = -1;
else
sign = 1;
if (pBf == sign*2) {
if (balanceFactor(_tree,_nValue) == (-1 * sign)) {
rotate(_tree,_nValue,side);
}
rotate(_tree,pValue,!side);
} else if (pBf != 0) {
rebalanceInsert(_tree,pValue);
}
}
}
function rebalanceDelete(Tree storage _tree,uint _pValue,bool side) private {
if (_pValue!=0) {
updateHeight(_tree,_pValue);
int pBf = balanceFactor(_tree,_pValue);
int sign;
if (side)
sign = 1;
else
sign = -1;
int bf = balanceFactor(_tree,_pValue);
if (bf==(2*sign)) {
Node storage p = _tree.nodes[_pValue];
uint sValue = p.children[!side];
int sBf = balanceFactor(_tree,sValue);
if (sBf == (-1 * sign)) {
rotate(_tree,sValue,!side);
}
rotate(_tree,_pValue,side);
if (sBf!=0) {
p = _tree.nodes[_pValue];
rebalanceDelete(_tree,p.parent,p.side);
}
} else if (pBf != sign) {
p = _tree.nodes[_pValue];
rebalanceDelete(_tree,p.parent,p.side);
}
}
}
function fixParents(Tree storage _tree,uint parent,bool side) private {
if (parent!=0) {
updateCount(_tree,parent);
updateCounts(_tree,parent);
rebalanceDelete(_tree,parent,side);
}
}
function insertHelper(Tree storage _tree,uint _pValue,bool _side,uint _value) private {
Node storage root = _tree.nodes[_pValue];
uint cValue = root.children[_side];
if (cValue==0) {
root.children[_side] = _value;
Node storage child = _tree.nodes[_value];
child.parent = _pValue;
child.side = _side;
child.height = 1;
child.count = 1;
updateCounts(_tree,_value);
rebalanceInsert(_tree,_value);
} else if (cValue==_value) {
_tree.nodes[cValue].dupes++;
updateCount(_tree,_value);
updateCounts(_tree,_value);
} else {
insertHelper(_tree,cValue,(_value >= cValue),_value);
}
}
function insert(Tree storage _tree,uint _value) internal {
if (_value==0) {
_tree.nodes[_value].dupes++;
} else {
insertHelper(_tree,0,true,_value);
}
}
function rightmostLeaf(Tree storage _tree,uint _value) private view returns (uint leaf) {
uint child = _tree.nodes[_value].children[true];
if (child!=0) {
return rightmostLeaf(_tree,child);
} else {
return _value;
}
}
function zeroOut(Tree storage _tree,uint _value) private {
Node storage n = _tree.nodes[_value];
n.parent = 0;
n.side = false;
n.children[false] = 0;
n.children[true] = 0;
n.count = 0;
n.height = 0;
n.dupes = 0;
}
function removeBranch(Tree storage _tree,uint _value,uint _left) private {
uint ipn = rightmostLeaf(_tree,_left);
Node storage i = _tree.nodes[ipn];
uint dupes = i.dupes;
removeHelper(_tree,ipn);
Node storage n = _tree.nodes[_value];
uint parent = n.parent;
Node storage p = _tree.nodes[parent];
uint height = n.height;
bool side = n.side;
uint ncount = n.count;
uint right = n.children[true];
uint left = n.children[false];
p.children[side] = ipn;
i.parent = parent;
i.side = side;
i.count = ncount+dupes-n.dupes;
i.height = height;
i.dupes = dupes;
if (left!=0) {
i.children[false] = left;
_tree.nodes[left].parent = ipn;
}
if (right!=0) {
i.children[true] = right;
_tree.nodes[right].parent = ipn;
}
zeroOut(_tree,_value);
updateCounts(_tree,ipn);
}
function removeHelper(Tree storage _tree,uint _value) private {
Node storage n = _tree.nodes[_value];
uint parent = n.parent;
bool side = n.side;
Node storage p = _tree.nodes[parent];
uint left = n.children[false];
uint right = n.children[true];
if ((left == 0) && (right == 0)) {
p.children[side] = 0;
zeroOut(_tree,_value);
fixParents(_tree,parent,side);
} else if ((left != 0) && (right != 0)) {
removeBranch(_tree,_value,left);
} else {
uint child = left+right;
Node storage c = _tree.nodes[child];
p.children[side] = child;
c.parent = parent;
c.side = side;
zeroOut(_tree,_value);
fixParents(_tree,parent,side);
}
}
function remove(Tree storage _tree,uint _value) internal {
Node storage n = _tree.nodes[_value];
if (_value==0) {
if (n.dupes==0) {
return;
}
} else {
if (n.count==0) {
return;
}
}
if (n.dupes>0) {
n.dupes--;
if (_value!=0) {
n.count--;
}
fixParents(_tree,n.parent,n.side);
} else {
removeHelper(_tree,_value);
}
}
}
// File: contracts/VotingMachines/GenesisProtocol.sol
/**
* @title GenesisProtocol implementation -an organization's voting machine scheme.
*/
contract GenesisProtocol is IntVoteInterface,UniversalScheme {
using SafeMath for uint;
using RealMath for int216;
using RealMath for int256;
using ECRecovery for bytes32;
using OrderStatisticTree for OrderStatisticTree.Tree;
enum ProposalState { None ,Closed, Executed, PreBoosted,Boosted,QuietEndingPeriod }
enum ExecutionState { None, PreBoostedTimeOut, PreBoostedBarCrossed, BoostedTimeOut,BoostedBarCrossed }
//Organization's parameters
struct Parameters {
uint preBoostedVoteRequiredPercentage; // the absolute vote percentages bar.
uint preBoostedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode.
uint boostedVotePeriodLimit; //the time limit for a proposal to be in an relative voting mode.
uint thresholdConstA;//constant A for threshold calculation . threshold =A * (e ** (numberOfBoostedProposals/B))
uint thresholdConstB;//constant B for threshold calculation . threshold =A * (e ** (numberOfBoostedProposals/B))
uint minimumStakingFee; //minimum staking fee allowed.
uint quietEndingPeriod; //quite ending period
uint proposingRepRewardConstA;//constant A for calculate proposer reward. proposerReward =(A*(RTotal) +B*(R+ - R-))/1000
uint proposingRepRewardConstB;//constant B for calculate proposing reward.proposerReward =(A*(RTotal) +B*(R+ - R-))/1000
uint stakerFeeRatioForVoters; // The “ratio of stake” to be paid to voters.
// All stakers pay a portion of their stake to all voters, stakerFeeRatioForVoters * (s+ + s-).
//All voters (pre and during boosting period) divide this portion in proportion to their reputation.
uint votersReputationLossRatio;//Unsuccessful pre booster voters lose votersReputationLossRatio% of their reputation.
uint votersGainRepRatioFromLostRep; //the percentages of the lost reputation which is divided by the successful pre boosted voters,
//in proportion to their reputation.
//The rest (100-votersGainRepRatioFromLostRep)% of lost reputation is divided between the successful wagers,
//in proportion to their stake.
uint daoBountyConst;//The DAO adds up a bounty for successful staker.
//The bounty formula is: s * daoBountyConst, where s+ is the wager staked for the proposal,
//and daoBountyConst is a constant factor that is configurable and changeable by the DAO given.
// daoBountyConst should be greater than stakerFeeRatioForVoters and less than 2 * stakerFeeRatioForVoters.
uint daoBountyLimit;//The daoBounty cannot be greater than daoBountyLimit.
}
struct Voter {
uint vote; // YES(1) ,NO(2)
uint reputation; // amount of voter's reputation
bool preBoosted;
}
struct Staker {
uint vote; // YES(1) ,NO(2)
uint amount; // amount of staker's stake
uint amountForBounty; // amount of staker's stake which will be use for bounty calculation
}
struct Proposal {
address avatar; // the organization's avatar the proposal is target to.
uint numOfChoices;
ExecutableInterface executable; // will be executed if the proposal will pass
uint votersStakes;
uint submittedTime;
uint boostedPhaseTime; //the time the proposal shift to relative mode.
ProposalState state;
uint winningVote; //the winning vote.
address proposer;
uint currentBoostedVotePeriodLimit;
bytes32 paramsHash;
uint daoBountyRemain;
uint[2] totalStakes;// totalStakes[0] - (amount staked minus fee) - Total number of tokens staked which can be redeemable by stakers.
// totalStakes[1] - (amount staked) - Total number of redeemable tokens.
// vote reputation
mapping(uint => uint ) votes;
// vote reputation
mapping(uint => uint ) preBoostedVotes;
// address voter
mapping(address => Voter ) voters;
// vote stakes
mapping(uint => uint ) stakes;
// address staker
mapping(address => Staker ) stakers;
}
event GPExecuteProposal(bytes32 indexed _proposalId, ExecutionState _executionState);
event Stake(bytes32 indexed _proposalId, address indexed _avatar, address indexed _staker,uint _vote,uint _amount);
event Redeem(bytes32 indexed _proposalId, address indexed _avatar, address indexed _beneficiary,uint _amount);
event RedeemDaoBounty(bytes32 indexed _proposalId, address indexed _avatar, address indexed _beneficiary,uint _amount);
event RedeemReputation(bytes32 indexed _proposalId, address indexed _avatar, address indexed _beneficiary,uint _amount);
mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters
mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself.
mapping(bytes=>bool) stakeSignatures; //stake signatures
uint constant public NUM_OF_CHOICES = 2;
uint constant public NO = 2;
uint constant public YES = 1;
uint public proposalsCnt; // Total number of proposals
mapping(address=>uint) orgBoostedProposalsCnt;
StandardToken public stakingToken;
mapping(address=>OrderStatisticTree.Tree) proposalsExpiredTimes; //proposals expired times
/**
* @dev Constructor
*/
constructor(StandardToken _stakingToken) public
{
stakingToken = _stakingToken;
}
/**
* @dev Check that the proposal is votable (open and not executed yet)
*/
modifier votable(bytes32 _proposalId) {
require(_isVotable(_proposalId));
_;
}
/**
* @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being
* generated by calculating keccak256 of a incremented counter.
* @param _numOfChoices number of voting choices
* @param _avatar an address to be sent as the payload to the _executable contract.
* @param _executable This contract will be executed when vote is over.
* @param _proposer address
* @return proposal's id.
*/
function propose(uint _numOfChoices, bytes32 , address _avatar, ExecutableInterface _executable,address _proposer)
external
returns(bytes32)
{
// Check valid params and number of choices:
require(_numOfChoices == NUM_OF_CHOICES);
require(ExecutableInterface(_executable) != address(0));
//Check parameters existence.
bytes32 paramsHash = getParametersFromController(Avatar(_avatar));
require(parameters[paramsHash].preBoostedVoteRequiredPercentage > 0);
// Generate a unique ID:
bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));
proposalsCnt++;
// Open proposal:
Proposal memory proposal;
proposal.numOfChoices = _numOfChoices;
proposal.avatar = _avatar;
proposal.executable = _executable;
proposal.state = ProposalState.PreBoosted;
// solium-disable-next-line security/no-block-members
proposal.submittedTime = now;
proposal.currentBoostedVotePeriodLimit = parameters[paramsHash].boostedVotePeriodLimit;
proposal.proposer = _proposer;
proposal.winningVote = NO;
proposal.paramsHash = paramsHash;
proposals[proposalId] = proposal;
emit NewProposal(proposalId, _avatar, _numOfChoices, _proposer, paramsHash);
return proposalId;
}
/**
* @dev Cancel a proposal, only the owner can call this function and only if allowOwner flag is true.
*/
function cancelProposal(bytes32 ) external returns(bool) {
//This is not allowed.
return false;
}
/**
* @dev staking function
* @param _proposalId id of the proposal
* @param _vote NO(2) or YES(1).
* @param _amount the betting amount
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function stake(bytes32 _proposalId, uint _vote, uint _amount) external returns(bool) {
return _stake(_proposalId,_vote,_amount,msg.sender);
}
// Digest describing the data the user signs according EIP 712.
// Needs to match what is passed to Metamask.
bytes32 public constant DELEGATION_HASH_EIP712 =
keccak256(abi.encodePacked("address GenesisProtocolAddress","bytes32 ProposalId", "uint Vote","uint AmountToStake","uint Nonce"));
// web3.eth.sign prefix
string public constant ETH_SIGN_PREFIX= "\x19Ethereum Signed Message:\n32";
/**
* @dev stakeWithSignature function
* @param _proposalId id of the proposal
* @param _vote NO(2) or YES(1).
* @param _amount the betting amount
* @param _nonce nonce value ,it is part of the signature to ensure that
a signature can be received only once.
* @param _signatureType signature type
1 - for web3.eth.sign
2 - for eth_signTypedData according to EIP #712.
* @param _signature - signed data by the staker
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function stakeWithSignature(
bytes32 _proposalId,
uint _vote,
uint _amount,
uint _nonce,
uint _signatureType,
bytes _signature
)
external
returns(bool)
{
require(stakeSignatures[_signature] == false);
// Recreate the digest the user signed
bytes32 delegationDigest;
if (_signatureType == 2) {
delegationDigest = keccak256(
abi.encodePacked(
DELEGATION_HASH_EIP712, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)))
);
} else {
delegationDigest = keccak256(
abi.encodePacked(
ETH_SIGN_PREFIX, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)))
);
}
address staker = delegationDigest.recover(_signature);
//a garbage staker address due to wrong signature will revert due to lack of approval and funds.
require(staker!=address(0));
stakeSignatures[_signature] = true;
return _stake(_proposalId,_vote,_amount,staker);
}
/**
* @dev voting function
* @param _proposalId id of the proposal
* @param _vote NO(2) or YES(1).
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function vote(bytes32 _proposalId, uint _vote) external votable(_proposalId) returns(bool) {
return internalVote(_proposalId, msg.sender, _vote, 0);
}
/**
* @dev voting function with owner functionality (can vote on behalf of someone else)
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function ownerVote(bytes32 , uint , address ) external returns(bool) {
//This is not allowed.
return false;
}
function voteWithSpecifiedAmounts(bytes32 _proposalId,uint _vote,uint _rep,uint) external votable(_proposalId) returns(bool) {
return internalVote(_proposalId,msg.sender,_vote,_rep);
}
/**
* @dev Cancel the vote of the msg.sender.
* cancel vote is not allow in genesisProtocol so this function doing nothing.
* This function is here in order to comply to the IntVoteInterface .
*/
function cancelVote(bytes32 _proposalId) external votable(_proposalId) {
//this is not allowed
return;
}
/**
* @dev getNumberOfChoices returns the number of choices possible in this proposal
* @param _proposalId the ID of the proposals
* @return uint that contains number of choices
*/
function getNumberOfChoices(bytes32 _proposalId) external view returns(uint) {
return proposals[_proposalId].numOfChoices;
}
/**
* @dev voteInfo returns the vote and the amount of reputation of the user committed to this proposal
* @param _proposalId the ID of the proposal
* @param _voter the address of the voter
* @return uint vote - the voters vote
* uint reputation - amount of reputation committed by _voter to _proposalId
*/
function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) {
Voter memory voter = proposals[_proposalId].voters[_voter];
return (voter.vote, voter.reputation);
}
/**
* @dev voteStatus returns the reputation voted for a proposal for a specific voting choice.
* @param _proposalId the ID of the proposal
* @param _choice the index in the
* @return voted reputation for the given choice
*/
function voteStatus(bytes32 _proposalId,uint _choice) external view returns(uint) {
return proposals[_proposalId].votes[_choice];
}
/**
* @dev isVotable check if the proposal is votable
* @param _proposalId the ID of the proposal
* @return bool true or false
*/
function isVotable(bytes32 _proposalId) external view returns(bool) {
return _isVotable(_proposalId);
}
/**
* @dev proposalStatus return the total votes and stakes for a given proposal
* @param _proposalId the ID of the proposal
* @return uint preBoostedVotes YES
* @return uint preBoostedVotes NO
* @return uint stakersStakes
* @return uint totalRedeemableStakes
* @return uint total stakes YES
* @return uint total stakes NO
*/
function proposalStatus(bytes32 _proposalId) external view returns(uint, uint, uint ,uint, uint ,uint) {
return (
proposals[_proposalId].preBoostedVotes[YES],
proposals[_proposalId].preBoostedVotes[NO],
proposals[_proposalId].totalStakes[0],
proposals[_proposalId].totalStakes[1],
proposals[_proposalId].stakes[YES],
proposals[_proposalId].stakes[NO]
);
}
/**
* @dev proposalAvatar return the avatar for a given proposal
* @param _proposalId the ID of the proposal
* @return uint total reputation supply
*/
function proposalAvatar(bytes32 _proposalId) external view returns(address) {
return (proposals[_proposalId].avatar);
}
/**
* @dev scoreThresholdParams return the score threshold params for a given
* organization.
* @param _avatar the organization's avatar
* @return uint thresholdConstA
* @return uint thresholdConstB
*/
function scoreThresholdParams(address _avatar) external view returns(uint,uint) {
bytes32 paramsHash = getParametersFromController(Avatar(_avatar));
Parameters memory params = parameters[paramsHash];
return (params.thresholdConstA,params.thresholdConstB);
}
/**
* @dev getStaker return the vote and stake amount for a given proposal and staker
* @param _proposalId the ID of the proposal
* @param _staker staker address
* @return uint vote
* @return uint amount
*/
function getStaker(bytes32 _proposalId,address _staker) external view returns(uint,uint) {
return (proposals[_proposalId].stakers[_staker].vote,proposals[_proposalId].stakers[_staker].amount);
}
/**
* @dev state return the state for a given proposal
* @param _proposalId the ID of the proposal
* @return ProposalState proposal state
*/
function state(bytes32 _proposalId) external view returns(ProposalState) {
return proposals[_proposalId].state;
}
/**
* @dev winningVote return the winningVote for a given proposal
* @param _proposalId the ID of the proposal
* @return uint winningVote
*/
function winningVote(bytes32 _proposalId) external view returns(uint) {
return proposals[_proposalId].winningVote;
}
/**
* @dev isAbstainAllow returns if the voting machine allow abstain (0)
* @return bool true or false
*/
function isAbstainAllow() external pure returns(bool) {
return false;
}
/**
* @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine.
* @return min - minimum number of choices
max - maximum number of choices
*/
function getAllowedRangeOfChoices() external pure returns(uint min,uint max) {
return (NUM_OF_CHOICES,NUM_OF_CHOICES);
}
/**
* @dev execute check if the proposal has been decided, and if so, execute the proposal
* @param _proposalId the id of the proposal
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function execute(bytes32 _proposalId) external votable(_proposalId) returns(bool) {
return _execute(_proposalId);
}
/**
* @dev redeem a reward for a successful stake, vote or proposing.
* The function use a beneficiary address as a parameter (and not msg.sender) to enable
* users to redeem on behalf of someone else.
* @param _proposalId the ID of the proposal
* @param _beneficiary - the beneficiary address
* @return rewards -
* rewards[0] - stakerTokenAmount
* rewards[1] - stakerReputationAmount
* rewards[2] - voterTokenAmount
* rewards[3] - voterReputationAmount
* rewards[4] - proposerReputationAmount
* @return reputation - redeem reputation
*/
function redeem(bytes32 _proposalId,address _beneficiary) public returns (uint[5] rewards) {
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed) || (proposal.state == ProposalState.Closed),"wrong proposal state");
Parameters memory params = parameters[proposal.paramsHash];
uint amount;
uint reputation;
uint lostReputation;
if (proposal.winningVote == YES) {
lostReputation = proposal.preBoostedVotes[NO];
} else {
lostReputation = proposal.preBoostedVotes[YES];
}
lostReputation = (lostReputation * params.votersReputationLossRatio)/100;
//as staker
Staker storage staker = proposal.stakers[_beneficiary];
if ((staker.amount>0) &&
(staker.vote == proposal.winningVote)) {
uint totalWinningStakes = proposal.stakes[proposal.winningVote];
if (totalWinningStakes != 0) {
rewards[0] = (staker.amount * proposal.totalStakes[0]) / totalWinningStakes;
}
if (proposal.state != ProposalState.Closed) {
rewards[1] = (staker.amount * ( lostReputation - ((lostReputation * params.votersGainRepRatioFromLostRep)/100)))/proposal.stakes[proposal.winningVote];
}
staker.amount = 0;
}
//as voter
Voter storage voter = proposal.voters[_beneficiary];
if ((voter.reputation != 0 ) && (voter.preBoosted)) {
uint preBoostedVotes = proposal.preBoostedVotes[YES] + proposal.preBoostedVotes[NO];
if (preBoostedVotes>0) {
rewards[2] = ((proposal.votersStakes * voter.reputation) / preBoostedVotes);
}
if (proposal.state == ProposalState.Closed) {
//give back reputation for the voter
rewards[3] = ((voter.reputation * params.votersReputationLossRatio)/100);
} else if (proposal.winningVote == voter.vote ) {
rewards[3] = (((voter.reputation * params.votersReputationLossRatio)/100) +
(((voter.reputation * lostReputation * params.votersGainRepRatioFromLostRep)/100)/preBoostedVotes));
}
voter.reputation = 0;
}
//as proposer
if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == YES)&&(proposal.proposer != address(0))) {
rewards[4] = (params.proposingRepRewardConstA.mul(proposal.votes[YES]+proposal.votes[NO]) + params.proposingRepRewardConstB.mul(proposal.votes[YES]-proposal.votes[NO]))/1000;
proposal.proposer = 0;
}
amount = rewards[0] + rewards[2];
reputation = rewards[1] + rewards[3] + rewards[4];
if (amount != 0) {
proposal.totalStakes[1] = proposal.totalStakes[1].sub(amount);
require(stakingToken.transfer(_beneficiary, amount));
emit Redeem(_proposalId,proposal.avatar,_beneficiary,amount);
}
if (reputation != 0 ) {
ControllerInterface(Avatar(proposal.avatar).owner()).mintReputation(reputation,_beneficiary,proposal.avatar);
emit RedeemReputation(_proposalId,proposal.avatar,_beneficiary,reputation);
}
}
/**
* @dev redeemDaoBounty a reward for a successful stake, vote or proposing.
* The function use a beneficiary address as a parameter (and not msg.sender) to enable
* users to redeem on behalf of someone else.
* @param _proposalId the ID of the proposal
* @param _beneficiary - the beneficiary address
* @return redeemedAmount - redeem token amount
* @return potentialAmount - potential redeem token amount(if there is enough tokens bounty at the avatar )
*/
function redeemDaoBounty(bytes32 _proposalId,address _beneficiary) public returns(uint redeemedAmount,uint potentialAmount) {
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed) || (proposal.state == ProposalState.Closed));
uint totalWinningStakes = proposal.stakes[proposal.winningVote];
if (
// solium-disable-next-line operator-whitespace
(proposal.stakers[_beneficiary].amountForBounty>0)&&
(proposal.stakers[_beneficiary].vote == proposal.winningVote)&&
(proposal.winningVote == YES)&&
(totalWinningStakes != 0))
{
//as staker
Parameters memory params = parameters[proposal.paramsHash];
uint beneficiaryLimit = (proposal.stakers[_beneficiary].amountForBounty.mul(params.daoBountyLimit)) / totalWinningStakes;
potentialAmount = (params.daoBountyConst.mul(proposal.stakers[_beneficiary].amountForBounty))/100;
if (potentialAmount > beneficiaryLimit) {
potentialAmount = beneficiaryLimit;
}
}
if ((potentialAmount != 0)&&(stakingToken.balanceOf(proposal.avatar) >= potentialAmount)) {
proposal.daoBountyRemain = proposal.daoBountyRemain.sub(potentialAmount);
require(ControllerInterface(Avatar(proposal.avatar).owner()).externalTokenTransfer(stakingToken,_beneficiary,potentialAmount,proposal.avatar));
proposal.stakers[_beneficiary].amountForBounty = 0;
redeemedAmount = potentialAmount;
emit RedeemDaoBounty(_proposalId,proposal.avatar,_beneficiary,redeemedAmount);
}
}
/**
* @dev shouldBoost check if a proposal should be shifted to boosted phase.
* @param _proposalId the ID of the proposal
* @return bool true or false.
*/
function shouldBoost(bytes32 _proposalId) public view returns(bool) {
Proposal memory proposal = proposals[_proposalId];
return (_score(_proposalId) >= threshold(proposal.paramsHash,proposal.avatar));
}
/**
* @dev score return the proposal score
* @param _proposalId the ID of the proposal
* @return uint proposal score.
*/
function score(bytes32 _proposalId) public view returns(int) {
return _score(_proposalId);
}
/**
* @dev getBoostedProposalsCount return the number of boosted proposal for an organization
* @param _avatar the organization avatar
* @return uint number of boosted proposals
*/
function getBoostedProposalsCount(address _avatar) public view returns(uint) {
uint expiredProposals;
if (proposalsExpiredTimes[_avatar].count() != 0) {
// solium-disable-next-line security/no-block-members
expiredProposals = proposalsExpiredTimes[_avatar].rank(now);
}
return orgBoostedProposalsCnt[_avatar].sub(expiredProposals);
}
/**
* @dev threshold return the organization's score threshold which required by
* a proposal to shift to boosted state.
* This threshold is dynamically set and it depend on the number of boosted proposal.
* @param _avatar the organization avatar
* @param _paramsHash the organization parameters hash
* @return int organization's score threshold.
*/
function threshold(bytes32 _paramsHash,address _avatar) public view returns(int) {
uint boostedProposals = getBoostedProposalsCount(_avatar);
int216 e = 2;
Parameters memory params = parameters[_paramsHash];
require(params.thresholdConstB > 0,"should be a valid parameter hash");
int256 power = int216(boostedProposals).toReal().div(int216(params.thresholdConstB).toReal());
if (power.fromReal() > 100 ) {
power = int216(100).toReal();
}
int256 res = int216(params.thresholdConstA).toReal().mul(e.toReal().pow(power));
return res.fromReal();
}
/**
* @dev hash the parameters, save them if necessary, and return the hash value
* @param _params a parameters array
* _params[0] - _preBoostedVoteRequiredPercentage,
* _params[1] - _preBoostedVotePeriodLimit, //the time limit for a proposal to be in an absolute voting mode.
* _params[2] -_boostedVotePeriodLimit, //the time limit for a proposal to be in an relative voting mode.
* _params[3] -_thresholdConstA
* _params[4] -_thresholdConstB
* _params[5] -_minimumStakingFee
* _params[6] -_quietEndingPeriod
* _params[7] -_proposingRepRewardConstA
* _params[8] -_proposingRepRewardConstB
* _params[9] -_stakerFeeRatioForVoters
* _params[10] -_votersReputationLossRatio
* _params[11] -_votersGainRepRatioFromLostRep
* _params[12] - _daoBountyConst
* _params[13] - _daoBountyLimit
*/
function setParameters(
uint[14] _params //use array here due to stack too deep issue.
)
public
returns(bytes32)
{
require(_params[0] <= 100 && _params[0] > 0,"0 < preBoostedVoteRequiredPercentage <= 100");
require(_params[4] > 0 && _params[4] <= 100000000,"0 < thresholdConstB < 100000000 ");
require(_params[3] <= 100000000 ether,"thresholdConstA <= 100000000 wei");
require(_params[9] <= 100,"stakerFeeRatioForVoters <= 100");
require(_params[10] <= 100,"votersReputationLossRatio <= 100");
require(_params[11] <= 100,"votersGainRepRatioFromLostRep <= 100");
require(_params[2] >= _params[6],"boostedVotePeriodLimit >= quietEndingPeriod");
require(_params[7] <= 100000000,"proposingRepRewardConstA <= 100000000");
require(_params[8] <= 100000000,"proposingRepRewardConstB <= 100000000");
require(_params[12] <= (2 * _params[9]),"daoBountyConst <= 2 * stakerFeeRatioForVoters");
require(_params[12] >= _params[9],"daoBountyConst >= stakerFeeRatioForVoters");
bytes32 paramsHash = getParametersHash(_params);
parameters[paramsHash] = Parameters({
preBoostedVoteRequiredPercentage: _params[0],
preBoostedVotePeriodLimit: _params[1],
boostedVotePeriodLimit: _params[2],
thresholdConstA:_params[3],
thresholdConstB:_params[4],
minimumStakingFee: _params[5],
quietEndingPeriod: _params[6],
proposingRepRewardConstA: _params[7],
proposingRepRewardConstB:_params[8],
stakerFeeRatioForVoters:_params[9],
votersReputationLossRatio:_params[10],
votersGainRepRatioFromLostRep:_params[11],
daoBountyConst:_params[12],
daoBountyLimit:_params[13]
});
return paramsHash;
}
/**
* @dev hashParameters returns a hash of the given parameters
*/
function getParametersHash(
uint[14] _params) //use array here due to stack too deep issue.
public
pure
returns(bytes32)
{
return keccak256(
abi.encodePacked(
_params[0],
_params[1],
_params[2],
_params[3],
_params[4],
_params[5],
_params[6],
_params[7],
_params[8],
_params[9],
_params[10],
_params[11],
_params[12],
_params[13]));
}
/**
* @dev execute check if the proposal has been decided, and if so, execute the proposal
* @param _proposalId the id of the proposal
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function _execute(bytes32 _proposalId) internal votable(_proposalId) returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
Proposal memory tmpProposal = proposal;
uint totalReputation = Avatar(proposal.avatar).nativeReputation().totalSupply();
uint executionBar = totalReputation * params.preBoostedVoteRequiredPercentage/100;
ExecutionState executionState = ExecutionState.None;
if (proposal.state == ProposalState.PreBoosted) {
// solium-disable-next-line security/no-block-members
if ((now - proposal.submittedTime) >= params.preBoostedVotePeriodLimit) {
proposal.state = ProposalState.Closed;
proposal.winningVote = NO;
executionState = ExecutionState.PreBoostedTimeOut;
} else if (proposal.votes[proposal.winningVote] > executionBar) {
// someone crossed the absolute vote execution bar.
proposal.state = ProposalState.Executed;
executionState = ExecutionState.PreBoostedBarCrossed;
} else if ( shouldBoost(_proposalId)) {
//change proposal mode to boosted mode.
proposal.state = ProposalState.Boosted;
// solium-disable-next-line security/no-block-members
proposal.boostedPhaseTime = now;
proposalsExpiredTimes[proposal.avatar].insert(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
orgBoostedProposalsCnt[proposal.avatar]++;
}
}
if ((proposal.state == ProposalState.Boosted) ||
(proposal.state == ProposalState.QuietEndingPeriod)) {
// solium-disable-next-line security/no-block-members
if ((now - proposal.boostedPhaseTime) >= proposal.currentBoostedVotePeriodLimit) {
proposalsExpiredTimes[proposal.avatar].remove(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
orgBoostedProposalsCnt[tmpProposal.avatar] = orgBoostedProposalsCnt[tmpProposal.avatar].sub(1);
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedTimeOut;
} else if (proposal.votes[proposal.winningVote] > executionBar) {
// someone crossed the absolute vote execution bar.
orgBoostedProposalsCnt[tmpProposal.avatar] = orgBoostedProposalsCnt[tmpProposal.avatar].sub(1);
proposalsExpiredTimes[proposal.avatar].remove(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedBarCrossed;
}
}
if (executionState != ExecutionState.None) {
if (proposal.winningVote == YES) {
uint daoBountyRemain = (params.daoBountyConst.mul(proposal.stakes[proposal.winningVote]))/100;
if (daoBountyRemain > params.daoBountyLimit) {
daoBountyRemain = params.daoBountyLimit;
}
proposal.daoBountyRemain = daoBountyRemain;
}
emit ExecuteProposal(_proposalId, proposal.avatar, proposal.winningVote, totalReputation);
emit GPExecuteProposal(_proposalId, executionState);
(tmpProposal.executable).execute(_proposalId, tmpProposal.avatar, int(proposal.winningVote));
}
return (executionState != ExecutionState.None);
}
/**
* @dev staking function
* @param _proposalId id of the proposal
* @param _vote NO(2) or YES(1).
* @param _amount the betting amount
* @param _staker the staker address
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function _stake(bytes32 _proposalId, uint _vote, uint _amount,address _staker) internal returns(bool) {
// 0 is not a valid vote.
require(_vote <= NUM_OF_CHOICES && _vote > 0);
require(_amount > 0);
if (_execute(_proposalId)) {
return true;
}
Proposal storage proposal = proposals[_proposalId];
if (proposal.state != ProposalState.PreBoosted) {
return false;
}
// enable to increase stake only on the previous stake vote
Staker storage staker = proposal.stakers[_staker];
if ((staker.amount > 0) && (staker.vote != _vote)) {
return false;
}
uint amount = _amount;
Parameters memory params = parameters[proposal.paramsHash];
require(amount >= params.minimumStakingFee);
require(stakingToken.transferFrom(_staker, address(this), amount));
proposal.totalStakes[1] = proposal.totalStakes[1].add(amount); //update totalRedeemableStakes
staker.amount += amount;
staker.amountForBounty = staker.amount;
staker.vote = _vote;
proposal.votersStakes += (params.stakerFeeRatioForVoters * amount)/100;
proposal.stakes[_vote] = amount.add(proposal.stakes[_vote]);
amount = amount - ((params.stakerFeeRatioForVoters*amount)/100);
proposal.totalStakes[0] = amount.add(proposal.totalStakes[0]);
// Event:
emit Stake(_proposalId, proposal.avatar, _staker, _vote, _amount);
// execute the proposal if this vote was decisive:
return _execute(_proposalId);
}
/**
* @dev Vote for a proposal, if the voter already voted, cancel the last vote and set a new one instead
* @param _proposalId id of the proposal
* @param _voter used in case the vote is cast for someone else
* @param _vote a value between 0 to and the proposal's number of choices.
* @param _rep how many reputation the voter would like to stake for this vote.
* if _rep==0 so the voter full reputation will be use.
* @return true in case of proposal execution otherwise false
* throws if proposal is not open or if it has been executed
* NB: executes the proposal if a decision has been reached
*/
function internalVote(bytes32 _proposalId, address _voter, uint _vote, uint _rep) internal returns(bool) {
// 0 is not a valid vote.
require(_vote <= NUM_OF_CHOICES && _vote > 0,"0 < _vote <= 2");
if (_execute(_proposalId)) {
return true;
}
Parameters memory params = parameters[proposals[_proposalId].paramsHash];
Proposal storage proposal = proposals[_proposalId];
// Check voter has enough reputation:
uint reputation = Avatar(proposal.avatar).nativeReputation().reputationOf(_voter);
require(reputation >= _rep);
uint rep = _rep;
if (rep == 0) {
rep = reputation;
}
// If this voter has already voted, return false.
if (proposal.voters[_voter].reputation != 0) {
return false;
}
// The voting itself:
proposal.votes[_vote] = rep.add(proposal.votes[_vote]);
//check if the current winningVote changed or there is a tie.
//for the case there is a tie the current winningVote set to NO.
if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) ||
((proposal.votes[NO] == proposal.votes[proposal.winningVote]) &&
proposal.winningVote == YES))
{
// solium-disable-next-line security/no-block-members
uint _now = now;
if ((proposal.state == ProposalState.QuietEndingPeriod) ||
((proposal.state == ProposalState.Boosted) && ((_now - proposal.boostedPhaseTime) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod)))) {
//quietEndingPeriod
proposalsExpiredTimes[proposal.avatar].remove(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
if (proposal.state != ProposalState.QuietEndingPeriod) {
proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod;
proposal.state = ProposalState.QuietEndingPeriod;
}
proposal.boostedPhaseTime = _now;
proposalsExpiredTimes[proposal.avatar].insert(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
}
proposal.winningVote = _vote;
}
proposal.voters[_voter] = Voter({
reputation: rep,
vote: _vote,
preBoosted:(proposal.state == ProposalState.PreBoosted)
});
if (proposal.state == ProposalState.PreBoosted) {
proposal.preBoostedVotes[_vote] = rep.add(proposal.preBoostedVotes[_vote]);
uint reputationDeposit = (params.votersReputationLossRatio * rep)/100;
ControllerInterface(Avatar(proposal.avatar).owner()).burnReputation(reputationDeposit,_voter,proposal.avatar);
}
// Event:
emit VoteProposal(_proposalId, proposal.avatar, _voter, _vote, rep);
// execute the proposal if this vote was decisive:
return _execute(_proposalId);
}
/**
* @dev _score return the proposal score
* For dual choice proposal S = (S+) - (S-)
* @param _proposalId the ID of the proposal
* @return int proposal score.
*/
function _score(bytes32 _proposalId) private view returns(int) {
Proposal storage proposal = proposals[_proposalId];
return int(proposal.stakes[YES]) - int(proposal.stakes[NO]);
}
/**
* @dev _isVotable check if the proposal is votable
* @param _proposalId the ID of the proposal
* @return bool true or false
*/
function _isVotable(bytes32 _proposalId) private view returns(bool) {
ProposalState pState = proposals[_proposalId].state;
return ((pState == ProposalState.PreBoosted)||(pState == ProposalState.Boosted)||(pState == ProposalState.QuietEndingPeriod));
}
}
|
getNativeReputation _avatar the organization avatar. return organization native reputation/
|
function getNativeReputation(address _avatar) external isAvatarValid(_avatar) view returns(address) {
return address(nativeReputation);
}
| 1,299,111 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.7.0;
import "../contracts/lifecycle/Ownable.sol";
/**
* The ERC721TokenRegistry is a basic registry mapping token symbols
* to their known, deployed addresses on the current blockchain.
*
* Note that the TokenRegistry does *not* mediate any of the
* core protocol's business logic, but, rather, is a helpful
* utility for Terms Contracts to use in encoding, decoding, and
* resolving the addresses of currently deployed tokens.
*
* At this point in time, administration of the Token Registry is
* under Dharma Labs' control. With more sophisticated decentralized
* governance mechanisms, we intend to shift ownership of this utility
* contract to the Dharma community.
*/
contract ERC721TokenRegistry is Ownable {
mapping (bytes32 => TokenAttributes) public symbolHashToTokenAttributes;
// Solidity prevents us from declaring a dynamically sized string array (since a string is
// itself an array, and 2D arrays are not supported), and so here we specify the maximum
// size of the tokenSymbolList.
string[4294967295] public tokenSymbolList;
uint32 public tokenSymbolListLength;
struct TokenAttributes {
// The ERC721 contract address.
address tokenAddress;
// The index in `tokenSymbolList` where the token's symbol can be found.
uint tokenIndex;
// The name of the given token, e.g. "CryptoKitties"
string name;
}
/**
* Maps the given symbol to the given token attributes.
*/
function setTokenAttributes(
string memory _symbol,
address _tokenAddress,
string memory _tokenName
)
public onlyOwner
{
bytes32 symbolHash = keccak256(abi.encode(_symbol));
// Attempt to retrieve the token's attributes from the registry.
TokenAttributes memory attributes = symbolHashToTokenAttributes[symbolHash];
if (attributes.tokenAddress == address(0)) {
// The token has not yet been added to the registry.
attributes.tokenAddress = _tokenAddress;
attributes.name = _tokenName;
attributes.tokenIndex = tokenSymbolListLength;
tokenSymbolList[tokenSymbolListLength] = _symbol;
tokenSymbolListLength++;
} else {
// The token has already been added to the registry; update attributes.
attributes.tokenAddress = _tokenAddress;
attributes.name = _tokenName;
}
// Update this contract's storage.
symbolHashToTokenAttributes[symbolHash] = attributes;
}
/**
* Given a symbol, resolves the current address of the token the symbol is mapped to.
*/
function getTokenAddressBySymbol(string memory _symbol) public view returns (address) {
bytes32 symbolHash = keccak256(abi.encode(_symbol));
TokenAttributes storage attributes = symbolHashToTokenAttributes[symbolHash];
return attributes.tokenAddress;
}
/**
* Given the known index of a token within the registry's symbol list,
* returns the address of the token mapped to the symbol at that index.
*/
function getTokenAddressByIndex(uint _index) public view returns (address) {
string storage symbol = tokenSymbolList[_index];
return getTokenAddressBySymbol(symbol);
}
/**
* Given a symbol, resolves the index of the token the symbol is mapped to within the registry's
* symbol list.
*/
function getTokenIndexBySymbol(string memory _symbol) public view returns (uint) {
bytes32 symbolHash = keccak256(abi.encode(_symbol));
TokenAttributes storage attributes = symbolHashToTokenAttributes[symbolHash];
return attributes.tokenIndex;
}
/**
* Given an index, resolves the symbol of the token at that index in the registry's
* token symbol list.
*/
function getTokenSymbolByIndex(uint _index) public view returns (string memory) {
return tokenSymbolList[_index];
}
/**
* Given a symbol, returns the name of the token the symbol is mapped to within the registry's
* symbol list.
*/
function getTokenNameBySymbol(string memory _symbol) public view returns (string memory) {
bytes32 symbolHash = keccak256(abi.encode(_symbol));
TokenAttributes storage attributes = symbolHashToTokenAttributes[symbolHash];
return attributes.name;
}
/**
* Given the index for a token in the registry, returns the name of the token as provided in
* the associated TokensAttribute struct.
*
* Example:
* getTokenNameByIndex(1);
* => "CryptoKitties"
*/
function getTokenNameByIndex(uint _index) public view returns (string memory) {
string memory symbol = getTokenSymbolByIndex(_index);
string memory tokenName = getTokenNameBySymbol(symbol);
return tokenName;
}
/**
* Given the symbol for a token in the registry, returns a tuple containing the token's address,
* the token's index in the registry, and the token's name.
*
* Example:
* getTokenAttributesBySymbol("CK");
* => ["0x06012c8cf97BEaD5deAe237070F9587f8E7A266d", 1, "CryptoKitties"]
*/
function getTokenAttributesBySymbol(string memory _symbol)
public
view
returns (
address,
uint,
string memory
)
{
bytes32 symbolHash = keccak256(abi.encode(_symbol));
TokenAttributes storage attributes = symbolHashToTokenAttributes[symbolHash];
return (
attributes.tokenAddress,
attributes.tokenIndex,
attributes.name
);
}
/**
* Given the index for a token in the registry, returns a tuple containing the token's address,
* the token's symbol, and the token's name.
*
* Example:
* getTokenAttributesByIndex(1);
* => ["0x06012c8cf97BEaD5deAe237070F9587f8E7A266d", "CK", "CryptoKitties"]
*/
function getTokenAttributesByIndex(uint _index)
public
view
returns (
address,
string memory,
string memory
)
{
string memory symbol = getTokenSymbolByIndex(_index);
bytes32 symbolHash = keccak256(abi.encode(symbol));
TokenAttributes storage attributes = symbolHashToTokenAttributes[symbolHash];
return (
attributes.tokenAddress,
symbol,
attributes.name
);
}
}
|
Given a symbol, resolves the current address of the token the symbol is mapped to./
|
function getTokenAddressBySymbol(string memory _symbol) public view returns (address) {
bytes32 symbolHash = keccak256(abi.encode(_symbol));
TokenAttributes storage attributes = symbolHashToTokenAttributes[symbolHash];
return attributes.tokenAddress;
}
| 14,038,982 |
/*
* Copyright 2019, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.5.3;
import "./MerkleLib.sol";
import "./ArbProtocol.sol";
library Bisection {
enum State {
NoChallenge,
Challenged,
Bisected
}
struct Challenge {
bytes32 vmId;
// After bisection this is an array of all sub-assertions
// After a challenge, the first assertion is the main assertion
bytes32 challengeState;
uint128[2] escrows;
address[2] players;
uint64 deadline;
// The current deadline at which the challenge timeouts and a winner is
// declared. This deadline resets at each step in the challenge
uint32 challengePeriod;
State state;
}
event ContinuedChallenge (
bytes32 indexed vmId,
address challenger,
uint assertionIndex
);
event BisectedAssertion(
bytes32 indexed vmId,
address bisecter,
bytes32[] afterHashAndMessageAndLogsBisections,
uint32 totalSteps,
uint256[] totalMessageAmounts
);
function continueChallenge(
Challenge storage _challenge,
uint _assertionToChallenge,
bytes memory _proof,
bytes32 _bisectionRoot,
bytes32 _bisectionHash
)
public
{
require(
_bisectionRoot == _challenge.challengeState,
"continueChallenge: Incorrect previous state"
);
require(
block.number <= _challenge.deadline,
"Challenge deadline expired"
);
require(
msg.sender == _challenge.players[1],
"Only original challenger can continue challenge"
);
require(
MerkleLib.verifyProof(
_proof,
_bisectionRoot,
_bisectionHash,
_assertionToChallenge + 1
),
"Invalid assertion selected"
);
_challenge.state = Bisection.State.Challenged;
_challenge.deadline = uint64(block.number) + uint64(_challenge.challengePeriod);
_challenge.challengeState = _bisectionHash;
emit ContinuedChallenge(_challenge.vmId, _challenge.players[1], _assertionToChallenge);
}
// fields
// _beforeHash
// _beforeInbox
function bisectAssertion(
Challenge storage _challenge,
bytes32[2] memory _fields,
bytes32[] memory _afterHashAndMessageAndLogsBisections,
uint256[] memory _totalMessageAmounts,
uint32 _totalSteps,
uint64[2] memory _timeBounds,
bytes21[] memory _tokenTypes,
uint256[] memory _beforeBalances
)
public
{
require(
_challenge.state == Bisection.State.Challenged,
"Can only bisect assertion in response to a challenge"
);
require(
_tokenTypes.length == 0 ||
(_totalMessageAmounts.length % _tokenTypes.length == 0),
"Incorrect input length"
);
require(
_tokenTypes.length == 0 ||
((_afterHashAndMessageAndLogsBisections.length - 1) / 3 ==
_totalMessageAmounts.length / _tokenTypes.length),
"Incorrect input length"
);
require(_tokenTypes.length == _beforeBalances.length, "Incorrect input length");
require(
block.number <= _challenge.deadline,
"Challenge deadline expired"
);
require(
msg.sender == _challenge.players[0],
"Only orignal asserter can bisect"
);
bytes32 fullHash;
bytes32[] memory bisectionHashes;
(fullHash, bisectionHashes) = generateBisectionDataImpl(
BisectAssertionData(
uint32((_afterHashAndMessageAndLogsBisections.length - 1) / 3),
_afterHashAndMessageAndLogsBisections,
_totalMessageAmounts,
_totalSteps,
_fields[0],
_timeBounds,
_tokenTypes,
_beforeBalances,
_fields[1]
)
);
require(
fullHash == _challenge.challengeState,
"Does not match prev state"
);
_challenge.state = Bisection.State.Bisected;
_challenge.deadline = uint64(block.number) + uint64(_challenge.challengePeriod);
_challenge.challengeState = MerkleLib.generateRoot(bisectionHashes);
emit BisectedAssertion(
_challenge.vmId,
_challenge.players[0],
_afterHashAndMessageAndLogsBisections,
_totalSteps,
_totalMessageAmounts
);
}
// bisectionFields:
// afterHash
// Message Bisections
// Logs Bisections
struct BisectAssertionData {
uint32 bisectionCount;
bytes32[] bisectionFields;
uint256[] totalMessageAmounts;
uint32 totalSteps;
bytes32 beforeHash;
uint64[2] timeBounds;
bytes21[] tokenTypes;
uint256[] beforeBalances;
bytes32 beforeInbox;
}
struct GenerateBisectionHashesImplFrame {
bytes32 beforeHash;
bytes32 preconditionHash;
bytes32 fullHash;
bytes32[] hashes;
uint256[] coinAmounts;
uint32 stepCount;
}
function generateBisectionDataImpl(
BisectAssertionData memory _data
)
private
pure
returns (bytes32, bytes32[] memory)
{
GenerateBisectionHashesImplFrame memory frame;
frame.hashes = new bytes32[](_data.bisectionCount);
frame.stepCount = _data.totalSteps / _data.bisectionCount + 1;
uint i;
uint j;
frame.beforeHash = _data.beforeHash;
for (j = 0; j < _data.bisectionCount; j++) {
if (j == _data.totalSteps % _data.bisectionCount) {
frame.stepCount--;
}
frame.coinAmounts = new uint256[](_data.tokenTypes.length);
for (i = 0; i < _data.tokenTypes.length; i++) {
frame.coinAmounts[i] += _data.totalMessageAmounts[j * _data.tokenTypes.length + i];
}
frame.preconditionHash = ArbProtocol.generatePreconditionHash(
frame.beforeHash,
_data.timeBounds,
_data.beforeInbox,
_data.tokenTypes,
_data.beforeBalances
);
for (i = 0; i < _data.tokenTypes.length; i++) {
_data.beforeBalances[i] -= frame.coinAmounts[i];
}
frame.hashes[j] = keccak256(
abi.encodePacked(
frame.preconditionHash,
ArbProtocol.generateAssertionHash(
_data.bisectionFields[j],
frame.stepCount,
_data.bisectionFields[_data.bisectionCount + j],
_data.bisectionFields[_data.bisectionCount + j + 1],
_data.bisectionFields[_data.bisectionCount * 2 + 1 + j],
_data.bisectionFields[_data.bisectionCount * 2 + 2 + j],
frame.coinAmounts
)
)
);
frame.beforeHash = _data.bisectionFields[j];
if (j == 0) {
frame.coinAmounts = new uint256[](_data.tokenTypes.length);
for (i = 0; i < _data.totalMessageAmounts.length; i++) {
frame.coinAmounts[i % _data.tokenTypes.length] += _data.totalMessageAmounts[i];
}
frame.fullHash = keccak256(
abi.encodePacked(
frame.preconditionHash,
ArbProtocol.generateAssertionHash(
_data.bisectionFields[_data.bisectionCount - 1],
_data.totalSteps,
_data.bisectionFields[_data.bisectionCount],
_data.bisectionFields[_data.bisectionCount * 2],
_data.bisectionFields[_data.bisectionCount * 2 + 1],
_data.bisectionFields[_data.bisectionFields.length - 1],
frame.coinAmounts
)
)
);
}
}
return (frame.fullHash, frame.hashes);
}
}
|
fields _beforeHash _beforeInbox
|
function bisectAssertion(
Challenge storage _challenge,
bytes32[2] memory _fields,
bytes32[] memory _afterHashAndMessageAndLogsBisections,
uint256[] memory _totalMessageAmounts,
uint32 _totalSteps,
uint64[2] memory _timeBounds,
bytes21[] memory _tokenTypes,
uint256[] memory _beforeBalances
)
public
{
require(
_challenge.state == Bisection.State.Challenged,
"Can only bisect assertion in response to a challenge"
);
require(
_tokenTypes.length == 0 ||
(_totalMessageAmounts.length % _tokenTypes.length == 0),
"Incorrect input length"
);
require(
_tokenTypes.length == 0 ||
((_afterHashAndMessageAndLogsBisections.length - 1) / 3 ==
_totalMessageAmounts.length / _tokenTypes.length),
"Incorrect input length"
);
require(_tokenTypes.length == _beforeBalances.length, "Incorrect input length");
require(
block.number <= _challenge.deadline,
"Challenge deadline expired"
);
require(
msg.sender == _challenge.players[0],
"Only orignal asserter can bisect"
);
bytes32 fullHash;
bytes32[] memory bisectionHashes;
(fullHash, bisectionHashes) = generateBisectionDataImpl(
BisectAssertionData(
uint32((_afterHashAndMessageAndLogsBisections.length - 1) / 3),
_afterHashAndMessageAndLogsBisections,
_totalMessageAmounts,
_totalSteps,
_fields[0],
_timeBounds,
_tokenTypes,
_beforeBalances,
_fields[1]
)
);
require(
fullHash == _challenge.challengeState,
"Does not match prev state"
);
_challenge.state = Bisection.State.Bisected;
_challenge.deadline = uint64(block.number) + uint64(_challenge.challengePeriod);
_challenge.challengeState = MerkleLib.generateRoot(bisectionHashes);
emit BisectedAssertion(
_challenge.vmId,
_challenge.players[0],
_afterHashAndMessageAndLogsBisections,
_totalSteps,
_totalMessageAmounts
);
}
| 14,121,389 |
./full_match/1/0x8CD834258d000166769733Dfb5fB6fD6E43dB4e7/sources/@nftculture/nftc-contracts/contracts/financial/NFTCPaymentSplitterBase.sol
|
Getter for the amount of payee's releasable Ether./
|
function releasable(address account) public view returns (uint256) {
return _releasable(account);
}
| 4,861,781 |
./full_match/43113/0x0B86ec194B844a23bC31DD17506e2621B16265DA/sources/contracts/ERC721Tradable.sol
|
increments the value of _currentTokenId/
|
function _incrementTokenId() private {
_currentTokenId++;
}
| 7,172,198 |
./partial_match/4/0xD66D362aDeD1d0c9Eac9d22A876A7d17C2DA8579/sources/Backo.sol
|
Add funds according to the membership level `_levelId` for `_rounds` rounds
|
function addFund(uint256 _rounds, uint256 _levelId)
public
payable
stopInEmergency
{
require(msg.sender != creator);
uint256 price = _rounds.mul(levelInfos[_levelId].amountPerRound);
require(msg.value >= price, 'addFund: Not enough value');
LevelInfo storage levelInfo = levelInfos[_levelId];
MemberInfo storage memberInfo = memberInfos[msg.sender];
if (memberInfo.roundsRemaining > 0) {
require(memberInfo.levelId == _levelId, 'addFund: wrong level');
memberInfo.levelId = _levelId;
memberInfo.lastClaimRound = roundsDone;
levelInfo.numberOfMembers = levelInfo.numberOfMembers.add(1);
}
memberInfo.roundsRemaining = memberInfo.roundsRemaining.add(_rounds);
_claimReward();
uint256 amountToRefund = msg.value.sub(price);
(bool success, ) = msg.sender.call.value(amountToRefund)("");
require(success);
emit MemberAddedFund(msg.sender, _rounds, _levelId);
}
| 16,990,862 |
./full_match/1/0x19de553a8CfFCFF8CB49E236C1a499F9CF083b97/sources/contracts/token/onft/ONFT721Core.sol
|
When a srcChain has the ability to transfer more chainIds in a single tx than the dst can do. Needs the ability to iterate and stop if the minGasToTransferAndStore is not met if not enough gas to process, store this index for next loop
|
function _creditTill(
uint16 _srcChainId,
address _toAddress,
uint _startIndex,
uint[] memory _tokenIds
) internal returns (uint256) {
uint i = _startIndex;
while (i < _tokenIds.length) {
if (gasleft() < minGasToTransferAndStore) break;
_creditTo(_srcChainId, _toAddress, _tokenIds[i]);
i++;
}
}
| 16,597,540 |
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import 'OpenZeppelin/[email protected]/contracts/math/SafeMath.sol';
import '../Governable.sol';
import '../../interfaces/IOracle.sol';
import '../../interfaces/IBaseOracle.sol';
import '../../interfaces/IERC20Wrapper.sol';
contract ProxyOracle is IOracle, Governable {
using SafeMath for uint;
/// The governor sets oracle information for a token.
event SetOracle(address token, Oracle info);
/// The governor unsets oracle information for a token.
event UnsetOracle(address token);
/// The governor sets token whitelist for an ERC1155 token.
event SetWhitelist(address token, bool ok);
struct Oracle {
uint16 borrowFactor; // The borrow factor for this token, multiplied by 1e4.
uint16 collateralFactor; // The collateral factor for this token, multiplied by 1e4.
uint16 liqIncentive; // The liquidation incentive, multiplied by 1e4.
}
IBaseOracle public immutable source;
mapping(address => Oracle) public oracles; // Mapping from token address to oracle info.
mapping(address => bool) public whitelistERC1155;
/// @dev Create the contract and initialize the first governor.
constructor(IBaseOracle _source) public {
source = _source;
__Governable__init();
}
/// @dev Set oracle information for the given list of token addresses.
function setOracles(address[] memory tokens, Oracle[] memory info) external onlyGov {
require(tokens.length == info.length, 'inconsistent length');
for (uint idx = 0; idx < tokens.length; idx++) {
require(info[idx].borrowFactor >= 10000, 'borrow factor must be at least 100%');
require(info[idx].collateralFactor <= 10000, 'collateral factor must be at most 100%');
require(info[idx].liqIncentive >= 10000, 'incentive must be at least 100%');
require(info[idx].liqIncentive <= 20000, 'incentive must be at most 200%');
oracles[tokens[idx]] = info[idx];
emit SetOracle(tokens[idx], info[idx]);
}
}
function unsetOracles(address[] memory tokens) external onlyGov {
for (uint idx = 0; idx < tokens.length; idx++) {
oracles[tokens[idx]] = Oracle(0, 0, 0);
emit UnsetOracle(tokens[idx]);
}
}
/// @dev Set whitelist status for the given list of token addresses.
function setWhitelistERC1155(address[] memory tokens, bool ok) external onlyGov {
for (uint idx = 0; idx < tokens.length; idx++) {
whitelistERC1155[tokens[idx]] = ok;
emit SetWhitelist(tokens[idx], ok);
}
}
/// @dev Return whether the oracle supports evaluating collateral value of the given token.
function support(address token, uint id) external view override returns (bool) {
if (!whitelistERC1155[token]) return false;
address tokenUnderlying = IERC20Wrapper(token).getUnderlyingToken(id);
return oracles[tokenUnderlying].liqIncentive != 0;
}
/// @dev Return the amount of token out as liquidation reward for liquidating token in.
function convertForLiquidation(
address tokenIn,
address tokenOut,
uint tokenOutId,
uint amountIn
) external view override returns (uint) {
require(whitelistERC1155[tokenOut], 'bad token');
address tokenOutUnderlying = IERC20Wrapper(tokenOut).getUnderlyingToken(tokenOutId);
uint rateUnderlying = IERC20Wrapper(tokenOut).getUnderlyingRate(tokenOutId);
Oracle memory oracleIn = oracles[tokenIn];
Oracle memory oracleOut = oracles[tokenOutUnderlying];
require(oracleIn.liqIncentive != 0, 'bad underlying in');
require(oracleOut.liqIncentive != 0, 'bad underlying out');
uint pxIn = source.getETHPx(tokenIn);
uint pxOut = source.getETHPx(tokenOutUnderlying);
uint amountOut = amountIn.mul(pxIn).div(pxOut);
amountOut = amountOut.mul(2**112).div(rateUnderlying);
return amountOut.mul(oracleIn.liqIncentive).mul(oracleOut.liqIncentive).div(10000 * 10000);
}
/// @dev Return the value of the given input as ETH for collateral purpose.
function asETHCollateral(
address token,
uint id,
uint amount,
address owner
) external view override returns (uint) {
require(whitelistERC1155[token], 'bad token');
address tokenUnderlying = IERC20Wrapper(token).getUnderlyingToken(id);
uint rateUnderlying = IERC20Wrapper(token).getUnderlyingRate(id);
uint amountUnderlying = amount.mul(rateUnderlying).div(2**112);
Oracle memory oracle = oracles[tokenUnderlying];
require(oracle.liqIncentive != 0, 'bad underlying collateral');
uint ethValue = source.getETHPx(tokenUnderlying).mul(amountUnderlying).div(2**112);
return ethValue.mul(oracle.collateralFactor).div(10000);
}
/// @dev Return the value of the given input as ETH for borrow purpose.
function asETHBorrow(
address token,
uint amount,
address owner
) external view override returns (uint) {
Oracle memory oracle = oracles[token];
require(oracle.liqIncentive != 0, 'bad underlying borrow');
uint ethValue = source.getETHPx(token).mul(amount).div(2**112);
return ethValue.mul(oracle.borrowFactor).div(10000);
}
}
|
Return whether the oracle supports evaluating collateral value of the given token.
|
function support(address token, uint id) external view override returns (bool) {
if (!whitelistERC1155[token]) return false;
address tokenUnderlying = IERC20Wrapper(token).getUnderlyingToken(id);
return oracles[tokenUnderlying].liqIncentive != 0;
}
| 942,328 |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.10;
import "../types/ExodusAccessControlled.sol";
import "../interfaces/IERC20.sol";
abstract contract FrontEndRewarder is ExodusAccessControlled {
/* ========= STATE VARIABLES ========== */
uint256 public daoReward; // % reward for dao (3 decimals: 100 = 1%)
uint256 public refReward; // % reward for referrer (3 decimals: 100 = 1%)
mapping(address => uint256) public rewards; // front end operator rewards
mapping(address => bool) public whitelisted; // whitelisted status for operators
IERC20 internal immutable exo; // reward token
constructor(IExodusAuthority _authority, IERC20 _exo) ExodusAccessControlled(_authority) {
exo = _exo;
}
/* ========= EXTERNAL FUNCTIONS ========== */
// pay reward to front end operator
function getReward() external {
uint256 reward = rewards[msg.sender];
rewards[msg.sender] = 0;
exo.transfer(msg.sender, reward);
}
/* ========= INTERNAL ========== */
/**
* @notice add new market payout to user data
*/
function _giveRewards(uint256 _payout, address _referral) internal returns (uint256) {
// first we calculate rewards paid to the DAO and to the front end operator (referrer)
uint256 toDAO = (_payout * daoReward) / 1e4;
uint256 toRef = (_payout * refReward) / 1e4;
// and store them in our rewards mapping
if (whitelisted[_referral]) {
rewards[_referral] += toRef;
rewards[authority.guardian()] += toDAO;
} else {
// the DAO receives both rewards if referrer is not whitelisted
rewards[authority.guardian()] += toDAO + toRef;
}
return toDAO + toRef;
}
/**
* @notice set rewards for front end operators and DAO
*/
function setRewards(uint256 _toFrontEnd, uint256 _toDAO) external onlyGovernor {
refReward = _toFrontEnd;
daoReward = _toDAO;
}
/**
* @notice add or remove addresses from the reward whitelist
*/
function whitelist(address _operator) external onlyPolicy {
whitelisted[_operator] = !whitelisted[_operator];
}
}
|
set rewards for front end operators and DAO/
|
function setRewards(uint256 _toFrontEnd, uint256 _toDAO) external onlyGovernor {
refReward = _toFrontEnd;
daoReward = _toDAO;
}
| 6,404,660 |
./partial_match/42/0xAb4fDe17F6a078fEc8A1320530664EF8877bb248/sources/AToken2PTokenMigrator.sol
|
验证需要转换的两个代币是否正确将pToken转给用户将pToken转给用户
|
function migrate(address aToken, address payable pToken, uint amount) public {
address self = address(this);
ATokenInterface aTokenInstance = ATokenInterface(aToken);
address underlyingAssetAddress = aTokenInstance.underlyingAssetAddress();
if (underlyingAssetAddress == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) {
PEther pEth = PEther(pToken);
require(compareStrings(pEth.symbol(), "pETH"), "aToken and pToken not match");
PERC20 pErc20 = PERC20(pToken);
require(pErc20.underlying() == underlyingAssetAddress, "aToken and pToken not match");
}
uint aTokenBalance = aTokenInstance.balanceOf(msg.sender);
require(amount <= aTokenBalance, "error amount");
aTokenInstance.redeem(amount);
uint afterBalance = _getTokenBalance(underlyingAssetAddress);
uint redeemedBalance = afterBalance.sub(beforeBalance);
if (underlyingAssetAddress == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) {
PEther newLpToken = PEther(pToken);
uint pTokenBeforeBalance = _getTokenBalance(pToken);
uint pTokenAfterBalance = _getTokenBalance(pToken);
mintedBalance = pTokenAfterBalance.sub(pTokenBeforeBalance);
newLpToken.transferFrom(self, msg.sender, mintedBalance);
PERC20 newLpToken = PERC20(pToken);
uint pTokenBeforeBalance = _getTokenBalance(pToken);
IERC20(underlyingAssetAddress).approve(address(newLpToken), redeemedBalance);
newLpToken.mint(redeemedBalance);
uint pTokenAfterBalance = _getTokenBalance(pToken);
mintedBalance = pTokenAfterBalance.sub(pTokenBeforeBalance);
newLpToken.approve(self, mintedBalance);
newLpToken.transferFrom(self, msg.sender, mintedBalance);
}
}
| 3,316,608 |
pragma solidity ^0.6.6;
// SPDX-License-Identifier: MIT
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
/**
* @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
/**
* @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
interface IERC1155 {
event TransferSingle(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256 _id,
uint256 _amount
);
event TransferBatch(
address indexed _operator,
address indexed _from,
address indexed _to,
uint256[] _ids,
uint256[] _amounts
);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
event URI(string _amount, uint256 indexed _id);
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes calldata _data
) external;
function create(
uint256 _maxSupply,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external returns (uint256 tokenId);
function safeTransferFrom(
address _from,
address _to,
uint256 _id,
uint256 _amount,
bytes calldata _data
) external;
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _amounts,
bytes calldata _data
) external;
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);
function setApprovalForAll(address _operator, bool _approved) external;
function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator);
}
// SPDX-License-Identifier: MIT
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping(address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// SPDX-License-Identifier: MIT
contract PauserRole is Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor() internal {
_addPauser(_msgSender());
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
// SPDX-License-Identifier: MIT
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor() internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
/**
* @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
/**
* @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
contract PoolTokenWrapper {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public token;
constructor(IERC20 _erc20Address) public {
token = IERC20(_erc20Address);
}
uint256 private _totalSupply;
// Objects balances [id][address] => balance
mapping(uint256 => mapping(address => uint256)) internal _balances;
mapping(address => uint256) private _accountBalances;
mapping(uint256 => uint256) private _poolBalances;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOfAccount(address account) public view returns (uint256) {
return _accountBalances[account];
}
function balanceOfPool(uint256 id) public view returns (uint256) {
return _poolBalances[id];
}
function balanceOf(address account, uint256 id) public view returns (uint256) {
return _balances[id][account];
}
function stake(uint256 id, uint256 amount) public virtual {
_totalSupply = _totalSupply.add(amount);
_poolBalances[id] = _poolBalances[id].add(amount);
_accountBalances[msg.sender] = _accountBalances[msg.sender].add(amount);
_balances[id][msg.sender] = _balances[id][msg.sender].add(amount);
token.safeTransferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 id, uint256 amount) public virtual {
_totalSupply = _totalSupply.sub(amount);
_poolBalances[id] = _poolBalances[id].sub(amount);
_accountBalances[msg.sender] = _accountBalances[msg.sender].sub(amount);
_balances[id][msg.sender] = _balances[id][msg.sender].sub(amount);
token.safeTransfer(msg.sender, amount);
}
function transfer(
uint256 fromId,
uint256 toId,
uint256 amount
) public virtual {
_poolBalances[fromId] = _poolBalances[fromId].sub(amount);
_balances[fromId][msg.sender] = _balances[fromId][msg.sender].sub(amount);
_poolBalances[toId] = _poolBalances[toId].add(amount);
_balances[toId][msg.sender] = _balances[toId][msg.sender].add(amount);
}
function _rescuePoints(address account, uint256 id) internal {
uint256 amount = _balances[id][account];
_totalSupply = _totalSupply.sub(amount);
_poolBalances[id] = _poolBalances[id].sub(amount);
_accountBalances[msg.sender] = _accountBalances[msg.sender].sub(amount);
_balances[id][account] = _balances[id][account].sub(amount);
token.safeTransfer(account, amount);
}
}
// SPDX-License-Identifier: MIT
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
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() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// SPDX-License-Identifier: MIT
contract NftStake is PoolTokenWrapper, Ownable, Pausable, ReentrancyGuard {
using SafeMath for uint256;
IERC1155 public nfts;
struct Card {
uint256 points;
uint256 releaseTime;
uint256 mintFee;
}
struct Pool {
uint256 periodStart;
uint256 maxStake;
uint256 rewardRate; // 11574074074000, 1 point per day per staked token
uint256 feesCollected;
uint256 spentPoints;
uint256 controllerShare;
address artist;
mapping(address => uint256) lastUpdateTime;
mapping(address => uint256) points;
mapping(uint256 => Card) cards;
}
uint256 public constant MAX_CONTROLLER_SHARE = 1000;
uint256 public constant MIN_CARD_POINTS = 1e17;
address public controller;
address public rescuer;
mapping(address => uint256) public pendingWithdrawals;
mapping(uint256 => Pool) public pools;
event UpdatedArtist(uint256 poolId, address artist);
event PoolAdded(uint256 poolId, address artist, uint256 periodStart, uint256 rewardRate, uint256 maxStake);
event CardAdded(uint256 poolId, uint256 cardId, uint256 points, uint256 mintFee, uint256 releaseTime);
event Staked(address indexed user, uint256 poolId, uint256 amount);
event Withdrawn(address indexed user, uint256 poolId, uint256 amount);
event Transferred(address indexed user, uint256 fromPoolId, uint256 toPoolId, uint256 amount);
event Redeemed(address indexed user, uint256 poolId, uint256 amount);
event CardPointsUpdated(uint256 poolId, uint256 cardId, uint256 points);
modifier updateReward(address account, uint256 id) {
if (account != address(0)) {
pools[id].points[account] = earned(account, id);
pools[id].lastUpdateTime[account] = block.timestamp;
}
_;
}
modifier poolExists(uint256 id) {
require(pools[id].rewardRate > 0, "pool does not exists");
_;
}
modifier cardExists(uint256 pool, uint256 card) {
require(pools[pool].cards[card].points > 0, "card does not exists");
_;
}
constructor(
address _controller,
IERC1155 _nftsAddress,
IERC20 _tokenAddress
) public PoolTokenWrapper(_tokenAddress) {
require(_controller != address(0), "Invalid controller");
controller = _controller;
nfts = _nftsAddress;
}
function cardMintFee(uint256 pool, uint256 card) public view returns (uint256) {
return pools[pool].cards[card].mintFee;
}
function cardReleaseTime(uint256 pool, uint256 card) public view returns (uint256) {
return pools[pool].cards[card].releaseTime;
}
function cardPoints(uint256 pool, uint256 card) public view returns (uint256) {
return pools[pool].cards[card].points;
}
function earned(address account, uint256 pool) public view returns (uint256) {
Pool storage p = pools[pool];
uint256 blockTime = block.timestamp;
return
balanceOf(account, pool).mul(blockTime.sub(p.lastUpdateTime[account]).mul(p.rewardRate)).div(1e18).add(
p.points[account]
);
}
// override PoolTokenWrapper's stake() function
function stake(uint256 pool, uint256 amount)
public
override
poolExists(pool)
updateReward(msg.sender, pool)
whenNotPaused()
nonReentrant
{
Pool memory p = pools[pool];
require(block.timestamp >= p.periodStart, "pool not open");
require(amount.add(balanceOf(msg.sender, pool)) <= p.maxStake, "stake exceeds max");
super.stake(pool, amount);
emit Staked(msg.sender, pool, amount);
}
// override PoolTokenWrapper's withdraw() function
function withdraw(uint256 pool, uint256 amount)
public
override
poolExists(pool)
updateReward(msg.sender, pool)
nonReentrant
{
require(amount > 0, "cannot withdraw 0");
super.withdraw(pool, amount);
emit Withdrawn(msg.sender, pool, amount);
}
// override PoolTokenWrapper's transfer() function
function transfer(
uint256 fromPool,
uint256 toPool,
uint256 amount
)
public
override
poolExists(fromPool)
poolExists(toPool)
updateReward(msg.sender, fromPool)
updateReward(msg.sender, toPool)
whenNotPaused()
nonReentrant
{
Pool memory toP = pools[toPool];
require(block.timestamp >= toP.periodStart, "pool not open");
require(amount.add(balanceOf(msg.sender, toPool)) <= toP.maxStake, "stake exceeds max");
super.transfer(fromPool, toPool, amount);
emit Transferred(msg.sender, fromPool, toPool, amount);
}
function transferAll(uint256 fromPool, uint256 toPool) external nonReentrant {
transfer(fromPool, toPool, balanceOf(msg.sender, fromPool));
}
function exit(uint256 pool) external {
withdraw(pool, balanceOf(msg.sender, pool));
}
function redeem(uint256 pool, uint256 card)
public
payable
poolExists(pool)
cardExists(pool, card)
updateReward(msg.sender, pool)
nonReentrant
{
Pool storage p = pools[pool];
Card memory c = p.cards[card];
require(block.timestamp >= c.releaseTime, "card not released");
require(p.points[msg.sender] >= c.points, "not enough points");
require(msg.value == c.mintFee, "support our artists, send eth");
if (c.mintFee > 0) {
uint256 _controllerShare = msg.value.mul(p.controllerShare).div(MAX_CONTROLLER_SHARE);
uint256 _artistRoyalty = msg.value.sub(_controllerShare);
require(_artistRoyalty.add(_controllerShare) == msg.value, "problem with fee");
p.feesCollected = p.feesCollected.add(c.mintFee);
pendingWithdrawals[controller] = pendingWithdrawals[controller].add(_controllerShare);
pendingWithdrawals[p.artist] = pendingWithdrawals[p.artist].add(_artistRoyalty);
}
p.points[msg.sender] = p.points[msg.sender].sub(c.points);
p.spentPoints = p.spentPoints.add(c.points);
nfts.mint(msg.sender, card, 1, "");
emit Redeemed(msg.sender, pool, c.points);
}
function rescuePoints(address account, uint256 pool)
public
poolExists(pool)
updateReward(account, pool)
nonReentrant
returns (uint256)
{
require(msg.sender == rescuer, "!rescuer");
Pool storage p = pools[pool];
uint256 earnedPoints = p.points[account];
p.spentPoints = p.spentPoints.add(earnedPoints);
p.points[account] = 0;
// transfer remaining tokens to the account
if (balanceOf(account, pool) > 0) {
_rescuePoints(account, pool);
}
emit Redeemed(account, pool, earnedPoints);
return earnedPoints;
}
function setArtist(uint256 pool_, address artist_) public onlyOwner poolExists(pool_) nonReentrant {
require(artist_ != address(0), "Invalid artist");
address oldArtist = pools[pool_].artist;
pendingWithdrawals[artist_] = pendingWithdrawals[artist_].add(pendingWithdrawals[oldArtist]);
pendingWithdrawals[oldArtist] = 0;
pools[pool_].artist = artist_;
emit UpdatedArtist(pool_, artist_);
}
function setController(address _controller) public onlyOwner nonReentrant {
require(_controller != address(0), "Invalid controller");
pendingWithdrawals[_controller] = pendingWithdrawals[_controller].add(pendingWithdrawals[controller]);
pendingWithdrawals[controller] = 0;
controller = _controller;
}
function setRescuer(address _rescuer) public onlyOwner nonReentrant {
rescuer = _rescuer;
}
function setControllerShare(uint256 pool, uint256 _controllerShare) public onlyOwner poolExists(pool) nonReentrant {
require(_controllerShare <= MAX_CONTROLLER_SHARE, "Incorrect controller share");
pools[pool].controllerShare = _controllerShare;
}
function addCard(
uint256 pool,
uint256 id,
uint256 points,
uint256 mintFee,
uint256 releaseTime
) public onlyOwner poolExists(pool) nonReentrant {
require(points >= MIN_CARD_POINTS, "Points too small");
Card storage c = pools[pool].cards[id];
c.points = points;
c.releaseTime = releaseTime;
c.mintFee = mintFee;
emit CardAdded(pool, id, points, mintFee, releaseTime);
}
function createCard(
uint256 pool,
uint256 supply,
uint256 points,
uint256 mintFee,
uint256 releaseTime
) public onlyOwner poolExists(pool) nonReentrant returns (uint256) {
require(points >= MIN_CARD_POINTS, "Points too small");
uint256 tokenId = nfts.create(supply, 0, "", "");
require(tokenId > 0, "ERC1155 create did not succeed");
Card storage c = pools[pool].cards[tokenId];
c.points = points;
c.releaseTime = releaseTime;
c.mintFee = mintFee;
emit CardAdded(pool, tokenId, points, mintFee, releaseTime);
return tokenId;
}
function createPool(
uint256 id,
uint256 periodStart,
uint256 maxStake,
uint256 rewardRate,
uint256 controllerShare,
address artist
) public onlyOwner nonReentrant returns (uint256) {
require(rewardRate > 0, "Invalid rewardRate");
require(pools[id].rewardRate == 0, "pool exists");
require(artist != address(0), "Invalid artist");
require(controllerShare <= MAX_CONTROLLER_SHARE, "Incorrect controller share");
Pool storage p = pools[id];
p.periodStart = periodStart;
p.maxStake = maxStake;
p.rewardRate = rewardRate;
p.controllerShare = controllerShare;
p.artist = artist;
emit PoolAdded(id, artist, periodStart, rewardRate, maxStake);
}
function withdrawFee() public nonReentrant {
uint256 amount = pendingWithdrawals[msg.sender];
require(amount > 0, "nothing to withdraw");
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
}
// For development and QA
function assignPointsTo(
uint256 pool_,
address tester_,
uint256 points_
) public onlyOwner poolExists(pool_) nonReentrant returns (uint256) {
Pool storage p = pools[pool_];
p.points[tester_] = points_;
// rescue continues
return p.points[tester_];
}
/**
* @dev Updates card points
* @param poolId_ uint256 ID of the pool
* @param cardId_ uint256 ID of the card to update
* @param points_ uint256 new "points" value
*/
function updateCardPoints(
uint256 poolId_,
uint256 cardId_,
uint256 points_
) public onlyOwner poolExists(poolId_) cardExists(poolId_, cardId_) nonReentrant {
require(points_ >= MIN_CARD_POINTS, "Points too small");
Card storage c = pools[poolId_].cards[cardId_];
c.points = points_;
emit CardPointsUpdated(poolId_, cardId_, points_);
}
}
// SPDX-License-Identifier: MIT
contract EddaNftStake is NftStake {
constructor(
address _controller,
IERC1155 _nftsAddress,
IERC20 _tokenAddress
) public NftStake(_controller, _nftsAddress, _tokenAddress) {}
}
|
transfer remaining tokens to the account
|
function rescuePoints(address account, uint256 pool)
public
poolExists(pool)
updateReward(account, pool)
nonReentrant
returns (uint256)
{
require(msg.sender == rescuer, "!rescuer");
Pool storage p = pools[pool];
uint256 earnedPoints = p.points[account];
p.spentPoints = p.spentPoints.add(earnedPoints);
p.points[account] = 0;
if (balanceOf(account, pool) > 0) {
_rescuePoints(account, pool);
}
emit Redeemed(account, pool, earnedPoints);
return earnedPoints;
}
| 5,394,751 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.1;
pragma experimental ABIEncoderV2;
/**
* @title The Primitive House -> Manages collateral, leverages liquidity.
* @author Primitive
*/
// Open Zeppelin
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {
ReentrancyGuard
} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// Primitive
import {ICore} from "./interfaces/ICore.sol";
import {IFlash} from "./interfaces/IFlash.sol";
// Internal
import {Accelerator} from "./Accelerator.sol";
import {IProxyPriceProvider} from "./oracle/interfaces/IProxyPriceProvider.sol";
import {IHouse} from "./interfaces/IHouse.sol";
import {IWETH} from "./interfaces/IWETH.sol";
import {SafeMath} from "./libraries/SafeMath.sol";
import {Manager} from "./Manager.sol";
import {BasicERC1155Receiver} from "./utils/BasicERC1155Receiver.sol";
import {IMultiToken} from "./interfaces/IMultiToken.sol";
import "hardhat/console.sol";
contract House is Manager, Accelerator, ReentrancyGuard, BasicERC1155Receiver {
using SafeERC20 for IERC20;
using SafeMath for uint256;
/**
* @dev If (!_EXECUTING), `_NONCE` = `_NO_NONCE`.
*/
uint256 private constant _NO_NONCE = uint256(-1);
/**
* @dev If (!_EXECUTING), `_ADDRESS` = `_NO_ADDRESS`.
*/
address private constant _NO_ADDRESS = address(21);
/**
* @notice Event emitted after a successful `execute` call on the House.
*/
event Executed(address indexed from, address indexed venue);
/**
* @notice Event emitted when `token` is deposited to the House.
*/
event CollateralDeposited(
uint256 indexed nonce,
address indexed token,
uint256 indexed tokenId,
uint256 amount
);
/**
* @notice Event emitted when `token` is pushed to `msg.sender`, which should be `_VENUE`.
*/
event CollateralWithdrawn(
uint256 indexed nonce,
address indexed token,
uint256 indexed tokenId,
uint256 amount
);
/**
* @notice House balance sheet data structure.
*/
struct Warchest {
uint256 totalDebt;
uint256 totalSupply;
}
/**
* @notice User account data structure.
* 1. Depositor address
* 2. The wrapped ERC1155 token. Only 1 per account.
* 3. The ids for the wrapped tokens. Up to 4.
* 4. The balances of the wrapped tokens with ids.
* 5. The debt of the underlying token
* 6. The delta of debt in the executing block
*/
struct Account {
address depositor;
address wrappedToken;
uint256[] wrappedIds;
mapping(uint256 => uint256) balanceOf;
mapping(address => uint256) debtOf;
uint256 delta;
}
address[] public allCollateralTokens;
/**
* @dev The contract to execute transactions on behalf of the House.
*/
Accelerator internal _accelerator;
/**
* @dev If the `execute` function was called this block.
*/
bool private _EXECUTING;
/**
* @dev If _EXECUTING, the account with nonce is being manipulated
*/
uint256 private _NONCE = _NO_NONCE;
/**
* @dev If _EXECUTING, the venue being used to manipulate the account.
*/
address private _VENUE = _NO_ADDRESS;
/**
* @dev If _EXECUTING, the Account.depositor by default, _VENUE if set.
*/
address private _EXECUTING_SENDER = _NO_ADDRESS;
/**
* @dev The current nonce that will be set when a new account is initialized.
*/
uint256 private _accountNonce;
/**
* @dev The state of debt for the House.
*/
Warchest private _chest;
/**
* @dev The proxy oracle contract.
*/
IProxyPriceProvider private _oracle;
/**
* @dev All the accounts from a nonce of 0 to `_accountNonce` - 1.
*/
mapping(uint256 => Account) private _accounts;
/**
* @dev The options -> token -> amount claim.
*/
mapping(bytes32 => mapping(address => uint256)) internal _houseBalance;
/**
* @dev The token -> amount collateral locked amount.
*/
mapping(address => uint256) internal _collateralBalance;
/**
* @notice A mutex to use during an `execute` call.
*/
modifier isExec() {
require(_NONCE != _NO_NONCE, "House: NO_NONCE");
require(_VENUE == msg.sender, "House: NO_VENUE");
require(!_EXECUTING, "House: IN_EXECUTION");
_EXECUTING = true;
_;
_EXECUTING = false;
}
constructor(address core_, IProxyPriceProvider oracle_) Manager(core_) {
_accelerator = new Accelerator();
_oracle = oracle_;
}
// ====== Transfers ======
/**
* @notice Transfers ERC20 tokens from the executing account's depositor to the executing _VENUE.
* @param token The address of the ERC20.
* @param amount The amount of ERC20 to transfer.
* @return Whether or not the transfer succeeded.
*/
function takeTokensFromUser(address token, uint256 amount)
public
isExec
returns (bool)
{
return _takeTokensFromUser(token, amount);
}
function _takeTokensFromUser(address token, uint256 amount)
internal
returns (bool)
{
IERC20(token).safeTransferFrom(
_accounts[getExecutingNonce()].depositor, // Account owner
msg.sender, // The venue
amount
);
return true;
}
// ===== Collateral Management =====
/**
* @notice Pulls collateral tokens from `msg.sender` which is the executing `_VENUE`.
* Adds the amount of pulled tokens to the Account with `_NONCE`.
* @dev Reverts if no wrapped tokens are actually sent to this contract.
* @param wrappedToken The ERC1155 token contract to call to.
* @param wrappedId The ERC1155 token id to transfer from `msg.sender` to this contract.
* @param amount The amount of ERC1155 tokens to transfer.
* @return Whether or not the transfer succeeded.
*/
function addCollateral(
address wrappedToken,
uint256 wrappedId,
uint256 amount
) public isExec returns (uint256) {
return _addCollateral(wrappedToken, wrappedId, amount);
}
function _addCollateral(
address token,
uint256 wid,
uint256 amount
) internal returns (uint256) {
Account storage acc = _accounts[getExecutingNonce()];
if (acc.wrappedToken != token || acc.balanceOf[wid] == uint256(0)) {
console.log("initializing collateral");
_initializeCollateral(acc, token, wid);
}
console.log("pull wrapped tokens");
// Pull the tokens
uint256 actualAmount = _pullWrappedToken(token, wid, amount);
require(actualAmount > 0, "House: ADD_ZERO");
console.log("add to account balance");
// Add the tokens to the executing account state
acc.balanceOf[wid] += amount;
emit CollateralDeposited(_NONCE, token, wid, amount);
return actualAmount;
}
function addBatchCollateral(
address wrappedToken,
uint256[] memory wrappedIds,
uint256[] memory amounts
) public isExec returns (uint256) {
return _addBatchCollateral(wrappedToken, wrappedIds, amounts);
}
function _addBatchCollateral(
address token,
uint256[] memory wids,
uint256[] memory amounts
) internal returns (uint256) {
Account storage acc = _accounts[getExecutingNonce()];
if (acc.wrappedToken != token) {
console.log("initializing collateral");
uint256 len = wids.length;
for (uint256 i = 0; i < len; i++) {
uint256 wid = wids[i];
uint256 bal = acc.balanceOf[wid];
if (bal == 0) {
_initializeCollateral(acc, token, wid);
}
}
}
console.log("pull wrapped tokens");
// Pull the tokens
uint256 actualAmount = _pullBatchWrappedTokens(token, wids, amounts);
require(actualAmount > 0, "House: ADD_ZERO");
console.log("add to account balance");
// Add the tokens to the executing account state
//acc.balance = acc.balance.add(amount); //FIX
return actualAmount;
}
uint8 private constant MAX_WIDS = uint8(4);
/**
* @notice Called to update an Account with `_NONCE` with a `token` and `wid`.
* @param acc The Account to manipulate, fetched with the executing `_NONCE`.
* @param token The wrapped ERC1155 contract.
* @param wid The wrapped ERC1155 token id.
* @return Whether or not the intiialization succeeded.
*/
function _initializeCollateral(
Account storage acc,
address token,
uint256 wid
) internal returns (bool) {
console.log("acc balance", acc.balanceOf[wid]);
require(acc.balanceOf[wid] == uint256(0), "House: INITIALIZED");
require(acc.wrappedIds.length <= MAX_WIDS, "House: MAX_WIDS");
console.log("setting account wrapped token and id");
acc.wrappedToken = token;
acc.wrappedIds.push(wid);
return true;
}
/**
* @notice Transfers `wrappedToken` with `wrappedId` from this contract to the `msg.sender`.
* @dev The `msg.sender` should always be the `_VENUE`, since this can only be called `inExec`.
* @param wrappedToken The ERC1155 token contract to call to.
* @param wrappedId The ERC1155 token id to transfer from `msg.sender` to this contract.
* @param amount The amount of ERC1155 tokens to transfer.
* @return Whether or not the transfer succeeded.
*/
function removeCollateral(
address wrappedToken,
uint256 wrappedId,
uint256 amount
) public isExec returns (bool) {
console.log("house: internal removal");
// Remove wrappedTokens from account state
bool success = _removeCollateral(wrappedToken, wrappedId, amount);
console.log("house: safetransferfrom this to msgsender");
// Push the wrappedTokens to the msg.sender.
IERC1155(wrappedToken).safeTransferFrom(
address(this),
msg.sender,
wrappedId,
amount,
""
);
emit CollateralWithdrawn(_NONCE, wrappedToken, wrappedId, amount);
return success;
}
function _removeCollateral(
address token,
uint256 wid,
uint256 amount
) internal returns (bool) {
Account storage acc = _accounts[getExecutingNonce()];
console.log("checking wrapped token and id");
uint256 balance = acc.balanceOf[wid];
require(balance > 0, "House: INVALID_ID");
require(acc.wrappedToken == token, "House: INVALID_TOKEN");
if (amount == uint256(-1)) {
amount = balance;
}
console.log(
"house: acc.balance sub amount",
acc.balanceOf[wid],
amount
);
acc.balanceOf[wid] -= amount;
return true;
}
// ===== Lending =====
uint256 internal constant BASE_FACTOR = 1e4; // Collateral factor is scaled to 1e4.
struct Market {
bool isListed;
uint16 collateralFactor;
}
mapping(address => Market) internal _markets;
function getMarket(address token) public view returns (Market memory) {
return _markets[token];
}
function getUnderlyingBorrowValue(uint256 accNonce)
public
view
returns (uint256)
{
Account storage acc = _accounts[accNonce];
uint256 len = allCollateralTokens.length;
uint256 value;
for (uint256 i = 0; i < len; i++) {
address token = allCollateralTokens[i];
uint256 bal = acc.debtOf[token];
uint256 debt = bal.mul(_chest.totalDebt).div(_chest.totalSupply);
uint16 collateralFactor = getMarket(token);
if (deby > 0) {
value += _oracle
.getBorrow(token, debt)
.mul(collateralFactor)
.div(BASE_FACTOR); // multiplied by cfactor
}
}
return value;
}
function getCollateralUnderlyingValue(uint256 accNonce)
public
view
returns (uint256)
{
Account storage acc = _accounts[accNonce];
address multi = acc.wrappedToken;
require(multi != address(0x0), "House: ZERO_COLLATERAL");
uint256 len = acc.wrappedIds.length;
uint256 value;
for (uint256 i = 0; i < len; i++) {
uint256 wid = wrappedIds[i];
uint256 bal = acc.balanceOf[wid];
uint16 collateralFactor =
getMarket(IMultiToken(multi).getUnderlyingToken(wid));
if (bal > 0) {
value += _oracle.getCollateral(
multi,
wid,
bal.mul(collateralFactor).div(BASE_FACTOR)
); // multiplied by collateral factor
}
}
return value;
}
/**
* @notice Mints options to the receiver addresses without checking collateral.
* @param oid The option data id used to fetch option related data.
* @param requestAmt The requestAmt of long and short option ERC20 tokens to mint.
* @param receivers The long option ERC20 receiver, and short option ERC20 receiver.
* @return Whether or not the mint succeeded.
*/
function borrowOptions(
bytes32 oid,
uint256 requestAmt,
address[] memory receivers
) external isExec returns (uint256) {
// Get the account that is being updated
Account storage acc = _accounts[getExecutingNonce()];
// Update the acc delta
acc.delta = requestAmt;
(address base, , , , ) = getParameters(oid);
// Update debt state
uint256 totalSupply = _chest.totalSupply;
uint256 totalDebt = _chest.totalDebt;
// standard IOU
uint256 shareDelta =
totalSupply > 0 ? requestAmt.mul(totalSupply).div(totalDebt) : 0;
// Update acc debt balance
acc.debtOf[base] += shareDelta;
uint256 actualAmt = _core.dangerousMint(oid, requestAmt, receivers);
// Reset delta by subtracting from actual amount borrowed
acc.delta = actualAmt.sub(acc.delta);
return actualAmt;
}
// ===== Execution =====
/**
* @notice Manipulates an Account with `accountNonce` using a venue.
* @dev Warning: low-level call is executed by `_accelerator` contract.
* @param accountNonce The Account to manipulate.
* @param venue The Venue to call and execute `params`.
* @param params The encoded selector and arguments for the `_accelerator` to call `venue` with.
* @return Whether the execution succeeded or not.
*/
function execute(
uint256 accountNonce,
address venue,
bytes calldata params
) external payable nonReentrant returns (bool) {
// Get the Account to manipulate
if (accountNonce == 0) {
accountNonce = _accountNonce++;
_accounts[accountNonce].depositor = msg.sender;
} else {
require(
_accounts[accountNonce].depositor == msg.sender,
"House: NOT_DEPOSITOR"
);
require(accountNonce < _accountNonce, "House: ABOVE_NONCE");
}
_NONCE = accountNonce;
_VENUE = venue;
_accelerator.executeCall(venue, params);
_NONCE = _NO_NONCE;
_VENUE = _NO_ADDRESS;
emit Executed(msg.sender, venue);
return true;
}
// ===== Option Hooks =====
function exercise(
bytes32 oid,
uint256 amount,
address receiver,
bool fromInternal
) external isExec returns (bool) {
// If exercising from an internal balance, use the Venue's balance of tokens.
if (fromInternal) {
_EXECUTING_SENDER = getExecutingVenue();
}
exercise(oid, amount, receiver);
_EXECUTING_SENDER = _NO_ADDRESS;
return true;
}
function redeem(
bytes32 oid,
uint256 amount,
address receiver,
bool fromInternal
) external isExec returns (bool) {
// If redeeming from an internal balance, use the Venue's balance of tokens.
if (fromInternal) {
_EXECUTING_SENDER = getExecutingVenue();
}
redeem(oid, amount, receiver);
_EXECUTING_SENDER = _NO_ADDRESS;
return true;
}
function close(
bytes32 oid,
uint256 amount,
address receiver,
bool fromInternal
) external isExec returns (bool) {
// If closing from an internal balance, use the Venue's balance of tokens.
if (fromInternal) {
_EXECUTING_SENDER = getExecutingVenue();
}
close(oid, amount, receiver);
_EXECUTING_SENDER = _NO_ADDRESS;
return true;
}
/**
* @notice Hook to be implemented by higher-level Manager contract after minting occurs.
*/
function _onAfterMint(
bytes32 oid,
uint256 amount,
address[] memory receivers
) internal override isExec returns (bool) {
// Update internal base token balance
(address baseToken, , , , ) = getParameters(oid);
console.log("got parameters", baseToken);
// Update houseBalance
_collateralBalance[baseToken] = _collateralBalance[baseToken].add(
amount
);
console.log("pull base tokens from caller");
// pull the base tokens from acc.depositor
IERC20(baseToken).safeTransferFrom(
getExecutingCaller(),
address(this),
amount
);
return true;
}
/*
* @notice Hook to be implemented by higher-level Manager contract before exercising occurs.
*/
function _onBeforeExercise(
bytes32 oid,
uint256 amount,
address receiver
) internal override returns (bool) {
(address baseToken, , , , ) = getParameters(oid);
console.log("checking is not expired");
require(notExpired(oid), "House: EXPIRED_OPTION");
console.log("subtracting base claim");
// Update claim for base tokens
_collateralBalance[baseToken] -= amount;
console.log("pushing base tokens");
// Push base tokens
IERC20(baseToken).safeTransfer(receiver, amount);
console.log("_core.dangerousExercise");
return true;
}
/**
* @notice Hook to be implemented by higher-level Manager contract after exercising occurs.
*/
function _onAfterExercise(
bytes32 oid,
uint256 amount,
address receiver,
uint256 lessBase,
uint256 plusQuote
) internal override returns (bool) {
(, address quoteToken, , , ) = getParameters(oid);
// Update claim for quote tokens
_collateralBalance[quoteToken] += plusQuote;
console.log("pulling quote tokens");
// Pulls quote tokens
Account storage acc = _accounts[getExecutingNonce()];
//address pullFrom = fromInternal ? msg.sender : acc.depositor;
// fromInternal ? getExecutingVenue : getExecutingCaller
IERC20(quoteToken).safeTransferFrom(
_getExecutingSender(),
address(this),
plusQuote
);
return true;
}
/**
* @notice Hook to be implemented by higher-level Manager contract before redemption occurs.
*/
function _onBeforeRedeem(
bytes32 oid,
uint256 amount,
address receiver
) internal override returns (uint256, uint256) {
(, address quoteToken, uint256 strikePrice, , ) = getParameters(oid);
(, address short) = _core.getTokenData(oid);
console.log("checking is not expired");
require(notExpired(oid), "House: EXPIRED_OPTION");
// if not from internal, pull short options from caller to venue
if (_getExecutingSender() == getExecutingCaller()) {
console.log("taking tokens from user");
_takeTokensFromUser(short, amount);
}
uint256 quoteClaim = _collateralBalance[quoteToken];
uint256 minOutputQuote = amount.mul(strikePrice).div(1 ether);
console.log("calling core.dangerousredeem");
return (minOutputQuote, quoteClaim);
}
/**
* @notice Hook to be implemented by higher-level Manager contract after redemption occurs.
*/
function _onAfterRedeem(
bytes32 oid,
uint256 amount,
address receiver,
uint256 lessQuote
) internal override returns (bool) {
console.log("subtracting base claim");
(, address quoteToken, , , ) = getParameters(oid);
// Update claim for quoteTokens
_collateralBalance[quoteToken] -= lessQuote;
console.log("pushing quote tokens");
// Push base tokens
IERC20(quoteToken).safeTransfer(receiver, lessQuote);
return true;
}
/**
* @notice Hook to be implemented by higher-level Manager contract before closing occurs.
*/
function _onBeforeClose(
bytes32 oid,
uint256 amount,
address receiver
) internal override returns (bool) {
(address long, address short) = _core.getTokenData(oid);
console.log("checking is not expired");
require(notExpired(oid), "House: EXPIRED_OPTION");
// if not from internal, pull short options from caller to venue
if (_getExecutingSender() == getExecutingCaller()) {
console.log("take long and short from user");
_takeTokensFromUser(short, amount);
_takeTokensFromUser(long, amount);
}
console.log("calling core.dangerousclose");
return true;
}
/**
* @notice Hook to be implemented by higher-level Manager contract after closing occurs.
*/
function _onAfterClose(
bytes32 oid,
uint256 amount,
address receiver,
uint256 lessBase
) internal override returns (bool) {
(address baseToken, , , , ) = getParameters(oid);
console.log("subtracting base claim");
// Update claim for baseTokens
_collateralBalance[baseToken] -= lessBase;
console.log("pushing base tokens");
// Push base tokens
IERC20(baseToken).safeTransfer(receiver, lessBase);
return true;
}
// ===== View =====
/**
* @notice A mutex that is set when the `execute` fn is called.
* @dev Reset after execute to false.
*/
function isExecuting() public view returns (bool) {
return _EXECUTING;
}
/**
* @notice The accountNonce which is being manipulated by the currently executing `execute` fn.
* @dev Reset after execute to _NO_NONCE.
*/
function getExecutingNonce() public view returns (uint256) {
return _NONCE;
}
/**
* @notice The `msg.sender` of the `execute` fn.
* @dev Reset after execute to _NO_ADDRESS.
*/
function getExecutingCaller() public view returns (address) {
return _accounts[getExecutingNonce()].depositor;
}
/**
* @notice The venue that is the `target` address of the `execute` fn.
* @dev Reset after execute to _NO_ADDRESS.
*/
function getExecutingVenue() public view returns (address) {
return _VENUE;
}
/**
* @notice Fetches the current account nonce, which will be the nonce of the next Account.
*/
function getAccountNonce() public view returns (uint256) {
return _accountNonce;
}
/**
* @notice Fetches the Account struct objects.
*/
function getAccount(uint256 accountNonce)
public
view
returns (
address,
address,
uint256[] memory,
uint256[] memory
)
{
Account storage acc = _accounts[accountNonce];
uint256 len = acc.wrappedIds.length;
uint256[] memory balances = new uint256[](len);
for (uint256 i = 0; i < len; i++) {
balances[i] = acc.balanceOf[acc.wrappedIds[i]];
}
return (acc.depositor, acc.wrappedToken, acc.wrappedIds, balances);
}
function getDebtOf(uint256 accountNonce, address token)
public
view
returns (uint256)
{
Account storage acc = _accounts[accountNonce];
return acc.debtOf[token];
}
/**
* @notice Fetches the Accelerator contract.
* @dev Accelerator is an intemediary to execute the `execute` fn on behalf of this contract.
*/
function getAccelerator() public view returns (address) {
return address(_accelerator);
}
function getOracle() public view returns (address) {
return address(_oracle);
}
// === View Hooks ===
/**
* @notice If `_EXECUTING_SENDER` is `_NO_ADDRESS`, use Account.depositor, else use the `_VENUE`.
* @dev Overrides the virtual hook in abstract Manager contract.
*/
function _getExecutingSender() internal view override returns (address) {
return
_EXECUTING_SENDER == _NO_ADDRESS
? getExecutingCaller()
: getExecutingVenue();
}
/**
* @notice Returns true if the expiry timestamp of an option is greater than or equal to current timestamp.
* @dev Overrides the virtual hook in abstract Manager contract.
*/
function _notExpired(bytes32 oid) internal view override returns (bool) {
(, , , uint32 expiry, ) = getParameters(oid);
return expiry >= block.timestamp;
}
}
|
Hook to be implemented by higher-level Manager contract after redemption occurs./ Update claim for quoteTokens Push base tokens
|
function _onAfterRedeem(
bytes32 oid,
uint256 amount,
address receiver,
uint256 lessQuote
) internal override returns (bool) {
console.log("subtracting base claim");
(, address quoteToken, , , ) = getParameters(oid);
_collateralBalance[quoteToken] -= lessQuote;
console.log("pushing quote tokens");
IERC20(quoteToken).safeTransfer(receiver, lessQuote);
return true;
}
| 6,417,599 |
/**
*Submitted for verification at Etherscan.io on 2021-07-15
*/
// Sources flattened with hardhat v2.1.1 https://hardhat.org
// File contracts/Interfaces/IBorrowerOperations.sol
// MIT
pragma solidity 0.6.11;
// Common interface for the Trove Manager.
interface IBorrowerOperations {
// --- Events ---
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event LUSDTokenAddressChanged(address _lusdTokenAddress);
event LQTYStakingAddressChanged(address _lqtyStakingAddress);
event TroveCreated(address indexed _borrower, uint arrayIndex);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event LUSDBorrowingFeePaid(address indexed _borrower, uint _LUSDFee);
// --- Functions ---
function setAddresses(
address _troveManagerAddress,
address _activePoolAddress,
address _defaultPoolAddress,
address _stabilityPoolAddress,
address _gasPoolAddress,
address _collSurplusPoolAddress,
address _priceFeedAddress,
address _sortedTrovesAddress,
address _lusdTokenAddress,
address _lqtyStakingAddress
) external;
function openTrove(uint _maxFee, uint _LUSDAmount, address _upperHint, address _lowerHint) external payable;
function addColl(address _upperHint, address _lowerHint) external payable;
function moveETHGainToTrove(address _user, address _upperHint, address _lowerHint) external payable;
function withdrawColl(uint _amount, address _upperHint, address _lowerHint) external;
function withdrawLUSD(uint _maxFee, uint _amount, address _upperHint, address _lowerHint) external;
function repayLUSD(uint _amount, address _upperHint, address _lowerHint) external;
function closeTrove() external;
function adjustTrove(uint _maxFee, uint _collWithdrawal, uint _debtChange, bool isDebtIncrease, address _upperHint, address _lowerHint) external payable;
function claimCollateral() external;
function getCompositeDebt(uint _debt) external pure returns (uint);
}
// File contracts/Interfaces/IStabilityPool.sol
// MIT
pragma solidity 0.6.11;
/*
* The Stability Pool holds LUSD tokens deposited by Stability Pool depositors.
*
* When a trove is liquidated, then depending on system conditions, some of its LUSD debt gets offset with
* LUSD in the Stability Pool: that is, the offset debt evaporates, and an equal amount of LUSD tokens in the Stability Pool is burned.
*
* Thus, a liquidation causes each depositor to receive a LUSD loss, in proportion to their deposit as a share of total deposits.
* They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors,
* in the same proportion.
*
* When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40%
* of the total LUSD in the Stability Pool, depletes 40% of each deposit.
*
* A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit,
* multiplying it by some factor in range ]0,1[
*
* Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations:
* https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf
*
* --- LQTY ISSUANCE TO STABILITY POOL DEPOSITORS ---
*
* An LQTY issuance event occurs at every deposit operation, and every liquidation.
*
* Each deposit is tagged with the address of the front end through which it was made.
*
* All deposits earn a share of the issued LQTY in proportion to the deposit as a share of total deposits. The LQTY earned
* by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate.
*
* Please see the system Readme for an overview:
* https://github.com/liquity/dev/blob/main/README.md#lqty-issuance-to-stability-providers
*/
interface IStabilityPool {
// --- Events ---
event StabilityPoolETHBalanceUpdated(uint _newBalance);
event StabilityPoolLUSDBalanceUpdated(uint _newBalance);
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event SortedTrovesAddressChanged(address _newSortedTrovesAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress);
event P_Updated(uint _P);
event S_Updated(uint _S, uint128 _epoch, uint128 _scale);
event G_Updated(uint _G, uint128 _epoch, uint128 _scale);
event EpochUpdated(uint128 _currentEpoch);
event ScaleUpdated(uint128 _currentScale);
event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate);
event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd);
event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G);
event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G);
event UserDepositChanged(address indexed _depositor, uint _newDeposit);
event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor);
event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _LUSDLoss);
event LQTYPaidToDepositor(address indexed _depositor, uint _LQTY);
event LQTYPaidToFrontEnd(address indexed _frontEnd, uint _LQTY);
event EtherSent(address _to, uint _amount);
// --- Functions ---
/*
* Called only once on init, to set addresses of other Liquity contracts
* Callable only by owner, renounces ownership at the end
*/
function setAddresses(
address _borrowerOperationsAddress,
address _troveManagerAddress,
address _activePoolAddress,
address _lusdTokenAddress,
address _sortedTrovesAddress,
address _priceFeedAddress,
address _communityIssuanceAddress
) external;
/*
* Initial checks:
* - Frontend is registered or zero address
* - Sender is not a registered frontend
* - _amount is not zero
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Tags the deposit with the provided front end tag param, if it's a new deposit
* - Sends depositor's accumulated gains (LQTY, ETH) to depositor
* - Sends the tagged front end's accumulated LQTY gains to the tagged front end
* - Increases deposit and tagged front end's stake, and takes new snapshots for each.
*/
function provideToSP(uint _amount, address _frontEndTag) external;
/*
* Initial checks:
* - _amount is zero or there are no under collateralized troves left in the system
* - User has a non zero deposit
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Removes the deposit's front end tag if it is a full withdrawal
* - Sends all depositor's accumulated gains (LQTY, ETH) to depositor
* - Sends the tagged front end's accumulated LQTY gains to the tagged front end
* - Decreases deposit and tagged front end's stake, and takes new snapshots for each.
*
* If _amount > userDeposit, the user withdraws all of their compounded deposit.
*/
function withdrawFromSP(uint _amount) external;
/*
* Initial checks:
* - User has a non zero deposit
* - User has an open trove
* - User has some ETH gain
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Sends all depositor's LQTY gain to depositor
* - Sends all tagged front end's LQTY gain to the tagged front end
* - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove
* - Leaves their compounded deposit in the Stability Pool
* - Updates snapshots for deposit and tagged front end stake
*/
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external;
/*
* Initial checks:
* - Frontend (sender) not already registered
* - User (sender) has no deposit
* - _kickbackRate is in the range [0, 100%]
* ---
* Front end makes a one-time selection of kickback rate upon registering
*/
function registerFrontEnd(uint _kickbackRate) external;
/*
* Initial checks:
* - Caller is TroveManager
* ---
* Cancels out the specified debt against the LUSD contained in the Stability Pool (as far as possible)
* and transfers the Trove's ETH collateral from ActivePool to StabilityPool.
* Only called by liquidation functions in the TroveManager.
*/
function offset(uint _debt, uint _coll) external;
/*
* Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`,
* to exclude edge cases like ETH received from a self-destruct.
*/
function getETH() external view returns (uint);
/*
* Returns LUSD held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset.
*/
function getTotalLUSDDeposits() external view returns (uint);
/*
* Calculates the ETH gain earned by the deposit since its last snapshots were taken.
*/
function getDepositorETHGain(address _depositor) external view returns (uint);
/*
* Calculate the LQTY gain earned by a deposit since its last snapshots were taken.
* If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned.
* Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through
* which they made their deposit.
*/
function getDepositorLQTYGain(address _depositor) external view returns (uint);
/*
* Return the LQTY gain earned by the front end.
*/
function getFrontEndLQTYGain(address _frontEnd) external view returns (uint);
/*
* Return the user's compounded deposit.
*/
function getCompoundedLUSDDeposit(address _depositor) external view returns (uint);
/*
* Return the front end's compounded stake.
*
* The front end's compounded stake is equal to the sum of its depositors' compounded deposits.
*/
function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint);
/*
* Fallback function
* Only callable by Active Pool, it just accounts for ETH received
* receive() external payable;
*/
}
// File contracts/Interfaces/IPriceFeed.sol
// MIT
pragma solidity 0.6.11;
interface IPriceFeed {
// --- Events ---
event LastGoodPriceUpdated(uint _lastGoodPrice);
// --- Function ---
function fetchPrice() external returns (uint);
}
// File contracts/Interfaces/ILiquityBase.sol
// MIT
pragma solidity 0.6.11;
interface ILiquityBase {
function priceFeed() external view returns (IPriceFeed);
}
// File contracts/Dependencies/IERC20.sol
// MIT
pragma solidity 0.6.11;
/**
* Based on the OpenZeppelin IER20 interface:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol
*
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
/**
* @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);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/Dependencies/IERC2612.sol
// MIT
pragma solidity 0.6.11;
/**
* @dev Interface of the ERC2612 standard as defined in the EIP.
*
* Adds the {permit} method, which can be used to change one's
* {IERC20-allowance} without having to send a transaction, by signing a
* message. This allows users to spend tokens without having to hold Ether.
*
* See https://eips.ethereum.org/EIPS/eip-2612.
*
* Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/
*/
interface IERC2612 {
/**
* @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 amount,
uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current ERC2612 nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases `owner`'s nonce by one. This
* prevents a signature from being used multiple times.
*
* `owner` can limit the time a Permit is valid for by setting `deadline` to
* a value in the near future. The deadline argument can be set to uint(-1) to
* create Permits that effectively never expire.
*/
function nonces(address owner) external view returns (uint256);
function version() external view returns (string memory);
function permitTypeHash() external view returns (bytes32);
function domainSeparator() external view returns (bytes32);
}
// File contracts/Interfaces/ILUSDToken.sol
// MIT
pragma solidity 0.6.11;
interface ILUSDToken is IERC20, IERC2612 {
// --- Events ---
event TroveManagerAddressChanged(address _troveManagerAddress);
event StabilityPoolAddressChanged(address _newStabilityPoolAddress);
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event LUSDTokenBalanceUpdated(address _user, uint _amount);
// --- Functions ---
function mint(address _account, uint256 _amount) external;
function burn(address _account, uint256 _amount) external;
function sendToPool(address _sender, address poolAddress, uint256 _amount) external;
function returnFromPool(address poolAddress, address user, uint256 _amount ) external;
}
// File contracts/Interfaces/ILQTYToken.sol
// MIT
pragma solidity 0.6.11;
interface ILQTYToken is IERC20, IERC2612 {
// --- Events ---
event CommunityIssuanceAddressSet(address _communityIssuanceAddress);
event LQTYStakingAddressSet(address _lqtyStakingAddress);
event LockupContractFactoryAddressSet(address _lockupContractFactoryAddress);
// --- Functions ---
function sendToLQTYStaking(address _sender, uint256 _amount) external;
function getDeploymentStartTime() external view returns (uint256);
function getLpRewardsEntitlement() external view returns (uint256);
}
// File contracts/Interfaces/ILQTYStaking.sol
// MIT
pragma solidity 0.6.11;
interface ILQTYStaking {
// --- Events --
event LQTYTokenAddressSet(address _lqtyTokenAddress);
event LUSDTokenAddressSet(address _lusdTokenAddress);
event TroveManagerAddressSet(address _troveManager);
event BorrowerOperationsAddressSet(address _borrowerOperationsAddress);
event ActivePoolAddressSet(address _activePoolAddress);
event StakeChanged(address indexed staker, uint newStake);
event StakingGainsWithdrawn(address indexed staker, uint LUSDGain, uint ETHGain);
event F_ETHUpdated(uint _F_ETH);
event F_LUSDUpdated(uint _F_LUSD);
event TotalLQTYStakedUpdated(uint _totalLQTYStaked);
event EtherSent(address _account, uint _amount);
event StakerSnapshotsUpdated(address _staker, uint _F_ETH, uint _F_LUSD);
// --- Functions ---
function setAddresses
(
address _lqtyTokenAddress,
address _lusdTokenAddress,
address _troveManagerAddress,
address _borrowerOperationsAddress,
address _activePoolAddress
) external;
function stake(uint _LQTYamount) external;
function unstake(uint _LQTYamount) external;
function increaseF_ETH(uint _ETHFee) external;
function increaseF_LUSD(uint _LQTYFee) external;
function getPendingETHGain(address _user) external view returns (uint);
function getPendingLUSDGain(address _user) external view returns (uint);
}
// File contracts/Interfaces/ITroveManager.sol
// MIT
pragma solidity 0.6.11;
// Common interface for the Trove Manager.
interface ITroveManager is ILiquityBase {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event LQTYTokenAddressChanged(address _lqtyTokenAddress);
event LQTYStakingAddressChanged(address _lqtyStakingAddress);
event Liquidation(uint _liquidatedDebt, uint _liquidatedColl, uint _collGasCompensation, uint _LUSDGasCompensation);
event Redemption(uint _attemptedLUSDAmount, uint _actualLUSDAmount, uint _ETHSent, uint _ETHFee);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event TroveLiquidated(address indexed _borrower, uint _debt, uint _coll, uint8 operation);
event BaseRateUpdated(uint _baseRate);
event LastFeeOpTimeUpdated(uint _lastFeeOpTime);
event TotalStakesUpdated(uint _newTotalStakes);
event SystemSnapshotsUpdated(uint _totalStakesSnapshot, uint _totalCollateralSnapshot);
event LTermsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveSnapshotsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveIndexUpdated(address _borrower, uint _newIndex);
// --- Functions ---
function setAddresses(
address _borrowerOperationsAddress,
address _activePoolAddress,
address _defaultPoolAddress,
address _stabilityPoolAddress,
address _gasPoolAddress,
address _collSurplusPoolAddress,
address _priceFeedAddress,
address _lusdTokenAddress,
address _sortedTrovesAddress,
address _lqtyTokenAddress,
address _lqtyStakingAddress
) external;
function stabilityPool() external view returns (IStabilityPool);
function lusdToken() external view returns (ILUSDToken);
function lqtyToken() external view returns (ILQTYToken);
function lqtyStaking() external view returns (ILQTYStaking);
function getTroveOwnersCount() external view returns (uint);
function getTroveFromTroveOwnersArray(uint _index) external view returns (address);
function getNominalICR(address _borrower) external view returns (uint);
function getCurrentICR(address _borrower, uint _price) external view returns (uint);
function liquidate(address _borrower) external;
function liquidateTroves(uint _n) external;
function batchLiquidateTroves(address[] calldata _troveArray) external;
function redeemCollateral(
uint _LUSDAmount,
address _firstRedemptionHint,
address _upperPartialRedemptionHint,
address _lowerPartialRedemptionHint,
uint _partialRedemptionHintNICR,
uint _maxIterations,
uint _maxFee
) external;
function updateStakeAndTotalStakes(address _borrower) external returns (uint);
function updateTroveRewardSnapshots(address _borrower) external;
function addTroveOwnerToArray(address _borrower) external returns (uint index);
function applyPendingRewards(address _borrower) external;
function getPendingETHReward(address _borrower) external view returns (uint);
function getPendingLUSDDebtReward(address _borrower) external view returns (uint);
function hasPendingRewards(address _borrower) external view returns (bool);
function getEntireDebtAndColl(address _borrower) external view returns (
uint debt,
uint coll,
uint pendingLUSDDebtReward,
uint pendingETHReward
);
function closeTrove(address _borrower) external;
function removeStake(address _borrower) external;
function getRedemptionRate() external view returns (uint);
function getRedemptionRateWithDecay() external view returns (uint);
function getRedemptionFeeWithDecay(uint _ETHDrawn) external view returns (uint);
function getBorrowingRate() external view returns (uint);
function getBorrowingRateWithDecay() external view returns (uint);
function getBorrowingFee(uint LUSDDebt) external view returns (uint);
function getBorrowingFeeWithDecay(uint _LUSDDebt) external view returns (uint);
function decayBaseRateFromBorrowing() external;
function getTroveStatus(address _borrower) external view returns (uint);
function getTroveStake(address _borrower) external view returns (uint);
function getTroveDebt(address _borrower) external view returns (uint);
function getTroveColl(address _borrower) external view returns (uint);
function setTroveStatus(address _borrower, uint num) external;
function increaseTroveColl(address _borrower, uint _collIncrease) external returns (uint);
function decreaseTroveColl(address _borrower, uint _collDecrease) external returns (uint);
function increaseTroveDebt(address _borrower, uint _debtIncrease) external returns (uint);
function decreaseTroveDebt(address _borrower, uint _collDecrease) external returns (uint);
function getTCR(uint _price) external view returns (uint);
function checkRecoveryMode(uint _price) external view returns (bool);
}
// File contracts/Interfaces/ISortedTroves.sol
// MIT
pragma solidity 0.6.11;
// Common interface for the SortedTroves Doubly Linked List.
interface ISortedTroves {
// --- Events ---
event SortedTrovesAddressChanged(address _sortedDoublyLLAddress);
event BorrowerOperationsAddressChanged(address _borrowerOperationsAddress);
event NodeAdded(address _id, uint _NICR);
event NodeRemoved(address _id);
// --- Functions ---
function setParams(uint256 _size, address _TroveManagerAddress, address _borrowerOperationsAddress) external;
function insert(address _id, uint256 _ICR, address _prevId, address _nextId) external;
function remove(address _id) external;
function reInsert(address _id, uint256 _newICR, address _prevId, address _nextId) external;
function contains(address _id) external view returns (bool);
function isFull() external view returns (bool);
function isEmpty() external view returns (bool);
function getSize() external view returns (uint256);
function getMaxSize() external view returns (uint256);
function getFirst() external view returns (address);
function getLast() external view returns (address);
function getNext(address _id) external view returns (address);
function getPrev(address _id) external view returns (address);
function validInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (bool);
function findInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (address, address);
}
// File contracts/Interfaces/ICommunityIssuance.sol
// MIT
pragma solidity 0.6.11;
interface ICommunityIssuance {
// --- Events ---
event LQTYTokenAddressSet(address _lqtyTokenAddress);
event StabilityPoolAddressSet(address _stabilityPoolAddress);
event TotalLQTYIssuedUpdated(uint _totalLQTYIssued);
// --- Functions ---
function setAddresses(address _lqtyTokenAddress, address _stabilityPoolAddress) external;
function issueLQTY() external returns (uint);
function sendLQTY(address _account, uint _LQTYamount) external;
}
// File contracts/Dependencies/BaseMath.sol
// MIT
pragma solidity 0.6.11;
contract BaseMath {
uint constant public DECIMAL_PRECISION = 1e18;
}
// File contracts/Dependencies/SafeMath.sol
// MIT
pragma solidity 0.6.11;
/**
* Based on OpenZeppelin's SafeMath:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
*
* @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 contracts/Dependencies/console.sol
// MIT
pragma solidity 0.6.11;
// Buidler's helper contract for console logging
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function log() internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log()"));
ignored;
} function logInt(int p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(int)", p0));
ignored;
}
function logUint(uint p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint)", p0));
ignored;
}
function logString(string memory p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string)", p0));
ignored;
}
function logBool(bool p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool)", p0));
ignored;
}
function logAddress(address p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address)", p0));
ignored;
}
function logBytes(bytes memory p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes)", p0));
ignored;
}
function logByte(byte p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(byte)", p0));
ignored;
}
function logBytes1(bytes1 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes1)", p0));
ignored;
}
function logBytes2(bytes2 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes2)", p0));
ignored;
}
function logBytes3(bytes3 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes3)", p0));
ignored;
}
function logBytes4(bytes4 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes4)", p0));
ignored;
}
function logBytes5(bytes5 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes5)", p0));
ignored;
}
function logBytes6(bytes6 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes6)", p0));
ignored;
}
function logBytes7(bytes7 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes7)", p0));
ignored;
}
function logBytes8(bytes8 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes8)", p0));
ignored;
}
function logBytes9(bytes9 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes9)", p0));
ignored;
}
function logBytes10(bytes10 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes10)", p0));
ignored;
}
function logBytes11(bytes11 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes11)", p0));
ignored;
}
function logBytes12(bytes12 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes12)", p0));
ignored;
}
function logBytes13(bytes13 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes13)", p0));
ignored;
}
function logBytes14(bytes14 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes14)", p0));
ignored;
}
function logBytes15(bytes15 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes15)", p0));
ignored;
}
function logBytes16(bytes16 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes16)", p0));
ignored;
}
function logBytes17(bytes17 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes17)", p0));
ignored;
}
function logBytes18(bytes18 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes18)", p0));
ignored;
}
function logBytes19(bytes19 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes19)", p0));
ignored;
}
function logBytes20(bytes20 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes20)", p0));
ignored;
}
function logBytes21(bytes21 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes21)", p0));
ignored;
}
function logBytes22(bytes22 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes22)", p0));
ignored;
}
function logBytes23(bytes23 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes23)", p0));
ignored;
}
function logBytes24(bytes24 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes24)", p0));
ignored;
}
function logBytes25(bytes25 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes25)", p0));
ignored;
}
function logBytes26(bytes26 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes26)", p0));
ignored;
}
function logBytes27(bytes27 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes27)", p0));
ignored;
}
function logBytes28(bytes28 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes28)", p0));
ignored;
}
function logBytes29(bytes29 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes29)", p0));
ignored;
}
function logBytes30(bytes30 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes30)", p0));
ignored;
}
function logBytes31(bytes31 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes31)", p0));
ignored;
}
function logBytes32(bytes32 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes32)", p0));
ignored;
}
function log(uint p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint)", p0));
ignored;
}
function log(string memory p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string)", p0));
ignored;
}
function log(bool p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool)", p0));
ignored;
}
function log(address p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address)", p0));
ignored;
}
function log(uint p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint)", p0, p1));
ignored;
}
function log(uint p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string)", p0, p1));
ignored;
}
function log(uint p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool)", p0, p1));
ignored;
}
function log(uint p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address)", p0, p1));
ignored;
}
function log(string memory p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint)", p0, p1));
ignored;
}
function log(string memory p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string)", p0, p1));
ignored;
}
function log(string memory p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool)", p0, p1));
ignored;
}
function log(string memory p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address)", p0, p1));
ignored;
}
function log(bool p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint)", p0, p1));
ignored;
}
function log(bool p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string)", p0, p1));
ignored;
}
function log(bool p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool)", p0, p1));
ignored;
}
function log(bool p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address)", p0, p1));
ignored;
}
function log(address p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint)", p0, p1));
ignored;
}
function log(address p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string)", p0, p1));
ignored;
}
function log(address p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool)", p0, p1));
ignored;
}
function log(address p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address)", p0, p1));
ignored;
}
function log(uint p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
ignored;
}
}
// File contracts/Dependencies/LiquityMath.sol
// MIT
pragma solidity 0.6.11;
library LiquityMath {
using SafeMath for uint;
uint internal constant DECIMAL_PRECISION = 1e18;
/* Precision for Nominal ICR (independent of price). Rationale for the value:
*
* - Making it “too high” could lead to overflows.
* - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division.
*
* This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39 ETH,
* and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.
*
*/
uint internal constant NICR_PRECISION = 1e20;
function _min(uint _a, uint _b) internal pure returns (uint) {
return (_a < _b) ? _a : _b;
}
function _max(uint _a, uint _b) internal pure returns (uint) {
return (_a >= _b) ? _a : _b;
}
/*
* Multiply two decimal numbers and use normal rounding rules:
* -round product up if 19'th mantissa digit >= 5
* -round product down if 19'th mantissa digit < 5
*
* Used only inside the exponentiation, _decPow().
*/
function decMul(uint x, uint y) internal pure returns (uint decProd) {
uint prod_xy = x.mul(y);
decProd = prod_xy.add(DECIMAL_PRECISION / 2).div(DECIMAL_PRECISION);
}
/*
* _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.
*
* Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity.
*
* Called by two functions that represent time in units of minutes:
* 1) TroveManager._calcDecayedBaseRate
* 2) CommunityIssuance._getCumulativeIssuanceFraction
*
* The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals
* "minutes in 1000 years": 60 * 24 * 365 * 1000
*
* If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be
* negligibly different from just passing the cap, since:
*
* In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years
* In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible
*/
function _decPow(uint _base, uint _minutes) internal pure returns (uint) {
if (_minutes > 525600000) {_minutes = 525600000;} // cap to avoid overflow
if (_minutes == 0) {return DECIMAL_PRECISION;}
uint y = DECIMAL_PRECISION;
uint x = _base;
uint n = _minutes;
// Exponentiation-by-squaring
while (n > 1) {
if (n % 2 == 0) {
x = decMul(x, x);
n = n.div(2);
} else { // if (n % 2 != 0)
y = decMul(x, y);
x = decMul(x, x);
n = (n.sub(1)).div(2);
}
}
return decMul(x, y);
}
function _getAbsoluteDifference(uint _a, uint _b) internal pure returns (uint) {
return (_a >= _b) ? _a.sub(_b) : _b.sub(_a);
}
function _computeNominalCR(uint _coll, uint _debt) internal pure returns (uint) {
if (_debt > 0) {
return _coll.mul(NICR_PRECISION).div(_debt);
}
// Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR.
else { // if (_debt == 0)
return 2**256 - 1;
}
}
function _computeCR(uint _coll, uint _debt, uint _price) internal pure returns (uint) {
if (_debt > 0) {
uint newCollRatio = _coll.mul(_price).div(_debt);
return newCollRatio;
}
// Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR.
else { // if (_debt == 0)
return 2**256 - 1;
}
}
}
// File contracts/Interfaces/IPool.sol
// MIT
pragma solidity 0.6.11;
// Common interface for the Pools.
interface IPool {
// --- Events ---
event ETHBalanceUpdated(uint _newBalance);
event LUSDBalanceUpdated(uint _newBalance);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
event StabilityPoolAddressChanged(address _newStabilityPoolAddress);
event EtherSent(address _to, uint _amount);
// --- Functions ---
function getETH() external view returns (uint);
function getLUSDDebt() external view returns (uint);
function increaseLUSDDebt(uint _amount) external;
function decreaseLUSDDebt(uint _amount) external;
}
// File contracts/Interfaces/IActivePool.sol
// MIT
pragma solidity 0.6.11;
interface IActivePool is IPool {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolLUSDDebtUpdated(uint _LUSDDebt);
event ActivePoolETHBalanceUpdated(uint _ETH);
// --- Functions ---
function sendETH(address _account, uint _amount) external;
}
// File contracts/Interfaces/IDefaultPool.sol
// MIT
pragma solidity 0.6.11;
interface IDefaultPool is IPool {
// --- Events ---
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event DefaultPoolLUSDDebtUpdated(uint _LUSDDebt);
event DefaultPoolETHBalanceUpdated(uint _ETH);
// --- Functions ---
function sendETHToActivePool(uint _amount) external;
}
// File contracts/Dependencies/LiquityBase.sol
// MIT
pragma solidity 0.6.11;
/*
* Base contract for TroveManager, BorrowerOperations and StabilityPool. Contains global system constants and
* common functions.
*/
contract LiquityBase is BaseMath, ILiquityBase {
using SafeMath for uint;
uint constant public _100pct = 1000000000000000000; // 1e18 == 100%
// Minimum collateral ratio for individual troves
uint constant public MCR = 1100000000000000000; // 110%
// Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, Recovery Mode is triggered.
uint constant public CCR = 1500000000000000000; // 150%
// Amount of LUSD to be locked in gas pool on opening troves
uint constant public LUSD_GAS_COMPENSATION = 200e18;
// Minimum amount of net LUSD debt a trove must have
uint constant public MIN_NET_DEBT = 1800e18;
// uint constant public MIN_NET_DEBT = 0;
uint constant public PERCENT_DIVISOR = 200; // dividing by 200 yields 0.5%
uint constant public BORROWING_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 5; // 0.5%
IActivePool public activePool;
IDefaultPool public defaultPool;
IPriceFeed public override priceFeed;
// --- Gas compensation functions ---
// Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation
function _getCompositeDebt(uint _debt) internal pure returns (uint) {
return _debt.add(LUSD_GAS_COMPENSATION);
}
function _getNetDebt(uint _debt) internal pure returns (uint) {
return _debt.sub(LUSD_GAS_COMPENSATION);
}
// Return the amount of ETH to be drawn from a trove's collateral and sent as gas compensation.
function _getCollGasCompensation(uint _entireColl) internal pure returns (uint) {
return _entireColl / PERCENT_DIVISOR;
}
function getEntireSystemColl() public view returns (uint entireSystemColl) {
uint activeColl = activePool.getETH();
uint liquidatedColl = defaultPool.getETH();
return activeColl.add(liquidatedColl);
}
function getEntireSystemDebt() public view returns (uint entireSystemDebt) {
uint activeDebt = activePool.getLUSDDebt();
uint closedDebt = defaultPool.getLUSDDebt();
return activeDebt.add(closedDebt);
}
function _getTCR(uint _price) internal view returns (uint TCR) {
uint entireSystemColl = getEntireSystemColl();
uint entireSystemDebt = getEntireSystemDebt();
TCR = LiquityMath._computeCR(entireSystemColl, entireSystemDebt, _price);
return TCR;
}
function _checkRecoveryMode(uint _price) internal view returns (bool) {
uint TCR = _getTCR(_price);
return TCR < CCR;
}
function _requireUserAcceptsFee(uint _fee, uint _amount, uint _maxFeePercentage) internal pure {
uint feePercentage = _fee.mul(DECIMAL_PRECISION).div(_amount);
require(feePercentage <= _maxFeePercentage, "Fee exceeded provided maximum");
}
}
// File contracts/Dependencies/LiquitySafeMath128.sol
// MIT
pragma solidity 0.6.11;
// uint128 addition and subtraction, with overflow protection.
library LiquitySafeMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 c = a + b;
require(c >= a, "LiquitySafeMath128: addition overflow");
return c;
}
function sub(uint128 a, uint128 b) internal pure returns (uint128) {
require(b <= a, "LiquitySafeMath128: subtraction overflow");
uint128 c = a - b;
return c;
}
}
// File contracts/Dependencies/Ownable.sol
// MIT
pragma solidity 0.6.11;
/**
* Based on OpenZeppelin's Ownable contract:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
*
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*
* NOTE: This function is not safe, as it doesn’t check owner is calling it.
* Make sure you check it before calling it.
*/
function _renounceOwnership() internal {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
// File contracts/Dependencies/CheckContract.sol
// MIT
pragma solidity 0.6.11;
contract CheckContract {
/**
* Check that the account is an already deployed non-destroyed contract.
* See: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol#L12
*/
function checkContract(address _account) internal view {
require(_account != address(0), "Account cannot be zero address");
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(_account) }
require(size > 0, "Account code size cannot be zero");
}
}
// File contracts/StabilityPool.sol
// MIT
pragma solidity 0.6.11;
/*
* The Stability Pool holds LUSD tokens deposited by Stability Pool depositors.
*
* When a trove is liquidated, then depending on system conditions, some of its LUSD debt gets offset with
* LUSD in the Stability Pool: that is, the offset debt evaporates, and an equal amount of LUSD tokens in the Stability Pool is burned.
*
* Thus, a liquidation causes each depositor to receive a LUSD loss, in proportion to their deposit as a share of total deposits.
* They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors,
* in the same proportion.
*
* When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40%
* of the total LUSD in the Stability Pool, depletes 40% of each deposit.
*
* A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit,
* multiplying it by some factor in range ]0,1[
*
*
* --- IMPLEMENTATION ---
*
* We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity.
*
* When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables:
* a product P, and a sum S.
*
* A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits
* and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the
* Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively.
*
* The formula for a depositor's accumulated ETH gain is derived here:
* https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf
*
* For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool,
* and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain.
*
* Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain
* can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S.
*
* Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded
* (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S.
* Essentially, they make a fresh deposit that overwrites the old one.
*
*
* --- SCALE FACTOR ---
*
* Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[.
* Unfortunately, Solidity floor division always reaches 0, sooner or later.
*
* A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P
* to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking.
*
* So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity),
* we first multiply P by 1e9, and increment a currentScale factor by 1.
*
* The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the
* scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the
* order of 1e-9.
*
* --- EPOCHS ---
*
* Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0
* forever, and break all future reward calculations.
*
* So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1.
*
* --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS ---
*
* When a deposit is made, it gets snapshots of the currentEpoch and the currentScale.
*
* When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer,
* then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0.
*
* Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t.
* If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit
* as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion LUSD has depleted to < 1 LUSD).
*
*
* --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS ---
*
* In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch.
*
* This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH.
*
* We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula:
* e_1 = d_t * (S - S_t) / P_t
*
* and also for scale after, taking care to divide the latter by a factor of 1e9:
* e_2 = d_t * S / (P_t * 1e9)
*
* The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything.
* The deposit therefore was present for reward events from the beginning of that second scale.
*
* S_i-S_t + S_{i+1}
* .<--------.------------>
* . .
* . S_i . S_{i+1}
* <--.-------->.<----------->
* S_t. .
* <->. .
* t .
* |---+---------|-------------|-----...
* i i+1
*
* The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their
* deposit spanned one scale change. We only care about gains across one scale change, since the compounded
* deposit is defined as being 0 once it has spanned more than one scale change.
*
*
* --- UPDATING P WHEN A LIQUIDATION OCCURS ---
*
* Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations:
* https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf
*
*
* --- LQTY ISSUANCE TO STABILITY POOL DEPOSITORS ---
*
* An LQTY issuance event occurs at every deposit operation, and every liquidation.
*
* Each deposit is tagged with the address of the front end through which it was made.
*
* All deposits earn a share of the issued LQTY in proportion to the deposit as a share of total deposits. The LQTY earned
* by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate.
*
* Please see the system Readme for an overview:
* https://github.com/liquity/dev/blob/main/README.md#lqty-issuance-to-stability-providers
*
* We use the same mathematical product-sum approach to track LQTY gains for depositors, where 'G' is the sum corresponding to LQTY gains.
* The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations.
*
*/
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool {
using LiquitySafeMath128 for uint128;
string constant public NAME = "StabilityPool";
IBorrowerOperations public borrowerOperations;
ITroveManager public troveManager;
ILUSDToken public lusdToken;
// Needed to check if there are pending liquidations
ISortedTroves public sortedTroves;
ICommunityIssuance public communityIssuance;
uint256 internal ETH; // deposited ether tracker
// Tracker for LUSD held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset.
uint256 internal totalLUSDDeposits;
// --- Data structures ---
struct FrontEnd {
uint kickbackRate;
bool registered;
}
struct Deposit {
uint initialValue;
address frontEndTag;
}
struct Snapshots {
uint S;
uint P;
uint G;
uint128 scale;
uint128 epoch;
}
mapping (address => Deposit) public deposits; // depositor address -> Deposit struct
mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct
mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct
mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end
mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct
/* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit,
* after a series of liquidations have occurred, each of which cancel some LUSD debt with the deposit.
*
* During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t
* is the snapshot of P taken at the instant the deposit was made. 18-digit decimal.
*/
uint public P = DECIMAL_PRECISION;
uint public constant SCALE_FACTOR = 1e9;
// Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1
uint128 public currentScale;
// With each offset that fully empties the Pool, the epoch is incremented by 1
uint128 public currentEpoch;
/* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t
* is the depositor's snapshot of S taken at the time t when the deposit was made.
*
* The 'S' sums are stored in a nested mapping (epoch => scale => sum):
*
* - The inner mapping records the sum S at different scales
* - The outer mapping records the (scale => sum) mappings, for different epochs.
*/
mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum;
/*
* Similarly, the sum 'G' is used to calculate LQTY gains. During it's lifetime, each deposit d_t earns a LQTY gain of
* ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made.
*
* LQTY reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations.
* In each case, the LQTY reward is issued (i.e. G is updated), before other state changes are made.
*/
mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG;
// Error tracker for the error correction in the LQTY issuance calculation
uint public lastLQTYError;
// Error trackers for the error correction in the offset calculation
uint public lastETHError_Offset;
uint public lastLUSDLossError_Offset;
// --- Events ---
event StabilityPoolETHBalanceUpdated(uint _newBalance);
event StabilityPoolLUSDBalanceUpdated(uint _newBalance);
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event SortedTrovesAddressChanged(address _newSortedTrovesAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress);
event P_Updated(uint _P);
event S_Updated(uint _S, uint128 _epoch, uint128 _scale);
event G_Updated(uint _G, uint128 _epoch, uint128 _scale);
event EpochUpdated(uint128 _currentEpoch);
event ScaleUpdated(uint128 _currentScale);
event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate);
event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd);
event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G);
event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G);
event UserDepositChanged(address indexed _depositor, uint _newDeposit);
event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor);
event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _LUSDLoss);
event LQTYPaidToDepositor(address indexed _depositor, uint _LQTY);
event LQTYPaidToFrontEnd(address indexed _frontEnd, uint _LQTY);
event EtherSent(address _to, uint _amount);
// --- Contract setters ---
function setAddresses(
address _borrowerOperationsAddress,
address _troveManagerAddress,
address _activePoolAddress,
address _lusdTokenAddress,
address _sortedTrovesAddress,
address _priceFeedAddress,
address _communityIssuanceAddress
)
external
override
onlyOwner
{
checkContract(_borrowerOperationsAddress);
checkContract(_troveManagerAddress);
checkContract(_activePoolAddress);
checkContract(_lusdTokenAddress);
checkContract(_sortedTrovesAddress);
checkContract(_priceFeedAddress);
checkContract(_communityIssuanceAddress);
borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress);
troveManager = ITroveManager(_troveManagerAddress);
activePool = IActivePool(_activePoolAddress);
lusdToken = ILUSDToken(_lusdTokenAddress);
sortedTroves = ISortedTroves(_sortedTrovesAddress);
priceFeed = IPriceFeed(_priceFeedAddress);
communityIssuance = ICommunityIssuance(_communityIssuanceAddress);
emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress);
emit TroveManagerAddressChanged(_troveManagerAddress);
emit ActivePoolAddressChanged(_activePoolAddress);
emit LUSDTokenAddressChanged(_lusdTokenAddress);
emit SortedTrovesAddressChanged(_sortedTrovesAddress);
emit PriceFeedAddressChanged(_priceFeedAddress);
emit CommunityIssuanceAddressChanged(_communityIssuanceAddress);
_renounceOwnership();
}
// --- Getters for public variables. Required by IPool interface ---
function getETH() external view override returns (uint) {
return ETH;
}
function getTotalLUSDDeposits() external view override returns (uint) {
return totalLUSDDeposits;
}
// --- External Depositor Functions ---
/* provideToSP():
*
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Tags the deposit with the provided front end tag param, if it's a new deposit
* - Sends depositor's accumulated gains (LQTY, ETH) to depositor
* - Sends the tagged front end's accumulated LQTY gains to the tagged front end
* - Increases deposit and tagged front end's stake, and takes new snapshots for each.
*/
function provideToSP(uint _amount, address _frontEndTag) external override {
_requireFrontEndIsRegisteredOrZero(_frontEndTag);
_requireFrontEndNotRegistered(msg.sender);
_requireNonZeroAmount(_amount);
uint initialDeposit = deposits[msg.sender].initialValue;
ICommunityIssuance communityIssuanceCached = communityIssuance;
_triggerLQTYIssuance(communityIssuanceCached);
if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);}
uint depositorETHGain = getDepositorETHGain(msg.sender);
uint compoundedLUSDDeposit = getCompoundedLUSDDeposit(msg.sender);
uint LUSDLoss = initialDeposit.sub(compoundedLUSDDeposit); // Needed only for event log
// First pay out any LQTY gains
address frontEnd = deposits[msg.sender].frontEndTag;
_payOutLQTYGains(communityIssuanceCached, msg.sender, frontEnd);
// Update front end stake
uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd);
uint newFrontEndStake = compoundedFrontEndStake.add(_amount);
_updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake);
emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender);
_sendLUSDtoStabilityPool(msg.sender, _amount);
uint newDeposit = compoundedLUSDDeposit.add(_amount);
_updateDepositAndSnapshots(msg.sender, newDeposit);
emit UserDepositChanged(msg.sender, newDeposit);
emit ETHGainWithdrawn(msg.sender, depositorETHGain, LUSDLoss); // LUSD Loss required for event log
_sendETHGainToDepositor(depositorETHGain);
}
/* withdrawFromSP():
*
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Removes the deposit's front end tag if it is a full withdrawal
* - Sends all depositor's accumulated gains (LQTY, ETH) to depositor
* - Sends the tagged front end's accumulated LQTY gains to the tagged front end
* - Decreases deposit and tagged front end's stake, and takes new snapshots for each.
*
* If _amount > userDeposit, the user withdraws all of their compounded deposit.
*/
function withdrawFromSP(uint _amount) external override {
if (_amount !=0) {_requireNoUnderCollateralizedTroves();}
uint initialDeposit = deposits[msg.sender].initialValue;
_requireUserHasDeposit(initialDeposit);
ICommunityIssuance communityIssuanceCached = communityIssuance;
_triggerLQTYIssuance(communityIssuanceCached);
uint depositorETHGain = getDepositorETHGain(msg.sender);
uint compoundedLUSDDeposit = getCompoundedLUSDDeposit(msg.sender);
uint LUSDtoWithdraw = LiquityMath._min(_amount, compoundedLUSDDeposit);
uint LUSDLoss = initialDeposit.sub(compoundedLUSDDeposit); // Needed only for event log
// First pay out any LQTY gains
address frontEnd = deposits[msg.sender].frontEndTag;
_payOutLQTYGains(communityIssuanceCached, msg.sender, frontEnd);
// Update front end stake
uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd);
uint newFrontEndStake = compoundedFrontEndStake.sub(LUSDtoWithdraw);
_updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake);
emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender);
_sendLUSDToDepositor(msg.sender, LUSDtoWithdraw);
// Update deposit
uint newDeposit = compoundedLUSDDeposit.sub(LUSDtoWithdraw);
_updateDepositAndSnapshots(msg.sender, newDeposit);
emit UserDepositChanged(msg.sender, newDeposit);
emit ETHGainWithdrawn(msg.sender, depositorETHGain, LUSDLoss); // LUSD Loss required for event log
_sendETHGainToDepositor(depositorETHGain);
}
/* withdrawETHGainToTrove:
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Sends all depositor's LQTY gain to depositor
* - Sends all tagged front end's LQTY gain to the tagged front end
* - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove
* - Leaves their compounded deposit in the Stability Pool
* - Updates snapshots for deposit and tagged front end stake */
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override {
uint initialDeposit = deposits[msg.sender].initialValue;
_requireUserHasDeposit(initialDeposit);
_requireUserHasTrove(msg.sender);
_requireUserHasETHGain(msg.sender);
ICommunityIssuance communityIssuanceCached = communityIssuance;
_triggerLQTYIssuance(communityIssuanceCached);
uint depositorETHGain = getDepositorETHGain(msg.sender);
uint compoundedLUSDDeposit = getCompoundedLUSDDeposit(msg.sender);
uint LUSDLoss = initialDeposit.sub(compoundedLUSDDeposit); // Needed only for event log
// First pay out any LQTY gains
address frontEnd = deposits[msg.sender].frontEndTag;
_payOutLQTYGains(communityIssuanceCached, msg.sender, frontEnd);
// Update front end stake
uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd);
uint newFrontEndStake = compoundedFrontEndStake;
_updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake);
emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender);
_updateDepositAndSnapshots(msg.sender, compoundedLUSDDeposit);
/* Emit events before transferring ETH gain to Trove.
This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn
and then it is deposited into the Trove, not the other way around). */
emit ETHGainWithdrawn(msg.sender, depositorETHGain, LUSDLoss);
emit UserDepositChanged(msg.sender, compoundedLUSDDeposit);
ETH = ETH.sub(depositorETHGain);
emit StabilityPoolETHBalanceUpdated(ETH);
emit EtherSent(msg.sender, depositorETHGain);
borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint);
}
// --- LQTY issuance functions ---
function _triggerLQTYIssuance(ICommunityIssuance _communityIssuance) internal {
uint LQTYIssuance = _communityIssuance.issueLQTY();
_updateG(LQTYIssuance);
}
function _updateG(uint _LQTYIssuance) internal {
uint totalLUSD = totalLUSDDeposits; // cached to save an SLOAD
/*
* When total deposits is 0, G is not updated. In this case, the LQTY issued can not be obtained by later
* depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract.
*
*/
if (totalLUSD == 0 || _LQTYIssuance == 0) {return;}
uint LQTYPerUnitStaked;
LQTYPerUnitStaked =_computeLQTYPerUnitStaked(_LQTYIssuance, totalLUSD);
uint marginalLQTYGain = LQTYPerUnitStaked.mul(P);
epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalLQTYGain);
emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale);
}
function _computeLQTYPerUnitStaked(uint _LQTYIssuance, uint _totalLUSDDeposits) internal returns (uint) {
/*
* Calculate the LQTY-per-unit staked. Division uses a "feedback" error correction, to keep the
* cumulative error low in the running total G:
*
* 1) Form a numerator which compensates for the floor division error that occurred the last time this
* function was called.
* 2) Calculate "per-unit-staked" ratio.
* 3) Multiply the ratio back by its denominator, to reveal the current floor division error.
* 4) Store this error for use in the next correction when this function is called.
* 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended.
*/
uint LQTYNumerator = _LQTYIssuance.mul(DECIMAL_PRECISION).add(lastLQTYError);
uint LQTYPerUnitStaked = LQTYNumerator.div(_totalLUSDDeposits);
lastLQTYError = LQTYNumerator.sub(LQTYPerUnitStaked.mul(_totalLUSDDeposits));
return LQTYPerUnitStaked;
}
// --- Liquidation functions ---
/*
* Cancels out the specified debt against the LUSD contained in the Stability Pool (as far as possible)
* and transfers the Trove's ETH collateral from ActivePool to StabilityPool.
* Only called by liquidation functions in the TroveManager.
*/
function offset(uint _debtToOffset, uint _collToAdd) external override {
_requireCallerIsTroveManager();
uint totalLUSD = totalLUSDDeposits; // cached to save an SLOAD
if (totalLUSD == 0 || _debtToOffset == 0) { return; }
_triggerLQTYIssuance(communityIssuance);
(uint ETHGainPerUnitStaked,
uint LUSDLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalLUSD);
_updateRewardSumAndProduct(ETHGainPerUnitStaked, LUSDLossPerUnitStaked); // updates S and P
_moveOffsetCollAndDebt(_collToAdd, _debtToOffset);
}
// --- Offset helper functions ---
function _computeRewardsPerUnitStaked(
uint _collToAdd,
uint _debtToOffset,
uint _totalLUSDDeposits
)
internal
returns (uint ETHGainPerUnitStaked, uint LUSDLossPerUnitStaked)
{
/*
* Compute the LUSD and ETH rewards. Uses a "feedback" error correction, to keep
* the cumulative error in the P and S state variables low:
*
* 1) Form numerators which compensate for the floor division errors that occurred the last time this
* function was called.
* 2) Calculate "per-unit-staked" ratios.
* 3) Multiply each ratio back by its denominator, to reveal the current floor division error.
* 4) Store these errors for use in the next correction when this function is called.
* 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended.
*/
uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset);
assert(_debtToOffset <= _totalLUSDDeposits);
if (_debtToOffset == _totalLUSDDeposits) {
LUSDLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit
lastLUSDLossError_Offset = 0;
} else {
uint LUSDLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastLUSDLossError_Offset);
/*
* Add 1 to make error in quotient positive. We want "slightly too much" LUSD loss,
* which ensures the error in any given compoundedLUSDDeposit favors the Stability Pool.
*/
LUSDLossPerUnitStaked = (LUSDLossNumerator.div(_totalLUSDDeposits)).add(1);
lastLUSDLossError_Offset = (LUSDLossPerUnitStaked.mul(_totalLUSDDeposits)).sub(LUSDLossNumerator);
}
ETHGainPerUnitStaked = ETHNumerator.div(_totalLUSDDeposits);
lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalLUSDDeposits));
return (ETHGainPerUnitStaked, LUSDLossPerUnitStaked);
}
// Update the Stability Pool reward sum S and product P
function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _LUSDLossPerUnitStaked) internal {
uint currentP = P;
uint newP;
assert(_LUSDLossPerUnitStaked <= DECIMAL_PRECISION);
/*
* The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool LUSD in the liquidation.
* We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - LUSDLossPerUnitStaked)
*/
uint newProductFactor = uint(DECIMAL_PRECISION).sub(_LUSDLossPerUnitStaked);
uint128 currentScaleCached = currentScale;
uint128 currentEpochCached = currentEpoch;
uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached];
/*
* Calculate the new S first, before we update P.
* The ETH gain for any given depositor from a liquidation depends on the value of their deposit
* (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation.
*
* Since S corresponds to ETH gain, and P to deposit loss, we update S first.
*/
uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP);
uint newS = currentS.add(marginalETHGain);
epochToScaleToSum[currentEpochCached][currentScaleCached] = newS;
emit S_Updated(newS, currentEpochCached, currentScaleCached);
// If the Stability Pool was emptied, increment the epoch, and reset the scale and product P
if (newProductFactor == 0) {
currentEpoch = currentEpochCached.add(1);
emit EpochUpdated(currentEpoch);
currentScale = 0;
emit ScaleUpdated(currentScale);
newP = DECIMAL_PRECISION;
// If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale
} else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) {
newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION);
currentScale = currentScaleCached.add(1);
emit ScaleUpdated(currentScale);
} else {
newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION);
}
assert(newP > 0);
P = newP;
emit P_Updated(newP);
}
function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal {
IActivePool activePoolCached = activePool;
// Cancel the liquidated LUSD debt with the LUSD in the stability pool
activePoolCached.decreaseLUSDDebt(_debtToOffset);
_decreaseLUSD(_debtToOffset);
// Burn the debt that was successfully offset
lusdToken.burn(address(this), _debtToOffset);
activePoolCached.sendETH(address(this), _collToAdd);
}
function _decreaseLUSD(uint _amount) internal {
uint newTotalLUSDDeposits = totalLUSDDeposits.sub(_amount);
totalLUSDDeposits = newTotalLUSDDeposits;
emit StabilityPoolLUSDBalanceUpdated(newTotalLUSDDeposits);
}
// --- Reward calculator functions for depositor and front end ---
/* Calculates the ETH gain earned by the deposit since its last snapshots were taken.
* Given by the formula: E = d0 * (S - S(0))/P(0)
* where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively.
* d0 is the last recorded deposit value.
*/
function getDepositorETHGain(address _depositor) public view override returns (uint) {
uint initialDeposit = deposits[_depositor].initialValue;
if (initialDeposit == 0) { return 0; }
Snapshots memory snapshots = depositSnapshots[_depositor];
uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots);
return ETHGain;
}
function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) {
/*
* Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change.
* If it does, the second portion of the ETH gain is scaled by 1e9.
* If the gain spans no scale change, the second portion will be 0.
*/
uint128 epochSnapshot = snapshots.epoch;
uint128 scaleSnapshot = snapshots.scale;
uint S_Snapshot = snapshots.S;
uint P_Snapshot = snapshots.P;
uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot);
uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR);
uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION);
return ETHGain;
}
/*
* Calculate the LQTY gain earned by a deposit since its last snapshots were taken.
* Given by the formula: LQTY = d0 * (G - G(0))/P(0)
* where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively.
* d0 is the last recorded deposit value.
*/
function getDepositorLQTYGain(address _depositor) public view override returns (uint) {
uint initialDeposit = deposits[_depositor].initialValue;
if (initialDeposit == 0) {return 0;}
address frontEndTag = deposits[_depositor].frontEndTag;
/*
* If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned.
* Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through
* which they made their deposit.
*/
uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate;
Snapshots memory snapshots = depositSnapshots[_depositor];
uint LQTYGain = kickbackRate.mul(_getLQTYGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION);
return LQTYGain;
}
/*
* Return the LQTY gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0)
* where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively.
*
* D0 is the last recorded value of the front end's total tagged deposits.
*/
function getFrontEndLQTYGain(address _frontEnd) public view override returns (uint) {
uint frontEndStake = frontEndStakes[_frontEnd];
if (frontEndStake == 0) { return 0; }
uint kickbackRate = frontEnds[_frontEnd].kickbackRate;
uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate);
Snapshots memory snapshots = frontEndSnapshots[_frontEnd];
uint LQTYGain = frontEndShare.mul(_getLQTYGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION);
return LQTYGain;
}
function _getLQTYGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) {
/*
* Grab the sum 'G' from the epoch at which the stake was made. The LQTY gain may span up to one scale change.
* If it does, the second portion of the LQTY gain is scaled by 1e9.
* If the gain spans no scale change, the second portion will be 0.
*/
uint128 epochSnapshot = snapshots.epoch;
uint128 scaleSnapshot = snapshots.scale;
uint G_Snapshot = snapshots.G;
uint P_Snapshot = snapshots.P;
uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot);
uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR);
uint LQTYGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION);
return LQTYGain;
}
// --- Compounded deposit and compounded front end stake ---
/*
* Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0)
* where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit.
*/
function getCompoundedLUSDDeposit(address _depositor) public view override returns (uint) {
uint initialDeposit = deposits[_depositor].initialValue;
if (initialDeposit == 0) { return 0; }
Snapshots memory snapshots = depositSnapshots[_depositor];
uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots);
return compoundedDeposit;
}
/*
* Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0)
* where P(0) is the depositor's snapshot of the product P, taken at the last time
* when one of the front end's tagged deposits updated their deposit.
*
* The front end's compounded stake is equal to the sum of its depositors' compounded deposits.
*/
function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) {
uint frontEndStake = frontEndStakes[_frontEnd];
if (frontEndStake == 0) { return 0; }
Snapshots memory snapshots = frontEndSnapshots[_frontEnd];
uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots);
return compoundedFrontEndStake;
}
// Internal function, used to calculcate compounded deposits and compounded front end stakes.
function _getCompoundedStakeFromSnapshots(
uint initialStake,
Snapshots memory snapshots
)
internal
view
returns (uint)
{
uint snapshot_P = snapshots.P;
uint128 scaleSnapshot = snapshots.scale;
uint128 epochSnapshot = snapshots.epoch;
// If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0
if (epochSnapshot < currentEpoch) { return 0; }
uint compoundedStake;
uint128 scaleDiff = currentScale.sub(scaleSnapshot);
/* Compute the compounded stake. If a scale change in P was made during the stake's lifetime,
* account for it. If more than one scale change was made, then the stake has decreased by a factor of
* at least 1e-9 -- so return 0.
*/
if (scaleDiff == 0) {
compoundedStake = initialStake.mul(P).div(snapshot_P);
} else if (scaleDiff == 1) {
compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR);
} else { // if scaleDiff >= 2
compoundedStake = 0;
}
/*
* If compounded deposit is less than a billionth of the initial deposit, return 0.
*
* NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error
* corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less
* than it's theoretical value.
*
* Thus it's unclear whether this line is still really needed.
*/
if (compoundedStake < initialStake.div(1e9)) {return 0;}
return compoundedStake;
}
// --- Sender functions for LUSD deposit, ETH gains and LQTY gains ---
// Transfer the LUSD tokens from the user to the Stability Pool's address, and update its recorded LUSD
function _sendLUSDtoStabilityPool(address _address, uint _amount) internal {
lusdToken.sendToPool(_address, address(this), _amount);
uint newTotalLUSDDeposits = totalLUSDDeposits.add(_amount);
totalLUSDDeposits = newTotalLUSDDeposits;
emit StabilityPoolLUSDBalanceUpdated(newTotalLUSDDeposits);
}
function _sendETHGainToDepositor(uint _amount) internal {
if (_amount == 0) {return;}
uint newETH = ETH.sub(_amount);
ETH = newETH;
emit StabilityPoolETHBalanceUpdated(newETH);
emit EtherSent(msg.sender, _amount);
(bool success, ) = msg.sender.call{ value: _amount }("");
require(success, "StabilityPool: sending ETH failed");
}
// Send LUSD to user and decrease LUSD in Pool
function _sendLUSDToDepositor(address _depositor, uint LUSDWithdrawal) internal {
if (LUSDWithdrawal == 0) {return;}
lusdToken.returnFromPool(address(this), _depositor, LUSDWithdrawal);
_decreaseLUSD(LUSDWithdrawal);
}
// --- External Front End functions ---
// Front end makes a one-time selection of kickback rate upon registering
function registerFrontEnd(uint _kickbackRate) external override {
_requireFrontEndNotRegistered(msg.sender);
_requireUserHasNoDeposit(msg.sender);
_requireValidKickbackRate(_kickbackRate);
frontEnds[msg.sender].kickbackRate = _kickbackRate;
frontEnds[msg.sender].registered = true;
emit FrontEndRegistered(msg.sender, _kickbackRate);
}
// --- Stability Pool Deposit Functionality ---
function _setFrontEndTag(address _depositor, address _frontEndTag) internal {
deposits[_depositor].frontEndTag = _frontEndTag;
emit FrontEndTagSet(_depositor, _frontEndTag);
}
function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal {
deposits[_depositor].initialValue = _newValue;
if (_newValue == 0) {
delete deposits[_depositor].frontEndTag;
delete depositSnapshots[_depositor];
emit DepositSnapshotUpdated(_depositor, 0, 0, 0);
return;
}
uint128 currentScaleCached = currentScale;
uint128 currentEpochCached = currentEpoch;
uint currentP = P;
// Get S and G for the current epoch and current scale
uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached];
uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached];
// Record new snapshots of the latest running product P, sum S, and sum G, for the depositor
depositSnapshots[_depositor].P = currentP;
depositSnapshots[_depositor].S = currentS;
depositSnapshots[_depositor].G = currentG;
depositSnapshots[_depositor].scale = currentScaleCached;
depositSnapshots[_depositor].epoch = currentEpochCached;
emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG);
}
function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal {
frontEndStakes[_frontEnd] = _newValue;
if (_newValue == 0) {
delete frontEndSnapshots[_frontEnd];
emit FrontEndSnapshotUpdated(_frontEnd, 0, 0);
return;
}
uint128 currentScaleCached = currentScale;
uint128 currentEpochCached = currentEpoch;
uint currentP = P;
// Get G for the current epoch and current scale
uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached];
// Record new snapshots of the latest running product P and sum G for the front end
frontEndSnapshots[_frontEnd].P = currentP;
frontEndSnapshots[_frontEnd].G = currentG;
frontEndSnapshots[_frontEnd].scale = currentScaleCached;
frontEndSnapshots[_frontEnd].epoch = currentEpochCached;
emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG);
}
function _payOutLQTYGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal {
// Pay out front end's LQTY gain
if (_frontEnd != address(0)) {
uint frontEndLQTYGain = getFrontEndLQTYGain(_frontEnd);
_communityIssuance.sendLQTY(_frontEnd, frontEndLQTYGain);
emit LQTYPaidToFrontEnd(_frontEnd, frontEndLQTYGain);
}
// Pay out depositor's LQTY gain
uint depositorLQTYGain = getDepositorLQTYGain(_depositor);
_communityIssuance.sendLQTY(_depositor, depositorLQTYGain);
emit LQTYPaidToDepositor(_depositor, depositorLQTYGain);
}
// --- 'require' functions ---
function _requireCallerIsActivePool() internal view {
require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool");
}
function _requireCallerIsTroveManager() internal view {
require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager");
}
function _requireNoUnderCollateralizedTroves() internal {
uint price = priceFeed.fetchPrice();
address lowestTrove = sortedTroves.getLast();
uint ICR = troveManager.getCurrentICR(lowestTrove, price);
require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR");
}
function _requireUserHasDeposit(uint _initialDeposit) internal pure {
require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit');
}
function _requireUserHasNoDeposit(address _address) internal view {
uint initialDeposit = deposits[_address].initialValue;
require(initialDeposit == 0, 'StabilityPool: User must have no deposit');
}
function _requireNonZeroAmount(uint _amount) internal pure {
require(_amount > 0, 'StabilityPool: Amount must be non-zero');
}
function _requireUserHasTrove(address _depositor) internal view {
require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to");
}
function _requireUserHasETHGain(address _depositor) internal view {
uint ETHGain = getDepositorETHGain(_depositor);
require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain");
}
function _requireFrontEndNotRegistered(address _address) internal view {
require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end");
}
function _requireFrontEndIsRegisteredOrZero(address _address) internal view {
require(frontEnds[_address].registered || _address == address(0),
"StabilityPool: Tag must be a registered front end, or the zero address");
}
function _requireValidKickbackRate(uint _kickbackRate) internal pure {
require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]");
}
// --- Fallback function ---
receive() external payable {
_requireCallerIsActivePool();
ETH = ETH.add(msg.value);
StabilityPoolETHBalanceUpdated(ETH);
}
}
// File contracts/B.Protocol/crop.sol
// AGPL-3.0-or-later
// Copyright (C) 2021 Dai Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity 0.6.11;
interface VatLike {
function urns(bytes32, address) external view returns (uint256, uint256);
function gem(bytes32, address) external view returns (uint256);
function slip(bytes32, address, int256) external;
}
interface ERC20 {
function balanceOf(address owner) external view returns (uint256);
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(address src, address dst, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function decimals() external returns (uint8);
}
// receives tokens and shares them among holders
contract CropJoin {
VatLike public immutable vat; // cdp engine
bytes32 public immutable ilk; // collateral type
ERC20 public immutable gem; // collateral token
uint256 public immutable dec; // gem decimals
ERC20 public immutable bonus; // rewards token
uint256 public share; // crops per gem [ray]
uint256 public total; // total gems [wad]
uint256 public stock; // crop balance [wad]
mapping (address => uint256) public crops; // crops per user [wad]
mapping (address => uint256) public stake; // gems per user [wad]
uint256 immutable internal to18ConversionFactor;
uint256 immutable internal toGemConversionFactor;
// --- Events ---
event Join(uint256 val);
event Exit(uint256 val);
event Flee();
event Tack(address indexed src, address indexed dst, uint256 wad);
constructor(address vat_, bytes32 ilk_, address gem_, address bonus_) public {
vat = VatLike(vat_);
ilk = ilk_;
gem = ERC20(gem_);
uint256 dec_ = ERC20(gem_).decimals();
require(dec_ <= 18);
dec = dec_;
to18ConversionFactor = 10 ** (18 - dec_);
toGemConversionFactor = 10 ** dec_;
bonus = ERC20(bonus_);
}
function add(uint256 x, uint256 y) public pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) public pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) public pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function divup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(x, sub(y, 1)) / y;
}
uint256 constant WAD = 10 ** 18;
function wmul(uint256 x, uint256 y) public pure returns (uint256 z) {
z = mul(x, y) / WAD;
}
function wdiv(uint256 x, uint256 y) public pure returns (uint256 z) {
z = mul(x, WAD) / y;
}
function wdivup(uint256 x, uint256 y) public pure returns (uint256 z) {
z = divup(mul(x, WAD), y);
}
uint256 constant RAY = 10 ** 27;
function rmul(uint256 x, uint256 y) public pure returns (uint256 z) {
z = mul(x, y) / RAY;
}
function rmulup(uint256 x, uint256 y) public pure returns (uint256 z) {
z = divup(mul(x, y), RAY);
}
function rdiv(uint256 x, uint256 y) public pure returns (uint256 z) {
z = mul(x, RAY) / y;
}
// Net Asset Valuation [wad]
function nav() public virtual returns (uint256) {
uint256 _nav = gem.balanceOf(address(this));
return mul(_nav, to18ConversionFactor);
}
// Net Assets per Share [wad]
function nps() public returns (uint256) {
if (total == 0) return WAD;
else return wdiv(nav(), total);
}
function crop() internal virtual returns (uint256) {
return sub(bonus.balanceOf(address(this)), stock);
}
function harvest(address from, address to) internal {
if (total > 0) share = add(share, rdiv(crop(), total));
uint256 last = crops[from];
uint256 curr = rmul(stake[from], share);
if (curr > last) require(bonus.transfer(to, curr - last));
stock = bonus.balanceOf(address(this));
}
function join(address urn, uint256 val) internal virtual {
harvest(urn, urn);
if (val > 0) {
uint256 wad = wdiv(mul(val, to18ConversionFactor), nps());
// Overflow check for int256(wad) cast below
// Also enforces a non-zero wad
require(int256(wad) > 0);
require(gem.transferFrom(msg.sender, address(this), val));
vat.slip(ilk, urn, int256(wad));
total = add(total, wad);
stake[urn] = add(stake[urn], wad);
}
crops[urn] = rmulup(stake[urn], share);
emit Join(val);
}
function exit(address guy, uint256 val) internal virtual {
harvest(msg.sender, guy);
if (val > 0) {
uint256 wad = wdivup(mul(val, to18ConversionFactor), nps());
// Overflow check for int256(wad) cast below
// Also enforces a non-zero wad
require(int256(wad) > 0);
require(gem.transfer(guy, val));
vat.slip(ilk, msg.sender, -int256(wad));
total = sub(total, wad);
stake[msg.sender] = sub(stake[msg.sender], wad);
}
crops[msg.sender] = rmulup(stake[msg.sender], share);
emit Exit(val);
}
}
// File contracts/B.Protocol/CropJoinAdapter.sol
// MIT
pragma solidity 0.6.11;
// NOTE! - this is not an ERC20 token. transfer is not supported.
contract CropJoinAdapter is CropJoin {
string constant public name = "B.AMM LUSD-ETH";
string constant public symbol = "LUSDETH";
uint constant public decimals = 18;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
constructor(address _lqty) public
CropJoin(address(new Dummy()), "B.AMM", address(new DummyGem()), _lqty)
{
}
// adapter to cropjoin
function nav() public override returns (uint256) {
return total;
}
function totalSupply() public view returns (uint256) {
return total;
}
function balanceOf(address owner) public view returns (uint256 balance) {
balance = stake[owner];
}
function mint(address to, uint value) virtual internal {
join(to, value);
emit Transfer(address(0), to, value);
}
function burn(address owner, uint value) virtual internal {
exit(owner, value);
emit Transfer(owner, address(0), value);
}
}
contract Dummy {
fallback() external {}
}
contract DummyGem is Dummy {
function transfer(address, uint) external pure returns(bool) {
return true;
}
function transferFrom(address, address, uint) external pure returns(bool) {
return true;
}
function decimals() external pure returns(uint) {
return 18;
}
}
// File contracts/B.Protocol/PriceFormula.sol
// MIT
pragma solidity 0.6.11;
contract PriceFormula {
using SafeMath for uint256;
function getSumFixedPoint(uint x, uint y, uint A) public pure returns(uint) {
if(x == 0 && y == 0) return 0;
uint sum = x.add(y);
for(uint i = 0 ; i < 255 ; i++) {
uint dP = sum;
dP = dP.mul(sum) / (x.mul(2)).add(1);
dP = dP.mul(sum) / (y.mul(2)).add(1);
uint prevSum = sum;
uint n = (A.mul(2).mul(x.add(y)).add(dP.mul(2))).mul(sum);
uint d = (A.mul(2).sub(1).mul(sum));
sum = n / d.add(dP.mul(3));
if(sum <= prevSum.add(1) && prevSum <= sum.add(1)) break;
}
return sum;
}
function getReturn(uint xQty, uint xBalance, uint yBalance, uint A) public pure returns(uint) {
uint sum = getSumFixedPoint(xBalance, yBalance, A);
uint c = sum.mul(sum) / (xQty.add(xBalance)).mul(2);
c = c.mul(sum) / A.mul(4);
uint b = (xQty.add(xBalance)).add(sum / A.mul(2));
uint yPrev = 0;
uint y = sum;
for(uint i = 0 ; i < 255 ; i++) {
yPrev = y;
uint n = (y.mul(y)).add(c);
uint d = y.mul(2).add(b).sub(sum);
y = n / d;
if(y <= yPrev.add(1) && yPrev <= y.add(1)) break;
}
return yBalance.sub(y).sub(1);
}
}
// File contracts/Dependencies/AggregatorV3Interface.sol
// MIT
// Code from https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol
pragma solidity 0.6.11;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File contracts/B.Protocol/BAMM.sol
// MIT
pragma solidity 0.6.11;
contract BAMM is CropJoinAdapter, PriceFormula, Ownable {
using SafeMath for uint256;
AggregatorV3Interface public immutable priceAggregator;
IERC20 public immutable LUSD;
StabilityPool immutable public SP;
address payable public immutable feePool;
uint public constant MAX_FEE = 100; // 1%
uint public fee = 0; // fee in bps
uint public A = 20;
uint public constant MIN_A = 20;
uint public constant MAX_A = 200;
uint public immutable maxDiscount; // max discount in bips
address public immutable frontEndTag;
uint constant public PRECISION = 1e18;
event ParamsSet(uint A, uint fee);
event UserDeposit(address indexed user, uint lusdAmount, uint numShares);
event UserWithdraw(address indexed user, uint lusdAmount, uint ethAmount, uint numShares);
event RebalanceSwap(address indexed user, uint lusdAmount, uint ethAmount, uint timestamp);
constructor(
address _priceAggregator,
address payable _SP,
address _LUSD,
address _LQTY,
uint _maxDiscount,
address payable _feePool,
address _fronEndTag)
public
CropJoinAdapter(_LQTY)
{
priceAggregator = AggregatorV3Interface(_priceAggregator);
LUSD = IERC20(_LUSD);
SP = StabilityPool(_SP);
feePool = _feePool;
maxDiscount = _maxDiscount;
frontEndTag = _fronEndTag;
}
function setParams(uint _A, uint _fee) external onlyOwner {
require(_fee <= MAX_FEE, "setParams: fee is too big");
require(_A >= MIN_A, "setParams: A too small");
require(_A <= MAX_A, "setParams: A too big");
fee = _fee;
A = _A;
emit ParamsSet(_A, _fee);
}
function fetchPrice() public view returns(uint) {
uint chainlinkDecimals;
uint chainlinkLatestAnswer;
uint chainlinkTimestamp;
// First, try to get current decimal precision:
try priceAggregator.decimals() returns (uint8 decimals) {
// If call to Chainlink succeeds, record the current decimal precision
chainlinkDecimals = decimals;
} catch {
// If call to Chainlink aggregator reverts, return a zero response with success = false
return 0;
}
// Secondly, try to get latest price data:
try priceAggregator.latestRoundData() returns
(
uint80 /* roundId */,
int256 answer,
uint256 /* startedAt */,
uint256 timestamp,
uint80 /* answeredInRound */
)
{
// If call to Chainlink succeeds, return the response and success = true
chainlinkLatestAnswer = uint(answer);
chainlinkTimestamp = timestamp;
} catch {
// If call to Chainlink aggregator reverts, return a zero response with success = false
return 0;
}
if(chainlinkTimestamp + 1 hours < now) return 0; // price is down
uint chainlinkFactor = 10 ** chainlinkDecimals;
return chainlinkLatestAnswer.mul(PRECISION) / chainlinkFactor;
}
function deposit(uint lusdAmount) external {
// update share
uint lusdValue = SP.getCompoundedLUSDDeposit(address(this));
uint ethValue = SP.getDepositorETHGain(address(this)).add(address(this).balance);
uint price = fetchPrice();
require(ethValue == 0 || price > 0, "deposit: chainlink is down");
uint totalValue = lusdValue.add(ethValue.mul(price) / PRECISION);
// this is in theory not reachable. if it is, better halt deposits
// the condition is equivalent to: (totalValue = 0) ==> (total = 0)
require(totalValue > 0 || total == 0, "deposit: system is rekt");
uint newShare = PRECISION;
if(total > 0) newShare = total.mul(lusdAmount) / totalValue;
// deposit
require(LUSD.transferFrom(msg.sender, address(this), lusdAmount), "deposit: transferFrom failed");
SP.provideToSP(lusdAmount, frontEndTag);
// update LP token
mint(msg.sender, newShare);
emit UserDeposit(msg.sender, lusdAmount, newShare);
}
function withdraw(uint numShares) external {
uint lusdValue = SP.getCompoundedLUSDDeposit(address(this));
uint ethValue = SP.getDepositorETHGain(address(this)).add(address(this).balance);
uint lusdAmount = lusdValue.mul(numShares).div(total);
uint ethAmount = ethValue.mul(numShares).div(total);
// this withdraws lusd, lqty, and eth
SP.withdrawFromSP(lusdAmount);
// update LP token
burn(msg.sender, numShares);
// send lusd and eth
if(lusdAmount > 0) LUSD.transfer(msg.sender, lusdAmount);
if(ethAmount > 0) {
(bool success, ) = msg.sender.call{ value: ethAmount }(""); // re-entry is fine here
require(success, "withdraw: sending ETH failed");
}
emit UserWithdraw(msg.sender, lusdAmount, ethAmount, numShares);
}
function addBps(uint n, int bps) internal pure returns(uint) {
require(bps <= 10000, "reduceBps: bps exceeds max");
require(bps >= -10000, "reduceBps: bps exceeds min");
return n.mul(uint(10000 + bps)) / 10000;
}
function getSwapEthAmount(uint lusdQty) public view returns(uint ethAmount, uint feeEthAmount) {
uint lusdBalance = SP.getCompoundedLUSDDeposit(address(this));
uint ethBalance = SP.getDepositorETHGain(address(this)).add(address(this).balance);
uint eth2usdPrice = fetchPrice();
if(eth2usdPrice == 0) return (0, 0); // chainlink is down
uint ethUsdValue = ethBalance.mul(eth2usdPrice) / PRECISION;
uint maxReturn = addBps(lusdQty.mul(PRECISION) / eth2usdPrice, int(maxDiscount));
uint xQty = lusdQty;
uint xBalance = lusdBalance;
uint yBalance = lusdBalance.add(ethUsdValue.mul(2));
uint usdReturn = getReturn(xQty, xBalance, yBalance, A);
uint basicEthReturn = usdReturn.mul(PRECISION) / eth2usdPrice;
if(ethBalance < basicEthReturn) basicEthReturn = ethBalance; // cannot give more than balance
if(maxReturn < basicEthReturn) basicEthReturn = maxReturn;
ethAmount = addBps(basicEthReturn, -int(fee));
feeEthAmount = basicEthReturn.sub(ethAmount);
}
// get ETH in return to LUSD
function swap(uint lusdAmount, uint minEthReturn, address payable dest) public returns(uint) {
(uint ethAmount, uint feeAmount) = getSwapEthAmount(lusdAmount);
require(ethAmount >= minEthReturn, "swap: low return");
LUSD.transferFrom(msg.sender, address(this), lusdAmount);
SP.provideToSP(lusdAmount, frontEndTag);
if(feeAmount > 0) feePool.transfer(feeAmount);
(bool success, ) = dest.call{ value: ethAmount }(""); // re-entry is fine here
require(success, "swap: sending ETH failed");
emit RebalanceSwap(msg.sender, lusdAmount, ethAmount, now);
return ethAmount;
}
// kyber network reserve compatible function
function trade(
IERC20 /* srcToken */,
uint256 srcAmount,
IERC20 /* destToken */,
address payable destAddress,
uint256 /* conversionRate */,
bool /* validate */
) external payable returns (bool) {
return swap(srcAmount, 0, destAddress) > 0;
}
function getConversionRate(
IERC20 /* src */,
IERC20 /* dest */,
uint256 srcQty,
uint256 /* blockNumber */
) external view returns (uint256) {
(uint ethQty, ) = getSwapEthAmount(srcQty);
return ethQty.mul(PRECISION) / srcQty;
}
receive() external payable {}
}
// File contracts/B.Protocol/BLens.sol
// MIT
pragma solidity 0.6.11;
contract BLens {
function add(uint256 x, uint256 y) public pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) public pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) public pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function divup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(x, sub(y, 1)) / y;
}
uint256 constant WAD = 10 ** 18;
function wmul(uint256 x, uint256 y) public pure returns (uint256 z) {
z = mul(x, y) / WAD;
}
function wdiv(uint256 x, uint256 y) public pure returns (uint256 z) {
z = mul(x, WAD) / y;
}
function wdivup(uint256 x, uint256 y) public pure returns (uint256 z) {
z = divup(mul(x, WAD), y);
}
uint256 constant RAY = 10 ** 27;
function rmul(uint256 x, uint256 y) public pure returns (uint256 z) {
z = mul(x, y) / RAY;
}
function rmulup(uint256 x, uint256 y) public pure returns (uint256 z) {
z = divup(mul(x, y), RAY);
}
function rdiv(uint256 x, uint256 y) public pure returns (uint256 z) {
z = mul(x, RAY) / y;
}
function getUnclaimedLqty(address user, BAMM bamm, ERC20 token) external returns(uint) {
// trigger bamm (p)lqty claim
bamm.withdraw(0);
if(bamm.total() == 0) return 0;
// duplicate harvest logic
uint crop = sub(token.balanceOf(address(bamm)), bamm.stock());
uint share = add(bamm.share(), rdiv(crop, bamm.total()));
uint last = bamm.crops(user);
uint curr = rmul(bamm.stake(user), share);
if(curr > last) return curr - last;
return 0;
}
}
|
trigger bamm (p)lqty claim duplicate harvest logic
|
function getUnclaimedLqty(address user, BAMM bamm, ERC20 token) external returns(uint) {
bamm.withdraw(0);
if(bamm.total() == 0) return 0;
uint crop = sub(token.balanceOf(address(bamm)), bamm.stock());
uint share = add(bamm.share(), rdiv(crop, bamm.total()));
uint last = bamm.crops(user);
uint curr = rmul(bamm.stake(user), share);
if(curr > last) return curr - last;
return 0;
}
| 11,856,180 |
./full_match/43114/0x9cFfe34Cd34537a95Ff1bd0816C443c6482E9B71/sources/VAXPATToken.sol
|
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
|
function tryMul(uint256 a, uint256 b) internal pure returns(bool, uint256) {
unchecked {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
| 4,643,065 |
/**
*Submitted for verification at BscScan.com on 2021-10-28
*/
/**
*Submitted for verification at arbiscan.io on 2021-09-22
*/
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.2;
interface ISushiswapV2Pair {
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;
}
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMathSushiswap {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
library SushiswapV2Library {
using SafeMathSushiswap for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'SushiswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'SushiswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint160(uint256(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303' // init code hash
)))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = ISushiswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'SushiswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'SushiswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'SushiswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'SushiswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'SushiswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'SushiswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'SushiswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'SushiswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// helper methods for interacting with ERC20 tokens and sending NATIVE that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferNative(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: NATIVE_TRANSFER_FAILED');
}
}
interface ISushiswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setMigrator(address) external;
}
interface IwNATIVE {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
interface AnyswapV1ERC20 {
function mint(address to, uint256 amount) external returns (bool);
function burn(address from, uint256 amount) external returns (bool);
function changeVault(address newVault) external returns (bool);
function depositVault(uint amount, address to) external returns (uint);
function withdrawVault(address from, uint amount, address to) external returns (uint);
function underlying() external view returns (address);
function deposit(uint amount, address to) external returns (uint);
function withdraw(uint amount, address to) external returns (uint);
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
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 callOptionalReturn(IERC20 token, bytes memory data) private {
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");
}
}
}
contract AnyswapV3Router {
using SafeERC20 for IERC20;
using SafeMathSushiswap for uint;
address public immutable factory;
address public immutable wNATIVE;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'AnyswapV3Router: EXPIRED');
_;
}
constructor(address _factory, address _wNATIVE, address _mpc) {
_newMPC = _mpc;
_newMPCEffectiveTime = block.timestamp;
factory = _factory;
wNATIVE = _wNATIVE;
}
receive() external payable {
assert(msg.sender == wNATIVE); // only accept Native via fallback from the wNative contract
}
address private _oldMPC;
address private _newMPC;
uint256 private _newMPCEffectiveTime;
event LogChangeMPC(address indexed oldMPC, address indexed newMPC, uint indexed effectiveTime, uint chainID);
event LogChangeRouter(address indexed oldRouter, address indexed newRouter, uint chainID);
event LogAnySwapIn(bytes32 indexed txhash, address indexed token, address indexed to, uint amount, uint fromChainID, uint toChainID);
event LogAnySwapOut(address indexed token, address indexed from, address indexed to, uint amount, uint fromChainID, uint toChainID);
event LogAnySwapTradeTokensForTokens(address[] path, address indexed from, address indexed to, uint amountIn, uint amountOutMin, uint fromChainID, uint toChainID);
event LogAnySwapTradeTokensForNative(address[] path, address indexed from, address indexed to, uint amountIn, uint amountOutMin, uint fromChainID, uint toChainID);
modifier onlyMPC() {
require(msg.sender == mpc(), "AnyswapV3Router: FORBIDDEN");
_;
}
function mpc() public view returns (address) {
if (block.timestamp >= _newMPCEffectiveTime) {
return _newMPC;
}
return _oldMPC;
}
function cID() public view returns (uint id) {
assembly {id := chainid()}
}
function changeMPC(address newMPC) public onlyMPC returns (bool) {
require(newMPC != address(0), "AnyswapV3Router: address(0x0)");
_oldMPC = mpc();
_newMPC = newMPC;
_newMPCEffectiveTime = block.timestamp + 2*24*3600;
emit LogChangeMPC(_oldMPC, _newMPC, _newMPCEffectiveTime, cID());
return true;
}
function changeVault(address token, address newVault) public onlyMPC returns (bool) {
require(newVault != address(0), "AnyswapV3Router: address(0x0)");
return AnyswapV1ERC20(token).changeVault(newVault);
}
function _anySwapOut(address from, address token, address to, uint amount, uint toChainID) internal {
AnyswapV1ERC20(token).burn(from, amount);
emit LogAnySwapOut(token, from, to, amount, cID(), toChainID);
}
// Swaps `amount` `token` from this chain to `toChainID` chain with recipient `to`
function anySwapOut(address token, address to, uint amount, uint toChainID) external {
_anySwapOut(msg.sender, token, to, amount, toChainID);
}
// Swaps `amount` `token` from this chain to `toChainID` chain with recipient `to` by minting with `underlying`
function anySwapOutUnderlying(address token, address to, uint amount, uint toChainID) external {
IERC20(AnyswapV1ERC20(token).underlying()).safeTransferFrom(msg.sender, token, amount);
AnyswapV1ERC20(token).depositVault(amount, msg.sender);
_anySwapOut(msg.sender, token, to, amount, toChainID);
}
function anySwapOutNative(address token, address to, uint toChainID) external payable {
require(AnyswapV1ERC20(token).underlying() == wNATIVE, "AnyswapV3Router: underlying is not wNATIVE");
IwNATIVE(wNATIVE).deposit{value: msg.value}();
assert(IwNATIVE(wNATIVE).transfer(token, msg.value));
AnyswapV1ERC20(token).depositVault(msg.value, msg.sender);
_anySwapOut(msg.sender, token, to, msg.value, toChainID);
}
function anySwapOutUnderlyingWithPermit(
address from,
address token,
address to,
uint amount,
uint deadline,
uint8 v,
bytes32 r,
bytes32 s,
uint toChainID
) external {
address _underlying = AnyswapV1ERC20(token).underlying();
IERC20(_underlying).permit(from, address(this), amount, deadline, v, r, s);
IERC20(_underlying).safeTransferFrom(from, token, amount);
AnyswapV1ERC20(token).depositVault(amount, from);
_anySwapOut(from, token, to, amount, toChainID);
}
function anySwapOutUnderlyingWithTransferPermit(
address from,
address token,
address to,
uint amount,
uint deadline,
uint8 v,
bytes32 r,
bytes32 s,
uint toChainID
) external {
IERC20(AnyswapV1ERC20(token).underlying()).transferWithPermit(from, token, amount, deadline, v, r, s);
AnyswapV1ERC20(token).depositVault(amount, from);
_anySwapOut(from, token, to, amount, toChainID);
}
function anySwapOut(address[] calldata tokens, address[] calldata to, uint[] calldata amounts, uint[] calldata toChainIDs) external {
for (uint i = 0; i < tokens.length; i++) {
_anySwapOut(msg.sender, tokens[i], to[i], amounts[i], toChainIDs[i]);
}
}
// swaps `amount` `token` in `fromChainID` to `to` on this chainID
function _anySwapIn(bytes32 txs, address token, address to, uint amount, uint fromChainID) internal {
AnyswapV1ERC20(token).mint(to, amount);
emit LogAnySwapIn(txs, token, to, amount, fromChainID, cID());
}
// swaps `amount` `token` in `fromChainID` to `to` on this chainID
// triggered by `anySwapOut`
function anySwapIn(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC {
_anySwapIn(txs, token, to, amount, fromChainID);
}
// swaps `amount` `token` in `fromChainID` to `to` on this chainID with `to` receiving `underlying`
function anySwapInUnderlying(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC {
_anySwapIn(txs, token, to, amount, fromChainID);
AnyswapV1ERC20(token).withdrawVault(to, amount, to);
}
// swaps `amount` `token` in `fromChainID` to `to` on this chainID with `to` receiving `underlying` if possible
function anySwapInAuto(bytes32 txs, address token, address to, uint amount, uint fromChainID) external onlyMPC {
_anySwapIn(txs, token, to, amount, fromChainID);
AnyswapV1ERC20 _anyToken = AnyswapV1ERC20(token);
address _underlying = _anyToken.underlying();
if (_underlying != address(0) && IERC20(_underlying).balanceOf(token) >= amount) {
if (_underlying == wNATIVE) {
_anyToken.withdrawVault(to, amount, address(this));
IwNATIVE(wNATIVE).withdraw(amount);
TransferHelper.safeTransferNative(to, amount);
} else {
_anyToken.withdrawVault(to, amount, to);
}
}
}
function depositNative(address token, address to) external payable returns (uint) {
require(AnyswapV1ERC20(token).underlying() == wNATIVE, "AnyswapV3Router: underlying is not wNATIVE");
IwNATIVE(wNATIVE).deposit{value: msg.value}();
assert(IwNATIVE(wNATIVE).transfer(token, msg.value));
AnyswapV1ERC20(token).depositVault(msg.value, to);
return msg.value;
}
function withdrawNative(address token, uint amount, address to) external returns (uint) {
require(AnyswapV1ERC20(token).underlying() == wNATIVE, "AnyswapV3Router: underlying is not wNATIVE");
AnyswapV1ERC20(token).withdrawVault(msg.sender, amount, address(this));
IwNATIVE(wNATIVE).withdraw(amount);
TransferHelper.safeTransferNative(to, amount);
return amount;
}
// extracts mpc fee from bridge fees
function anySwapFeeTo(address token, uint amount) external onlyMPC {
address _mpc = mpc();
AnyswapV1ERC20(token).mint(_mpc, amount);
AnyswapV1ERC20(token).withdrawVault(_mpc, amount, _mpc);
}
function anySwapIn(bytes32[] calldata txs, address[] calldata tokens, address[] calldata to, uint256[] calldata amounts, uint[] calldata fromChainIDs) external onlyMPC {
for (uint i = 0; i < tokens.length; i++) {
_anySwapIn(txs[i], tokens[i], to[i], amounts[i], fromChainIDs[i]);
}
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = SushiswapV2Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? SushiswapV2Library.pairFor(factory, output, path[i + 2]) : _to;
ISushiswapV2Pair(SushiswapV2Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint toChainID
) external virtual ensure(deadline) {
AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn);
emit LogAnySwapTradeTokensForTokens(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID);
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForTokensUnderlying(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint toChainID
) external virtual ensure(deadline) {
IERC20(AnyswapV1ERC20(path[0]).underlying()).safeTransferFrom(msg.sender, path[0], amountIn);
AnyswapV1ERC20(path[0]).depositVault(amountIn, msg.sender);
AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn);
emit LogAnySwapTradeTokensForTokens(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID);
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForTokensUnderlyingWithPermit(
address from,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint8 v,
bytes32 r,
bytes32 s,
uint toChainID
) external virtual ensure(deadline) {
address _underlying = AnyswapV1ERC20(path[0]).underlying();
IERC20(_underlying).permit(from, address(this), amountIn, deadline, v, r, s);
IERC20(_underlying).safeTransferFrom(from, path[0], amountIn);
AnyswapV1ERC20(path[0]).depositVault(amountIn, from);
AnyswapV1ERC20(path[0]).burn(from, amountIn);
{
address[] memory _path = path;
address _from = from;
address _to = to;
uint _amountIn = amountIn;
uint _amountOutMin = amountOutMin;
uint _cID = cID();
uint _toChainID = toChainID;
emit LogAnySwapTradeTokensForTokens(_path, _from, _to, _amountIn, _amountOutMin, _cID, _toChainID);
}
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForTokensUnderlyingWithTransferPermit(
address from,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint8 v,
bytes32 r,
bytes32 s,
uint toChainID
) external virtual ensure(deadline) {
IERC20(AnyswapV1ERC20(path[0]).underlying()).transferWithPermit(from, path[0], amountIn, deadline, v, r, s);
AnyswapV1ERC20(path[0]).depositVault(amountIn, from);
AnyswapV1ERC20(path[0]).burn(from, amountIn);
emit LogAnySwapTradeTokensForTokens(path, from, to, amountIn, amountOutMin, cID(), toChainID);
}
// Swaps `amounts[path.length-1]` `path[path.length-1]` to `to` on this chain
// Triggered by `anySwapOutExactTokensForTokens`
function anySwapInExactTokensForTokens(
bytes32 txs,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint fromChainID
) external onlyMPC virtual ensure(deadline) returns (uint[] memory amounts) {
amounts = SushiswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'SushiswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT');
_anySwapIn(txs, path[0], SushiswapV2Library.pairFor(factory, path[0], path[1]), amounts[0], fromChainID);
_swap(amounts, path, to);
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForNative(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint toChainID
) external virtual ensure(deadline) {
AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn);
emit LogAnySwapTradeTokensForNative(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID);
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForNativeUnderlying(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint toChainID
) external virtual ensure(deadline) {
IERC20(AnyswapV1ERC20(path[0]).underlying()).safeTransferFrom(msg.sender, path[0], amountIn);
AnyswapV1ERC20(path[0]).depositVault(amountIn, msg.sender);
AnyswapV1ERC20(path[0]).burn(msg.sender, amountIn);
emit LogAnySwapTradeTokensForNative(path, msg.sender, to, amountIn, amountOutMin, cID(), toChainID);
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForNativeUnderlyingWithPermit(
address from,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint8 v,
bytes32 r,
bytes32 s,
uint toChainID
) external virtual ensure(deadline) {
address _underlying = AnyswapV1ERC20(path[0]).underlying();
IERC20(_underlying).permit(from, address(this), amountIn, deadline, v, r, s);
IERC20(_underlying).safeTransferFrom(from, path[0], amountIn);
AnyswapV1ERC20(path[0]).depositVault(amountIn, from);
AnyswapV1ERC20(path[0]).burn(from, amountIn);
{
address[] memory _path = path;
address _from = from;
address _to = to;
uint _amountIn = amountIn;
uint _amountOutMin = amountOutMin;
uint _cID = cID();
uint _toChainID = toChainID;
emit LogAnySwapTradeTokensForNative(_path, _from, _to, _amountIn, _amountOutMin, _cID, _toChainID);
}
}
// sets up a cross-chain trade from this chain to `toChainID` for `path` trades to `to`
function anySwapOutExactTokensForNativeUnderlyingWithTransferPermit(
address from,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint8 v,
bytes32 r,
bytes32 s,
uint toChainID
) external virtual ensure(deadline) {
IERC20(AnyswapV1ERC20(path[0]).underlying()).transferWithPermit(from, path[0], amountIn, deadline, v, r, s);
AnyswapV1ERC20(path[0]).depositVault(amountIn, from);
AnyswapV1ERC20(path[0]).burn(from, amountIn);
emit LogAnySwapTradeTokensForNative(path, from, to, amountIn, amountOutMin, cID(), toChainID);
}
// Swaps `amounts[path.length-1]` `path[path.length-1]` to `to` on this chain
// Triggered by `anySwapOutExactTokensForNative`
function anySwapInExactTokensForNative(
bytes32 txs,
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline,
uint fromChainID
) external onlyMPC virtual ensure(deadline) returns (uint[] memory amounts) {
require(path[path.length - 1] == wNATIVE, 'AnyswapV3Router: INVALID_PATH');
amounts = SushiswapV2Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'AnyswapV3Router: INSUFFICIENT_OUTPUT_AMOUNT');
_anySwapIn(txs, path[0], SushiswapV2Library.pairFor(factory, path[0], path[1]), amounts[0], fromChainID);
_swap(amounts, path, address(this));
IwNATIVE(wNATIVE).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferNative(to, amounts[amounts.length - 1]);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual returns (uint amountB) {
return SushiswapV2Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
returns (uint amountOut)
{
return SushiswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
returns (uint amountIn)
{
return SushiswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
returns (uint[] memory amounts)
{
return SushiswapV2Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
returns (uint[] memory amounts)
{
return SushiswapV2Library.getAmountsIn(factory, amountOut, path);
}
}
|
given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
|
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'SushiswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'SushiswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
| 1,038,042 |
./partial_match/3/0xd19B106B5D780962766Aa1Edc0Ce3c83ef999637/sources/CallistoMaker.sol
|
Withdraw LP tokens from MasterChef.
|
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accCTOPerShare).div(1e12).sub(user.rewardDebt);
safeCTOTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accCTOPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
| 5,081,668 |
./partial_match/8453/0xd9063d6E82BE1DfC705E53F47De5fcB73D59d935/sources/Sevens.sol
|
Store value in variable num value to store/
|
function store(uint256 num) public {
num = 777;
number = num;
}
| 16,727,445 |
./full_match/1/0xdF9Fb9E7731DfA4a17aDbB3a462E30470eb4d802/sources/contracts/ClosedDoors.sol
|
Returns the set price based on the tokenId given _tokenId the tokenId to get the class and determine the price of/ Keys are first in the token order so check those first
|
function getPricePerClass(uint256 _tokenId) internal view returns (uint256) {
return priceKeyS;
return 0;
}
| 3,874,234 |
pragma solidity 0.5.17;
import "@chainlink/contracts/src/v0.5/interfaces/AggregatorInterface.sol";
import {Ownable} from "@openzeppelin/contracts/ownership/Ownable.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
contract Oracle is Ownable {
using SafeMath for uint;
AggregatorInterface[] public refs;
AggregatorInterface public ethUsdAggregator;
/**
* @dev Initialize oracle with chainlink aggregators
* @param _aggregators <coin>-ETH Aggregator
* @param _ethUsdAggregator ETH-USD Aggregator
*/
constructor(
AggregatorInterface[] memory _aggregators,
AggregatorInterface _ethUsdAggregator
) public {
refs.length = _aggregators.length;
for(uint8 i = 0; i < _aggregators.length; i++) {
refs[i] = _aggregators[i];
}
ethUsdAggregator = _ethUsdAggregator;
}
/**
* @dev The latestAnswer value for all USD reference data contracts is multiplied by 100000000
* before being written on-chain and by 1000000000000000000 for all ETH pairs.
*/
function getPriceFeed() public view returns(uint[] memory feed) {
int256 ethUsdRate = ethUsdAggregator.latestAnswer();
feed = new uint[](refs.length);
for(uint8 i = 0; i < refs.length; i++) {
feed[i] = uint(refs[i].latestAnswer() * ethUsdRate).div(1e8);
}
}
function addAggregator(AggregatorInterface _aggregator) external onlyOwner {
refs.push(_aggregator);
}
}
|
The latestAnswer value for all USD reference data contracts is multiplied by 100000000 before being written on-chain and by 1000000000000000000 for all ETH pairs./
|
function getPriceFeed() public view returns(uint[] memory feed) {
int256 ethUsdRate = ethUsdAggregator.latestAnswer();
feed = new uint[](refs.length);
for(uint8 i = 0; i < refs.length; i++) {
feed[i] = uint(refs[i].latestAnswer() * ethUsdRate).div(1e8);
}
}
| 6,443,254 |
./full_match/1/0x84524bAa1951247b3A2617A843e6eCe915Bb9674/sources/contracts/MainHelper.sol
|
Helper function to convert {_amount} of a certain pool with {_poolToken} into lending shares. Includes devison by zero and share security checks. Needs latest pseudo amount for accurate result./
|
function calculateLendingShares(
address _poolToken,
uint256 _amount
)
public
view
returns (uint256)
{
uint256 shares = getTotalDepositShares(
_poolToken
);
if (shares <= 1) {
return _amount;
}
uint256 pseudo = getPseudoTotalPool(
_poolToken
);
if (pseudo == 0) {
return _amount;
}
return _amount
* shares
/ pseudo;
}
| 8,497,264 |
./partial_match/4/0x2f3c81fa2b0E171A135C128142Dbf877213c5071/sources/LiquidPledging.sol
|
`onlyVault` Cancels a withdraw request, changing the PledgeState from Paying back to Pledged idPledge Id of the pledge that's withdraw is to be canceled amount Quantity of ether (in wei) to be canceled When a payment is canceled, never is assigned to a project.
|
function cancelPayment(uint64 idPledge, uint amount) public onlyVault {
Pledge storage p = _findPledge(idPledge);
require(p.pledgeState == PledgeState.Paying);
uint64 idOldPledge = _findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
p.token,
PledgeState.Pledged
);
idOldPledge = normalizePledge(idOldPledge);
_doTransfer(idPledge, idOldPledge, amount);
}
| 8,506,666 |
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/IEtherTokenV06.sol";
import "@0x/contracts-erc20/contracts/src/v06/LibERC20TokenV06.sol";
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibMathV06.sol";
import "../fixins/FixinCommon.sol";
import "../fixins/FixinProtocolFees.sol";
import "../fixins/FixinEIP712.sol";
import "../fixins/FixinTokenSpender.sol";
import "../errors/LibNativeOrdersRichErrors.sol";
import "../migrations/LibMigrate.sol";
import "../storage/LibNativeOrdersStorage.sol";
import "../vendor/v3/IStaking.sol";
import "./libs/LibSignature.sol";
import "./libs/LibNativeOrder.sol";
import "./INativeOrdersFeature.sol";
import "./IFeature.sol";
/// @dev Feature for interacting with limit orders.
contract NativeOrdersFeature is
IFeature,
INativeOrdersFeature,
FixinCommon,
FixinProtocolFees,
FixinEIP712,
FixinTokenSpender
{
using LibSafeMathV06 for uint256;
using LibSafeMathV06 for uint128;
using LibRichErrorsV06 for bytes;
using LibERC20TokenV06 for IERC20TokenV06;
/// @dev Params for `_settleOrder()`.
struct SettleOrderInfo {
// Order hash.
bytes32 orderHash;
// Maker of the order.
address maker;
// Taker of the order.
address taker;
// Maker token.
IERC20TokenV06 makerToken;
// Taker token.
IERC20TokenV06 takerToken;
// Maker token amount.
uint128 makerAmount;
// Taker token amount.
uint128 takerAmount;
// Maximum taker token amount to fill.
uint128 takerTokenFillAmount;
// How much taker token amount has already been filled in this order.
uint128 takerTokenFilledAmount;
}
/// @dev Params for `_fillLimitOrderPrivate()`
struct FillLimitOrderPrivateParams {
// The limit order.
LibNativeOrder.LimitOrder order;
// The order signature.
LibSignature.Signature signature;
// Maximum taker token to fill this order with.
uint128 takerTokenFillAmount;
// The order taker.
address taker;
// The order sender.
address sender;
}
// @dev Fill results returned by `_fillLimitOrderPrivate()` and
/// `_fillRfqOrderPrivate()`.
struct FillNativeOrderResults {
uint256 ethProtocolFeePaid;
uint128 takerTokenFilledAmount;
uint128 makerTokenFilledAmount;
uint128 takerTokenFeeFilledAmount;
}
// @dev Params for `_getActualFillableTakerTokenAmount()`.
struct GetActualFillableTakerTokenAmountParams {
address maker;
IERC20TokenV06 makerToken;
uint128 orderMakerAmount;
uint128 orderTakerAmount;
LibNativeOrder.OrderInfo orderInfo;
}
/// @dev Name of this feature.
string public constant override FEATURE_NAME = "LimitOrders";
/// @dev Version of this feature.
uint256 public immutable override FEATURE_VERSION = _encodeVersion(1, 0, 1);
/// @dev Highest bit of a uint256, used to flag cancelled orders.
uint256 private constant HIGH_BIT = 1 << 255;
constructor(
address zeroExAddress,
IEtherTokenV06 weth,
IStaking staking,
FeeCollectorController feeCollectorController,
uint32 protocolFeeMultiplier,
bytes32 greedyTokensBloomFilter
)
public
FixinEIP712(zeroExAddress)
FixinProtocolFees(weth, staking, feeCollectorController, protocolFeeMultiplier)
FixinTokenSpender(greedyTokensBloomFilter)
{
// solhint-disable no-empty-blocks
}
/// @dev Initialize and register this feature.
/// Should be delegatecalled by `Migrate.migrate()`.
/// @return success `LibMigrate.SUCCESS` on success.
function migrate()
external
returns (bytes4 success)
{
_registerFeatureFunction(this.transferProtocolFeesForPools.selector);
_registerFeatureFunction(this.fillLimitOrder.selector);
_registerFeatureFunction(this.fillRfqOrder.selector);
_registerFeatureFunction(this.fillOrKillLimitOrder.selector);
_registerFeatureFunction(this.fillOrKillRfqOrder.selector);
_registerFeatureFunction(this._fillLimitOrder.selector);
_registerFeatureFunction(this._fillRfqOrder.selector);
_registerFeatureFunction(this.cancelLimitOrder.selector);
_registerFeatureFunction(this.cancelRfqOrder.selector);
_registerFeatureFunction(this.batchCancelLimitOrders.selector);
_registerFeatureFunction(this.batchCancelRfqOrders.selector);
_registerFeatureFunction(this.cancelPairLimitOrders.selector);
_registerFeatureFunction(this.batchCancelPairLimitOrders.selector);
_registerFeatureFunction(this.cancelPairRfqOrders.selector);
_registerFeatureFunction(this.batchCancelPairRfqOrders.selector);
_registerFeatureFunction(this.getLimitOrderInfo.selector);
_registerFeatureFunction(this.getRfqOrderInfo.selector);
_registerFeatureFunction(this.getLimitOrderHash.selector);
_registerFeatureFunction(this.getRfqOrderHash.selector);
_registerFeatureFunction(this.getProtocolFeeMultiplier.selector);
_registerFeatureFunction(this.registerAllowedRfqOrigins.selector);
_registerFeatureFunction(this.getLimitOrderRelevantState.selector);
_registerFeatureFunction(this.getRfqOrderRelevantState.selector);
_registerFeatureFunction(this.batchGetLimitOrderRelevantStates.selector);
_registerFeatureFunction(this.batchGetRfqOrderRelevantStates.selector);
return LibMigrate.MIGRATE_SUCCESS;
}
/// @dev Transfers protocol fees from the `FeeCollector` pools into
/// the staking contract.
/// @param poolIds Staking pool IDs
function transferProtocolFeesForPools(bytes32[] calldata poolIds)
external
override
{
for (uint256 i = 0; i < poolIds.length; ++i) {
_transferFeesForPool(poolIds[i]);
}
}
/// @dev Fill a limit order. The taker and sender will be the caller.
/// @param order The limit order. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// the caller.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token amount to fill this order with.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillLimitOrder(
LibNativeOrder.LimitOrder memory order,
LibSignature.Signature memory signature,
uint128 takerTokenFillAmount
)
public
override
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount)
{
FillNativeOrderResults memory results =
_fillLimitOrderPrivate(FillLimitOrderPrivateParams({
order: order,
signature: signature,
takerTokenFillAmount: takerTokenFillAmount,
taker: msg.sender,
sender: msg.sender
}));
_refundExcessProtocolFeeToSender(results.ethProtocolFeePaid);
(takerTokenFilledAmount, makerTokenFilledAmount) = (
results.takerTokenFilledAmount,
results.makerTokenFilledAmount
);
}
/// @dev Fill an RFQ order for up to `takerTokenFillAmount` taker tokens.
/// The taker will be the caller. ETH should be attached to pay the
/// protocol fee.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token amount to fill this order with.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillRfqOrder(
LibNativeOrder.RfqOrder memory order,
LibSignature.Signature memory signature,
uint128 takerTokenFillAmount
)
public
override
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount)
{
FillNativeOrderResults memory results =
_fillRfqOrderPrivate(
order,
signature,
takerTokenFillAmount,
msg.sender
);
(takerTokenFilledAmount, makerTokenFilledAmount) = (
results.takerTokenFilledAmount,
results.makerTokenFilledAmount
);
}
/// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens.
/// The taker will be the caller. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// the caller.
/// @param order The limit order.
/// @param signature The order signature.
/// @param takerTokenFillAmount How much taker token to fill this order with.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillOrKillLimitOrder(
LibNativeOrder.LimitOrder memory order,
LibSignature.Signature memory signature,
uint128 takerTokenFillAmount
)
public
override
payable
returns (uint128 makerTokenFilledAmount)
{
FillNativeOrderResults memory results =
_fillLimitOrderPrivate(FillLimitOrderPrivateParams({
order: order,
signature: signature,
takerTokenFillAmount: takerTokenFillAmount,
taker: msg.sender,
sender: msg.sender
}));
// Must have filled exactly the amount requested.
if (results.takerTokenFilledAmount < takerTokenFillAmount) {
LibNativeOrdersRichErrors.FillOrKillFailedError(
getLimitOrderHash(order),
results.takerTokenFilledAmount,
takerTokenFillAmount
).rrevert();
}
_refundExcessProtocolFeeToSender(results.ethProtocolFeePaid);
makerTokenFilledAmount = results.makerTokenFilledAmount;
}
/// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens.
/// The taker will be the caller. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// the caller.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount How much taker token to fill this order with.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillOrKillRfqOrder(
LibNativeOrder.RfqOrder memory order,
LibSignature.Signature memory signature,
uint128 takerTokenFillAmount
)
public
override
returns (uint128 makerTokenFilledAmount)
{
FillNativeOrderResults memory results =
_fillRfqOrderPrivate(
order,
signature,
takerTokenFillAmount,
msg.sender
);
// Must have filled exactly the amount requested.
if (results.takerTokenFilledAmount < takerTokenFillAmount) {
LibNativeOrdersRichErrors.FillOrKillFailedError(
getRfqOrderHash(order),
results.takerTokenFilledAmount,
takerTokenFillAmount
).rrevert();
}
makerTokenFilledAmount = results.makerTokenFilledAmount;
}
/// @dev Fill a limit order. Internal variant. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// `msg.sender` (not `sender`).
/// @param order The limit order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token to fill this order with.
/// @param taker The order taker.
/// @param sender The order sender.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function _fillLimitOrder(
LibNativeOrder.LimitOrder memory order,
LibSignature.Signature memory signature,
uint128 takerTokenFillAmount,
address taker,
address sender
)
public
virtual
override
payable
onlySelf
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount)
{
FillNativeOrderResults memory results =
_fillLimitOrderPrivate(FillLimitOrderPrivateParams({
order: order,
signature: signature,
takerTokenFillAmount: takerTokenFillAmount,
taker: taker,
sender: sender
}));
_refundExcessProtocolFeeToSender(results.ethProtocolFeePaid);
(takerTokenFilledAmount, makerTokenFilledAmount) = (
results.takerTokenFilledAmount,
results.makerTokenFilledAmount
);
}
/// @dev Fill an RFQ order. Internal variant. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// `msg.sender` (not `sender`).
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token to fill this order with.
/// @param taker The order taker.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function _fillRfqOrder(
LibNativeOrder.RfqOrder memory order,
LibSignature.Signature memory signature,
uint128 takerTokenFillAmount,
address taker
)
public
virtual
override
onlySelf
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount)
{
FillNativeOrderResults memory results =
_fillRfqOrderPrivate(
order,
signature,
takerTokenFillAmount,
taker
);
(takerTokenFilledAmount, makerTokenFilledAmount) = (
results.takerTokenFilledAmount,
results.makerTokenFilledAmount
);
}
/// @dev Cancel a single limit order. The caller must be the maker.
/// Silently succeeds if the order has already been cancelled.
/// @param order The limit order.
function cancelLimitOrder(LibNativeOrder.LimitOrder memory order)
public
override
{
bytes32 orderHash = getLimitOrderHash(order);
if (msg.sender != order.maker) {
LibNativeOrdersRichErrors.OnlyOrderMakerAllowed(
orderHash,
msg.sender,
order.maker
).rrevert();
}
_cancelOrderHash(orderHash, order.maker);
}
/// @dev Cancel a single RFQ order. The caller must be the maker.
/// Silently succeeds if the order has already been cancelled.
/// @param order The RFQ order.
function cancelRfqOrder(LibNativeOrder.RfqOrder memory order)
public
override
{
bytes32 orderHash = getRfqOrderHash(order);
if (msg.sender != order.maker) {
LibNativeOrdersRichErrors.OnlyOrderMakerAllowed(
orderHash,
msg.sender,
order.maker
).rrevert();
}
_cancelOrderHash(orderHash, order.maker);
}
/// @dev Cancel multiple limit orders. The caller must be the maker.
/// Silently succeeds if the order has already been cancelled.
/// @param orders The limit orders.
function batchCancelLimitOrders(LibNativeOrder.LimitOrder[] memory orders)
public
override
{
for (uint256 i = 0; i < orders.length; ++i) {
cancelLimitOrder(orders[i]);
}
}
/// @dev Cancel multiple RFQ orders. The caller must be the maker.
/// Silently succeeds if the order has already been cancelled.
/// @param orders The RFQ orders.
function batchCancelRfqOrders(LibNativeOrder.RfqOrder[] memory orders)
public
override
{
for (uint256 i = 0; i < orders.length; ++i) {
cancelRfqOrder(orders[i]);
}
}
/// @dev Cancel all limit orders for a given maker and pair with a salt less
/// than the value provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairLimitOrders(
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
public
override
{
LibNativeOrdersStorage.Storage storage stor =
LibNativeOrdersStorage.getStorage();
uint256 oldMinValidSalt =
stor.limitOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt
[msg.sender]
[address(makerToken)]
[address(takerToken)];
// New min salt must >= the old one.
if (oldMinValidSalt > minValidSalt) {
LibNativeOrdersRichErrors.
CancelSaltTooLowError(minValidSalt, oldMinValidSalt)
.rrevert();
}
stor.limitOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt
[msg.sender]
[address(makerToken)]
[address(takerToken)] = minValidSalt;
emit PairCancelledLimitOrders(
msg.sender,
address(makerToken),
address(takerToken),
minValidSalt
);
}
/// @dev Cancel all limit orders for a given maker and pair with a salt less
/// than the value provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairLimitOrders(
IERC20TokenV06[] memory makerTokens,
IERC20TokenV06[] memory takerTokens,
uint256[] memory minValidSalts
)
public
override
{
require(
makerTokens.length == takerTokens.length &&
makerTokens.length == minValidSalts.length,
"NativeOrdersFeature/MISMATCHED_PAIR_ORDERS_ARRAY_LENGTHS"
);
for (uint256 i = 0; i < makerTokens.length; ++i) {
cancelPairLimitOrders(
makerTokens[i],
takerTokens[i],
minValidSalts[i]
);
}
}
/// @dev Cancel all RFQ orders for a given maker and pair with a salt less
/// than the value provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairRfqOrders(
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
public
override
{
LibNativeOrdersStorage.Storage storage stor =
LibNativeOrdersStorage.getStorage();
uint256 oldMinValidSalt =
stor.rfqOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt
[msg.sender]
[address(makerToken)]
[address(takerToken)];
// New min salt must >= the old one.
if (oldMinValidSalt > minValidSalt) {
LibNativeOrdersRichErrors.
CancelSaltTooLowError(minValidSalt, oldMinValidSalt)
.rrevert();
}
stor.rfqOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt
[msg.sender]
[address(makerToken)]
[address(takerToken)] = minValidSalt;
emit PairCancelledRfqOrders(
msg.sender,
address(makerToken),
address(takerToken),
minValidSalt
);
}
/// @dev Mark what tx.origin addresses are allowed to fill an order that
/// specifies the message sender as its txOrigin.
/// @param origins An array of origin addresses to update.
/// @param allowed True to register, false to unregister.
function registerAllowedRfqOrigins(
address[] memory origins,
bool allowed
)
external
override
{
require(msg.sender == tx.origin,
"NativeOrdersFeature/NO_CONTRACT_ORIGINS");
LibNativeOrdersStorage.Storage storage stor =
LibNativeOrdersStorage.getStorage();
for (uint256 i = 0; i < origins.length; i++) {
stor.originRegistry[msg.sender][origins[i]] = allowed;
}
emit RfqOrderOriginsAllowed(msg.sender, origins, allowed);
}
/// @dev Cancel all RFQ orders for a given maker and pair with a salt less
/// than the value provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairRfqOrders(
IERC20TokenV06[] memory makerTokens,
IERC20TokenV06[] memory takerTokens,
uint256[] memory minValidSalts
)
public
override
{
require(
makerTokens.length == takerTokens.length &&
makerTokens.length == minValidSalts.length,
"NativeOrdersFeature/MISMATCHED_PAIR_ORDERS_ARRAY_LENGTHS"
);
for (uint256 i = 0; i < makerTokens.length; ++i) {
cancelPairRfqOrders(
makerTokens[i],
takerTokens[i],
minValidSalts[i]
);
}
}
/// @dev Get the order info for a limit order.
/// @param order The limit order.
/// @return orderInfo Info about the order.
function getLimitOrderInfo(LibNativeOrder.LimitOrder memory order)
public
override
view
returns (LibNativeOrder.OrderInfo memory orderInfo)
{
// Recover maker and compute order hash.
orderInfo.orderHash = getLimitOrderHash(order);
uint256 minValidSalt = LibNativeOrdersStorage.getStorage()
.limitOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt
[order.maker]
[address(order.makerToken)]
[address(order.takerToken)];
_populateCommonOrderInfoFields(
orderInfo,
order.takerAmount,
order.expiry,
order.salt,
minValidSalt
);
}
/// @dev Get the order info for an RFQ order.
/// @param order The RFQ order.
/// @return orderInfo Info about the order.
function getRfqOrderInfo(LibNativeOrder.RfqOrder memory order)
public
override
view
returns (LibNativeOrder.OrderInfo memory orderInfo)
{
// Recover maker and compute order hash.
orderInfo.orderHash = getRfqOrderHash(order);
uint256 minValidSalt = LibNativeOrdersStorage.getStorage()
.rfqOrdersMakerToMakerTokenToTakerTokenToMinValidOrderSalt
[order.maker]
[address(order.makerToken)]
[address(order.takerToken)];
_populateCommonOrderInfoFields(
orderInfo,
order.takerAmount,
order.expiry,
order.salt,
minValidSalt
);
// Check for missing txOrigin.
if (order.txOrigin == address(0)) {
orderInfo.status = LibNativeOrder.OrderStatus.INVALID;
}
}
/// @dev Get the canonical hash of a limit order.
/// @param order The limit order.
/// @return orderHash The order hash.
function getLimitOrderHash(LibNativeOrder.LimitOrder memory order)
public
override
view
returns (bytes32 orderHash)
{
return _getEIP712Hash(
LibNativeOrder.getLimitOrderStructHash(order)
);
}
/// @dev Get the canonical hash of an RFQ order.
/// @param order The RFQ order.
/// @return orderHash The order hash.
function getRfqOrderHash(LibNativeOrder.RfqOrder memory order)
public
override
view
returns (bytes32 orderHash)
{
return _getEIP712Hash(
LibNativeOrder.getRfqOrderStructHash(order)
);
}
/// @dev Get order info, fillable amount, and signature validity for a limit order.
/// Fillable amount is determined using balances and allowances of the maker.
/// @param order The limit order.
/// @param signature The order signature.
/// @return orderInfo Info about the order.
/// @return actualFillableTakerTokenAmount How much of the order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValid Whether the signature is valid.
function getLimitOrderRelevantState(
LibNativeOrder.LimitOrder memory order,
LibSignature.Signature calldata signature
)
public
override
view
returns (
LibNativeOrder.OrderInfo memory orderInfo,
uint128 actualFillableTakerTokenAmount,
bool isSignatureValid
)
{
orderInfo = getLimitOrderInfo(order);
actualFillableTakerTokenAmount = _getActualFillableTakerTokenAmount(
GetActualFillableTakerTokenAmountParams({
maker: order.maker,
makerToken: order.makerToken,
orderMakerAmount: order.makerAmount,
orderTakerAmount: order.takerAmount,
orderInfo: orderInfo
})
);
isSignatureValid = order.maker ==
LibSignature.getSignerOfHash(orderInfo.orderHash, signature);
}
/// @dev Get order info, fillable amount, and signature validity for an RFQ order.
/// Fillable amount is determined using balances and allowances of the maker.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @return orderInfo Info about the order.
/// @return actualFillableTakerTokenAmount How much of the order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValid Whether the signature is valid.
function getRfqOrderRelevantState(
LibNativeOrder.RfqOrder memory order,
LibSignature.Signature memory signature
)
public
override
view
returns (
LibNativeOrder.OrderInfo memory orderInfo,
uint128 actualFillableTakerTokenAmount,
bool isSignatureValid
)
{
orderInfo = getRfqOrderInfo(order);
actualFillableTakerTokenAmount = _getActualFillableTakerTokenAmount(
GetActualFillableTakerTokenAmountParams({
maker: order.maker,
makerToken: order.makerToken,
orderMakerAmount: order.makerAmount,
orderTakerAmount: order.takerAmount,
orderInfo: orderInfo
})
);
isSignatureValid = order.maker ==
LibSignature.getSignerOfHash(orderInfo.orderHash, signature);
}
/// @dev Batch version of `getLimitOrderRelevantState()`, without reverting.
/// Orders that would normally cause `getLimitOrderRelevantState()`
/// to revert will have empty results.
/// @param orders The limit orders.
/// @param signatures The order signatures.
/// @return orderInfos Info about the orders.
/// @return actualFillableTakerTokenAmounts How much of each order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValids Whether each signature is valid for the order.
function batchGetLimitOrderRelevantStates(
LibNativeOrder.LimitOrder[] calldata orders,
LibSignature.Signature[] calldata signatures
)
external
override
view
returns (
LibNativeOrder.OrderInfo[] memory orderInfos,
uint128[] memory actualFillableTakerTokenAmounts,
bool[] memory isSignatureValids
)
{
require(
orders.length == signatures.length,
"NativeOrdersFeature/MISMATCHED_ARRAY_LENGTHS"
);
orderInfos = new LibNativeOrder.OrderInfo[](orders.length);
actualFillableTakerTokenAmounts = new uint128[](orders.length);
isSignatureValids = new bool[](orders.length);
for (uint256 i = 0; i < orders.length; ++i) {
try
this.getLimitOrderRelevantState(orders[i], signatures[i])
returns (
LibNativeOrder.OrderInfo memory orderInfo,
uint128 actualFillableTakerTokenAmount,
bool isSignatureValid
)
{
orderInfos[i] = orderInfo;
actualFillableTakerTokenAmounts[i] = actualFillableTakerTokenAmount;
isSignatureValids[i] = isSignatureValid;
}
catch {}
}
}
/// @dev Batch version of `getRfqOrderRelevantState()`, without reverting.
/// Orders that would normally cause `getRfqOrderRelevantState()`
/// to revert will have empty results.
/// @param orders The RFQ orders.
/// @param signatures The order signatures.
/// @return orderInfos Info about the orders.
/// @return actualFillableTakerTokenAmounts How much of each order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValids Whether each signature is valid for the order.
function batchGetRfqOrderRelevantStates(
LibNativeOrder.RfqOrder[] calldata orders,
LibSignature.Signature[] calldata signatures
)
external
override
view
returns (
LibNativeOrder.OrderInfo[] memory orderInfos,
uint128[] memory actualFillableTakerTokenAmounts,
bool[] memory isSignatureValids
)
{
require(
orders.length == signatures.length,
"NativeOrdersFeature/MISMATCHED_ARRAY_LENGTHS"
);
orderInfos = new LibNativeOrder.OrderInfo[](orders.length);
actualFillableTakerTokenAmounts = new uint128[](orders.length);
isSignatureValids = new bool[](orders.length);
for (uint256 i = 0; i < orders.length; ++i) {
try
this.getRfqOrderRelevantState(orders[i], signatures[i])
returns (
LibNativeOrder.OrderInfo memory orderInfo,
uint128 actualFillableTakerTokenAmount,
bool isSignatureValid
)
{
orderInfos[i] = orderInfo;
actualFillableTakerTokenAmounts[i] = actualFillableTakerTokenAmount;
isSignatureValids[i] = isSignatureValid;
}
catch {}
}
}
/// @dev Get the protocol fee multiplier. This should be multiplied by the
/// gas price to arrive at the required protocol fee to fill a native order.
/// @return multiplier The protocol fee multiplier.
function getProtocolFeeMultiplier()
external
override
view
returns (uint32 multiplier)
{
return PROTOCOL_FEE_MULTIPLIER;
}
/// @dev Populate `status` and `takerTokenFilledAmount` fields in
/// `orderInfo`, which use the same code path for both limit and
/// RFQ orders.
/// @param orderInfo `OrderInfo` with `orderHash` and `maker` filled.
/// @param takerAmount The order's taker token amount..
/// @param expiry The order's expiry.
/// @param salt The order's salt.
/// @param salt The minimum valid salt for the maker and pair combination.
function _populateCommonOrderInfoFields(
LibNativeOrder.OrderInfo memory orderInfo,
uint128 takerAmount,
uint64 expiry,
uint256 salt,
uint256 minValidSalt
)
private
view
{
LibNativeOrdersStorage.Storage storage stor =
LibNativeOrdersStorage.getStorage();
// Get the filled and direct cancel state.
{
// The high bit of the raw taker token filled amount will be set
// if the order was cancelled.
uint256 rawTakerTokenFilledAmount =
stor.orderHashToTakerTokenFilledAmount[orderInfo.orderHash];
orderInfo.takerTokenFilledAmount = uint128(rawTakerTokenFilledAmount);
if (orderInfo.takerTokenFilledAmount >= takerAmount) {
orderInfo.status = LibNativeOrder.OrderStatus.FILLED;
return;
}
if (rawTakerTokenFilledAmount & HIGH_BIT != 0) {
orderInfo.status = LibNativeOrder.OrderStatus.CANCELLED;
return;
}
}
// Check for expiration.
if (expiry <= uint64(block.timestamp)) {
orderInfo.status = LibNativeOrder.OrderStatus.EXPIRED;
return;
}
// Check if the order was cancelled by salt.
if (minValidSalt > salt) {
orderInfo.status = LibNativeOrder.OrderStatus.CANCELLED;
return;
}
orderInfo.status = LibNativeOrder.OrderStatus.FILLABLE;
}
/// @dev Calculate the actual fillable taker token amount of an order
/// based on maker allowance and balances.
function _getActualFillableTakerTokenAmount(
GetActualFillableTakerTokenAmountParams memory params
)
private
view
returns (uint128 actualFillableTakerTokenAmount)
{
if (params.orderMakerAmount == 0 || params.orderTakerAmount == 0) {
// Empty order.
return 0;
}
if (params.orderInfo.status != LibNativeOrder.OrderStatus.FILLABLE) {
// Not fillable.
return 0;
}
// Get the fillable maker amount based on the order quantities and
// previously filled amount
uint256 fillableMakerTokenAmount = LibMathV06.getPartialAmountFloor(
uint256(
params.orderTakerAmount
- params.orderInfo.takerTokenFilledAmount
),
uint256(params.orderTakerAmount),
uint256(params.orderMakerAmount)
);
// Clamp it to the amount of maker tokens we can spend on behalf of the
// maker.
fillableMakerTokenAmount = LibSafeMathV06.min256(
fillableMakerTokenAmount,
_getSpendableERC20BalanceOf(params.makerToken, params.maker)
);
// Convert to taker token amount.
return LibMathV06.getPartialAmountCeil(
fillableMakerTokenAmount,
uint256(params.orderMakerAmount),
uint256(params.orderTakerAmount)
).safeDowncastToUint128();
}
/// @dev Cancel a limit or RFQ order directly by its order hash.
/// @param orderHash The order's order hash.
/// @param maker The order's maker.
function _cancelOrderHash(bytes32 orderHash, address maker)
private
{
LibNativeOrdersStorage.Storage storage stor =
LibNativeOrdersStorage.getStorage();
// Set the high bit on the raw taker token fill amount to indicate
// a cancel. It's OK to cancel twice.
stor.orderHashToTakerTokenFilledAmount[orderHash] |= HIGH_BIT;
emit OrderCancelled(orderHash, maker);
}
/// @dev Fill a limit order. Private variant. Does not refund protocol fees.
/// @param params Function params.
/// @return results Results of the fill.
function _fillLimitOrderPrivate(FillLimitOrderPrivateParams memory params)
private
returns (FillNativeOrderResults memory results)
{
LibNativeOrder.OrderInfo memory orderInfo = getLimitOrderInfo(params.order);
// Must be fillable.
if (orderInfo.status != LibNativeOrder.OrderStatus.FILLABLE) {
LibNativeOrdersRichErrors.OrderNotFillableError(
orderInfo.orderHash,
uint8(orderInfo.status)
).rrevert();
}
// Must be fillable by the taker.
if (params.order.taker != address(0) && params.order.taker != params.taker) {
LibNativeOrdersRichErrors.OrderNotFillableByTakerError(
orderInfo.orderHash,
params.taker,
params.order.taker
).rrevert();
}
// Must be fillable by the sender.
if (params.order.sender != address(0) && params.order.sender != params.sender) {
LibNativeOrdersRichErrors.OrderNotFillableBySenderError(
orderInfo.orderHash,
params.sender,
params.order.sender
).rrevert();
}
// Signature must be valid for the order.
{
address signer = LibSignature.getSignerOfHash(
orderInfo.orderHash,
params.signature
);
if (signer != params.order.maker) {
LibNativeOrdersRichErrors.OrderNotSignedByMakerError(
orderInfo.orderHash,
signer,
params.order.maker
).rrevert();
}
}
// Pay the protocol fee.
results.ethProtocolFeePaid = _collectProtocolFee(params.order.pool);
// Settle between the maker and taker.
(results.takerTokenFilledAmount, results.makerTokenFilledAmount) = _settleOrder(
SettleOrderInfo({
orderHash: orderInfo.orderHash,
maker: params.order.maker,
taker: params.taker,
makerToken: IERC20TokenV06(params.order.makerToken),
takerToken: IERC20TokenV06(params.order.takerToken),
makerAmount: params.order.makerAmount,
takerAmount: params.order.takerAmount,
takerTokenFillAmount: params.takerTokenFillAmount,
takerTokenFilledAmount: orderInfo.takerTokenFilledAmount
})
);
// Pay the fee recipient.
if (params.order.takerTokenFeeAmount > 0) {
results.takerTokenFeeFilledAmount = uint128(LibMathV06.getPartialAmountFloor(
results.takerTokenFilledAmount,
params.order.takerAmount,
params.order.takerTokenFeeAmount
));
_transferERC20Tokens(
params.order.takerToken,
params.taker,
params.order.feeRecipient,
uint256(results.takerTokenFeeFilledAmount)
);
}
emit LimitOrderFilled(
orderInfo.orderHash,
params.order.maker,
params.taker,
params.order.feeRecipient,
address(params.order.makerToken),
address(params.order.takerToken),
results.takerTokenFilledAmount,
results.makerTokenFilledAmount,
results.takerTokenFeeFilledAmount,
results.ethProtocolFeePaid,
params.order.pool
);
}
/// @dev Fill an RFQ order. Private variant. Does not refund protocol fees.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token to fill this order with.
/// @param taker The order taker.
/// @return results Results of the fill.
function _fillRfqOrderPrivate(
LibNativeOrder.RfqOrder memory order,
LibSignature.Signature memory signature,
uint128 takerTokenFillAmount,
address taker
)
private
returns (FillNativeOrderResults memory results)
{
LibNativeOrder.OrderInfo memory orderInfo = getRfqOrderInfo(order);
// Must be fillable.
if (orderInfo.status != LibNativeOrder.OrderStatus.FILLABLE) {
LibNativeOrdersRichErrors.OrderNotFillableError(
orderInfo.orderHash,
uint8(orderInfo.status)
).rrevert();
}
{
LibNativeOrdersStorage.Storage storage stor =
LibNativeOrdersStorage.getStorage();
// Must be fillable by the tx.origin.
if (order.txOrigin != tx.origin && !stor.originRegistry[order.txOrigin][tx.origin]) {
LibNativeOrdersRichErrors.OrderNotFillableByOriginError(
orderInfo.orderHash,
tx.origin,
order.txOrigin
).rrevert();
}
}
// Must be fillable by the taker.
if (order.taker != address(0) && order.taker != taker) {
LibNativeOrdersRichErrors.OrderNotFillableByTakerError(
orderInfo.orderHash,
taker,
order.taker
).rrevert();
}
// Signature must be valid for the order.
{
address signer = LibSignature.getSignerOfHash(orderInfo.orderHash, signature);
if (signer != order.maker) {
LibNativeOrdersRichErrors.OrderNotSignedByMakerError(
orderInfo.orderHash,
signer,
order.maker
).rrevert();
}
}
// Settle between the maker and taker.
(results.takerTokenFilledAmount, results.makerTokenFilledAmount) = _settleOrder(
SettleOrderInfo({
orderHash: orderInfo.orderHash,
maker: order.maker,
taker: taker,
makerToken: IERC20TokenV06(order.makerToken),
takerToken: IERC20TokenV06(order.takerToken),
makerAmount: order.makerAmount,
takerAmount: order.takerAmount,
takerTokenFillAmount: takerTokenFillAmount,
takerTokenFilledAmount: orderInfo.takerTokenFilledAmount
})
);
emit RfqOrderFilled(
orderInfo.orderHash,
order.maker,
taker,
address(order.makerToken),
address(order.takerToken),
results.takerTokenFilledAmount,
results.makerTokenFilledAmount,
order.pool
);
}
/// @dev Settle the trade between an order's maker and taker.
/// @param settleInfo Information needed to execute the settlement.
/// @return takerTokenFilledAmount How much taker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function _settleOrder(SettleOrderInfo memory settleInfo)
private
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount)
{
// Clamp the taker token fill amount to the fillable amount.
takerTokenFilledAmount = LibSafeMathV06.min128(
settleInfo.takerTokenFillAmount,
settleInfo.takerAmount.safeSub128(settleInfo.takerTokenFilledAmount)
);
// Compute the maker token amount.
// This should never overflow because the values are all clamped to
// (2^128-1).
makerTokenFilledAmount = uint128(LibMathV06.getPartialAmountFloor(
uint256(takerTokenFilledAmount),
uint256(settleInfo.takerAmount),
uint256(settleInfo.makerAmount)
));
if (takerTokenFilledAmount == 0 || makerTokenFilledAmount == 0) {
// Nothing to do.
return (0, 0);
}
// Update filled state for the order.
LibNativeOrdersStorage
.getStorage()
.orderHashToTakerTokenFilledAmount[settleInfo.orderHash] =
// OK to overwrite the whole word because we shouldn't get to this
// function if the order is cancelled.
settleInfo.takerTokenFilledAmount.safeAdd128(takerTokenFilledAmount);
// Transfer taker -> maker.
_transferERC20Tokens(
settleInfo.takerToken,
settleInfo.taker,
settleInfo.maker,
takerTokenFilledAmount
);
// Transfer maker -> taker.
_transferERC20Tokens(
settleInfo.makerToken,
settleInfo.maker,
settleInfo.taker,
makerTokenFilledAmount
);
}
/// @dev Refund any leftover protocol fees in `msg.value` to `msg.sender`.
/// @param ethProtocolFeePaid How much ETH was paid in protocol fees.
function _refundExcessProtocolFeeToSender(uint256 ethProtocolFeePaid)
private
{
if (msg.value > ethProtocolFeePaid && msg.sender != address(this)) {
uint256 refundAmount = msg.value.safeSub(ethProtocolFeePaid);
(bool success,) = msg
.sender
.call{value: refundAmount}("");
if (!success) {
LibNativeOrdersRichErrors.ProtocolFeeRefundFailed(
msg.sender,
refundAmount
).rrevert();
}
}
}
}
|
Initialize and register this feature. Should be delegatecalled by `Migrate.migrate()`. return success `LibMigrate.SUCCESS` on success.
|
function migrate()
external
returns (bytes4 success)
{
_registerFeatureFunction(this.transferProtocolFeesForPools.selector);
_registerFeatureFunction(this.fillLimitOrder.selector);
_registerFeatureFunction(this.fillRfqOrder.selector);
_registerFeatureFunction(this.fillOrKillLimitOrder.selector);
_registerFeatureFunction(this.fillOrKillRfqOrder.selector);
_registerFeatureFunction(this._fillLimitOrder.selector);
_registerFeatureFunction(this._fillRfqOrder.selector);
_registerFeatureFunction(this.cancelLimitOrder.selector);
_registerFeatureFunction(this.cancelRfqOrder.selector);
_registerFeatureFunction(this.batchCancelLimitOrders.selector);
_registerFeatureFunction(this.batchCancelRfqOrders.selector);
_registerFeatureFunction(this.cancelPairLimitOrders.selector);
_registerFeatureFunction(this.batchCancelPairLimitOrders.selector);
_registerFeatureFunction(this.cancelPairRfqOrders.selector);
_registerFeatureFunction(this.batchCancelPairRfqOrders.selector);
_registerFeatureFunction(this.getLimitOrderInfo.selector);
_registerFeatureFunction(this.getRfqOrderInfo.selector);
_registerFeatureFunction(this.getLimitOrderHash.selector);
_registerFeatureFunction(this.getRfqOrderHash.selector);
_registerFeatureFunction(this.getProtocolFeeMultiplier.selector);
_registerFeatureFunction(this.registerAllowedRfqOrigins.selector);
_registerFeatureFunction(this.getLimitOrderRelevantState.selector);
_registerFeatureFunction(this.getRfqOrderRelevantState.selector);
_registerFeatureFunction(this.batchGetLimitOrderRelevantStates.selector);
_registerFeatureFunction(this.batchGetRfqOrderRelevantStates.selector);
return LibMigrate.MIGRATE_SUCCESS;
}
| 2,544,587 |
/*
* source https://github.com/lukso-network/rICO-smart-contracts
* @name rICO
* @package rICO-smart-contracts
* @author Micky Socaci <[email protected]>, Fabian Vogelsteller <@frozeman>, Marjorie Hernandez <[email protected]>
* @license MIT
*/
pragma solidity ^0.5.0;
import "./zeppelin/math/SafeMath.sol";
import "./zeppelin/token/ERC777/IERC777.sol";
import "./zeppelin/token/ERC777/IERC777Recipient.sol";
import "./zeppelin/introspection/IERC1820Registry.sol";
contract ReversibleICO is IERC777Recipient {
/*
* Instances
*/
using SafeMath for uint256;
/// @dev The address of the introspection registry contract deployed.
IERC1820Registry private ERC1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient");
/*
* Contract States
*/
/// @dev It is set to TRUE after the deployer initializes the contract.
bool public initialized;
/// @dev Security guard. The freezer address can the freeze the contract and move its funds in case of emergency.
bool public frozen;
uint256 public frozenPeriod;
uint256 public freezeStart;
/*
* Addresses
*/
/// @dev Only the deploying address is allowed to initialize the contract.
address public deployingAddress;
/// @dev The rICO token contract address.
address public tokenAddress;
/// @dev The address of wallet of the project running the rICO.
address public projectAddress;
/// @dev Only the whitelist controller can whitelist addresses.
address public whitelistingAddress;
/// @dev Only the freezer address can call the freeze functions.
address public freezerAddress;
/// @dev Only the rescuer address can move funds if the rICO is frozen.
address public rescuerAddress;
/*
* Public Variables
*/
/// @dev Total amount tokens initially available to be bought, increases if the project adds more.
uint256 public initialTokenSupply;
/// @dev Total amount tokens currently available to be bought.
uint256 public tokenSupply;
/// @dev Total amount of ETH currently accepted as a commitment to buy tokens (excluding pendingETH).
uint256 public committedETH;
/// @dev Total amount of ETH currently pending to be whitelisted.
uint256 public pendingETH;
/// @dev Accumulated amount of all ETH returned from canceled pending ETH.
uint256 public canceledETH;
/// @dev Accumulated amount of all ETH withdrawn by participants.
uint256 public withdrawnETH;
/// @dev Count of the number the project has withdrawn from the funds raised.
uint256 public projectWithdrawCount;
/// @dev Total amount of ETH withdrawn by the project
uint256 public projectWithdrawnETH;
/// @dev Minimum amount of ETH accepted for a contribution. Everything lower than that will trigger a canceling of pending ETH.
uint256 public minContribution = 0.001 ether;
uint256 public maxContribution = 4000 ether;
mapping(uint8 => Stage) public stages;
uint8 public stageCount;
/// @dev Maps participants stats by their address.
mapping(address => Participant) public participants;
/// @dev Maps participants address to a unique participant ID (incremental IDs, based on "participantCount").
mapping(uint256 => address) public participantsById;
/// @dev Total number of rICO participants.
uint256 public participantCount;
/*
* Commit phase (Stage 0)
*/
/// @dev Initial token price in the commit phase (Stage 0).
uint256 public commitPhasePrice;
/// @dev Block number that indicates the start of the commit phase.
uint256 public commitPhaseStartBlock;
/// @dev Block number that indicates the end of the commit phase.
uint256 public commitPhaseEndBlock;
/// @dev The duration of the commit phase in blocks.
uint256 public commitPhaseBlockCount;
/*
* Buy phases (Stages 1-n)
*/
/// @dev Block number that indicates the start of the buy phase (Stages 1-n).
uint256 public buyPhaseStartBlock;
/// @dev Block number that indicates the end of the buy phase.
uint256 public buyPhaseEndBlock;
/// @dev The duration of the buy phase in blocks.
uint256 public buyPhaseBlockCount;
/*
* Internal Variables
*/
/// @dev Total amount of the current reserved ETH for the project by the participants contributions.
uint256 internal _projectCurrentlyReservedETH;
/// @dev Accumulated amount allocated to the project by participants.
uint256 internal _projectUnlockedETH;
/// @dev Last block since the project has calculated the _projectUnlockedETH.
uint256 internal _projectLastBlock;
/*
* Structs
*/
/*
* Stages
* Stage 0 = commit phase
* Stage 1-n = buy phase
*/
struct Stage {
uint256 tokenLimit; // 500k > 9.5M >
uint256 tokenPrice;
}
/*
* Participants
*/
struct Participant {
bool whitelisted;
uint32 contributions;
uint32 withdraws;
uint256 firstContributionBlock;
uint256 reservedTokens;
uint256 committedETH;
uint256 pendingETH;
uint256 _currentReservedTokens;
uint256 _unlockedTokens;
uint256 _lastBlock;
mapping(uint8 => ParticipantStageDetails) stages;
}
struct ParticipantStageDetails {
uint256 pendingETH;
}
/*
* Events
*/
event PendingContributionAdded(address indexed participantAddress, uint256 indexed amount, uint32 indexed contributionId, uint8 stageId);
event PendingContributionsCanceled(address indexed participantAddress, uint256 indexed amount, uint32 indexed contributionId);
event WhitelistApproved(address indexed participantAddress, uint256 indexed pendingETH, uint32 indexed contributions);
event WhitelistRejected(address indexed participantAddress, uint256 indexed pendingETH, uint32 indexed contributions);
event ContributionsAccepted(address indexed participantAddress, uint256 indexed ethAmount, uint256 indexed tokenAmount, uint8 stageId);
event ProjectWithdraw(address indexed projectAddress, uint256 indexed amount, uint32 indexed withdrawCount);
event ParticipantWithdraw(address indexed participantAddress, uint256 indexed ethAmount, uint256 indexed tokenAmount, uint32 withdrawCount);
event StageChanged(uint8 indexed stageId, uint256 indexed tokenLimit, uint256 indexed tokenPrice, uint256 effectiveBlockNumber);
event WhitelistingAddressChanged(address indexed whitelistingAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event FreezerAddressChanged(address indexed freezerAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event SecurityFreeze(address indexed freezerAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event SecurityUnfreeze(address indexed freezerAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event SecurityDisableEscapeHatch(address indexed freezerAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event SecurityEscapeHatch(address indexed rescuerAddress, address indexed to, uint8 indexed stageId, uint256 effectiveBlockNumber);
event TransferEvent (
uint8 indexed typeId,
address indexed relatedAddress,
uint256 indexed value
);
enum TransferTypes {
NOT_SET, // 0
WHITELIST_REJECTED, // 1
CONTRIBUTION_CANCELED, // 2
CONTRIBUTION_ACCEPTED_OVERFLOW, // 3 not accepted ETH
PARTICIPANT_WITHDRAW, // 4
PARTICIPANT_WITHDRAW_OVERFLOW, // 5 not returnable tokens
PROJECT_WITHDRAWN, // 6
FROZEN_ESCAPEHATCH_TOKEN, // 7
FROZEN_ESCAPEHATCH_ETH // 8
}
// ------------------------------------------------------------------------------------------------
/// @notice Constructor sets the deployer and defines ERC777TokensRecipient interface support.
constructor() public {
deployingAddress = msg.sender;
ERC1820.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this));
}
/**
* @notice Initializes the contract. Only the deployer (set in the constructor) can call this method.
* @param _tokenAddress The address of the ERC777 rICO token contract.
* @param _whitelistingAddress The address handling whitelisting.
* @param _projectAddress The project wallet that can withdraw ETH contributions.
* @param _commitPhaseStartBlock The block at which the commit phase starts.
* @param _buyPhaseStartBlock The duration of the commit phase in blocks.
* @param _initialPrice The initial token price (in WEI per token) during the commit phase.
* @param _stageCount The number of the rICO stages, excluding the commit phase (Stage 0).
* @param _stageTokenLimitIncrease The duration of each stage in blocks.
* @param _stagePriceIncrease A factor used to increase the token price from the _initialPrice at each subsequent stage.
*/
function init(
address _tokenAddress,
address _whitelistingAddress,
address _freezerAddress,
address _rescuerAddress,
address _projectAddress,
uint256 _commitPhaseStartBlock,
uint256 _buyPhaseStartBlock,
uint256 _buyPhaseEndBlock,
uint256 _initialPrice,
uint8 _stageCount, // Its not recommended to choose more than 50 stages! (9 stages require ~650k GAS when whitelisting contributions, the whitelisting function could run out of gas with a high number of stages, preventing accepting contributions)
uint256 _stageTokenLimitIncrease,
uint256 _stagePriceIncrease
)
public
onlyDeployingAddress
isNotInitialized
{
require(_tokenAddress != address(0), "_tokenAddress cannot be 0x");
require(_whitelistingAddress != address(0), "_whitelistingAddress cannot be 0x");
require(_freezerAddress != address(0), "_freezerAddress cannot be 0x");
require(_rescuerAddress != address(0), "_rescuerAddress cannot be 0x");
require(_projectAddress != address(0), "_projectAddress cannot be 0x");
// require(_commitPhaseStartBlock > getCurrentBlockNumber(), "Start block cannot be set in the past.");
// Assign address variables
tokenAddress = _tokenAddress;
whitelistingAddress = _whitelistingAddress;
freezerAddress = _freezerAddress;
rescuerAddress = _rescuerAddress;
projectAddress = _projectAddress;
// UPDATE global STATS
commitPhaseStartBlock = _commitPhaseStartBlock;
commitPhaseEndBlock = _buyPhaseStartBlock.sub(1);
commitPhaseBlockCount = commitPhaseEndBlock.sub(commitPhaseStartBlock).add(1);
commitPhasePrice = _initialPrice;
stageCount = _stageCount;
// Setup stage 0: The commit phase.
Stage storage commitPhase = stages[0];
commitPhase.tokenLimit = _stageTokenLimitIncrease;
commitPhase.tokenPrice = _initialPrice;
// Setup stage 1 to n: The buy phase stages
uint256 previousStageTokenLimit = _stageTokenLimitIncrease;
// Update stages: start, end, price
for (uint8 i = 1; i <= _stageCount; i++) {
// Get i-th stage
Stage storage byStage = stages[i];
// set the stage limit amount
byStage.tokenLimit = previousStageTokenLimit.add(_stageTokenLimitIncrease);
// Store the current stage endBlock in order to update the next one
previousStageTokenLimit = byStage.tokenLimit;
// At each stage the token price increases by _stagePriceIncrease * stageCount
byStage.tokenPrice = _initialPrice.add(_stagePriceIncrease.mul(i));
}
// UPDATE global STATS
// The buy phase starts on the subsequent block of the commitPhase's (stage0) endBlock
buyPhaseStartBlock = _buyPhaseStartBlock;
// The buy phase ends when the lat stage ends
buyPhaseEndBlock = _buyPhaseEndBlock;
// The duration of buyPhase in blocks
buyPhaseBlockCount = buyPhaseEndBlock.sub(buyPhaseStartBlock).add(1);
// The contract is now initialized
initialized = true;
}
/*
* Public functions
* ------------------------------------------------------------------------------------------------
*/
/*
* Public functions
* The main way to interact with the rICO.
*/
/**
* @notice FALLBACK function: If the amount sent is smaller than `minContribution` it cancels all pending contributions.
* IF you are a known contributor with at least 1 contribution and you are whitelisted, you can send ETH without calling "commit()" to contribute more.
*/
function()
external
payable
isInitialized
isNotFrozen
{
Participant storage participantStats = participants[msg.sender];
// allow to commit directly if its a known user with at least 1 contribution
if (participantStats.whitelisted == true && participantStats.contributions > 0) {
commit();
// otherwise try to cancel
} else {
require(msg.value < minContribution, 'To contribute call commit() [0x3c7a3aff] and send ETH along.');
// Participant cancels pending contributions.
cancelPendingContributions(msg.sender, msg.value);
}
}
/**
* @notice ERC777TokensRecipient implementation for receiving ERC777 tokens.
* @param _from Token sender.
* @param _amount Token amount.
*/
function tokensReceived(
address,
address _from,
address,
uint256 _amount,
bytes calldata,
bytes calldata
)
external
isInitialized
isNotFrozen
{
// rICO should only receive tokens from the rICO token contract.
// Transactions from any other token contract revert
require(msg.sender == tokenAddress, "Unknown token contract sent tokens.");
// Project wallet adds tokens to the sale
if (_from == projectAddress) {
// increase the supply
tokenSupply = tokenSupply.add(_amount);
initialTokenSupply = initialTokenSupply.add(_amount);
// rICO participant sends tokens back
} else {
withdraw(_from, _amount);
}
}
/**
* @notice Allows a participant to reserve tokens by committing ETH as contributions.
*
* Function signature: 0x3c7a3aff
*/
function commit()
public
payable
isInitialized
isNotFrozen
isRunning
{
// Reject contributions lower than the minimum amount, and max than maxContribution
require(msg.value >= minContribution, "Value sent is less than the minimum contribution.");
// Participant initial state record
uint8 currentStage = getCurrentStage();
Participant storage participantStats = participants[msg.sender];
ParticipantStageDetails storage byStage = participantStats.stages[currentStage];
require(participantStats.committedETH.add(msg.value) <= maxContribution, "Value sent is larger than the maximum contribution.");
// Check if participant already exists
if (participantStats.contributions == 0) {
// Identify the participants by their Id
participantsById[participantCount] = msg.sender;
// Increase participant count
participantCount++;
}
// UPDATE PARTICIPANT STATS
participantStats.contributions++;
participantStats.pendingETH = participantStats.pendingETH.add(msg.value);
byStage.pendingETH = byStage.pendingETH.add(msg.value);
// UPDATE GLOBAL STATS
pendingETH = pendingETH.add(msg.value);
emit PendingContributionAdded(
msg.sender,
msg.value,
uint32(participantStats.contributions),
currentStage
);
// If whitelisted, process the contribution automatically
if (participantStats.whitelisted == true) {
acceptContributions(msg.sender);
}
}
/**
* @notice Allows a participant to cancel pending contributions
*
* Function signature: 0xea8a1af0
*/
function cancel()
external
payable
isInitialized
isNotFrozen
{
cancelPendingContributions(msg.sender, msg.value);
}
/**
* @notice Approves or rejects participants.
* @param _addresses The list of participant address.
* @param _approve Indicates if the provided participants are approved (true) or rejected (false).
*/
function whitelist(address[] calldata _addresses, bool _approve)
external
onlyWhitelistingAddress
isInitialized
isNotFrozen
isRunning
{
// Revert if the provided list is empty
require(_addresses.length > 0, "No addresses given to whitelist.");
for (uint256 i = 0; i < _addresses.length; i++) {
address participantAddress = _addresses[i];
Participant storage participantStats = participants[participantAddress];
if (_approve) {
if (participantStats.whitelisted == false) {
// If participants are approved: whitelist them and accept their contributions
participantStats.whitelisted = true;
emit WhitelistApproved(participantAddress, participantStats.pendingETH, uint32(participantStats.contributions));
}
// accept any pending ETH
acceptContributions(participantAddress);
} else {
participantStats.whitelisted = false;
emit WhitelistRejected(participantAddress, participantStats.pendingETH, uint32(participantStats.contributions));
// Cancel participants pending contributions.
cancelPendingContributions(participantAddress, 0);
}
}
}
/**
* @notice Allows the project to withdraw tokens.
* @param _tokenAmount The token amount.
*/
function projectTokenWithdraw(uint256 _tokenAmount)
external
onlyProjectAddress
isInitialized
{
require(_tokenAmount <= tokenSupply, "Requested amount too high, not enough tokens available.");
// decrease the supply
tokenSupply = tokenSupply.sub(_tokenAmount);
initialTokenSupply = initialTokenSupply.sub(_tokenAmount);
// sent all tokens from the contract to the _to address
// solium-disable-next-line security/no-send
IERC777(tokenAddress).send(projectAddress, _tokenAmount, "");
}
/**
* @notice Allows for the project to withdraw ETH.
* @param _ethAmount The ETH amount in wei.
*/
function projectWithdraw(uint256 _ethAmount)
external
onlyProjectAddress
isInitialized
isNotFrozen
{
// UPDATE the locked/unlocked ratio for the project
calcProjectAllocation();
// Get current allocated ETH to the project
uint256 availableForWithdraw = _projectUnlockedETH.sub(projectWithdrawnETH);
require(_ethAmount <= availableForWithdraw, "Requested amount too high, not enough ETH unlocked.");
// UPDATE global STATS
projectWithdrawCount++;
projectWithdrawnETH = projectWithdrawnETH.add(_ethAmount);
// Event emission
emit ProjectWithdraw(
projectAddress,
_ethAmount,
uint32(projectWithdrawCount)
);
emit TransferEvent(
uint8(TransferTypes.PROJECT_WITHDRAWN),
projectAddress,
_ethAmount
);
// Transfer ETH to project wallet
address(uint160(projectAddress)).transfer(_ethAmount);
}
function changeStage(uint8 _stageId, uint256 _tokenLimit, uint256 _tokenPrice)
external
onlyProjectAddress
isInitialized
{
stages[_stageId].tokenLimit = _tokenLimit;
stages[_stageId].tokenPrice = _tokenPrice;
if(_stageId > stageCount) {
stageCount = _stageId;
}
emit StageChanged(_stageId, _tokenLimit, _tokenPrice, getCurrentEffectiveBlockNumber());
}
function changeWhitelistingAddress(address _newAddress)
external
onlyProjectAddress
isInitialized
{
whitelistingAddress = _newAddress;
emit WhitelistingAddressChanged(whitelistingAddress, getCurrentStage(), getCurrentEffectiveBlockNumber());
}
function changeFreezerAddress(address _newAddress)
external
onlyProjectAddress
isInitialized
{
freezerAddress = _newAddress;
emit FreezerAddressChanged(freezerAddress, getCurrentStage(), getCurrentEffectiveBlockNumber());
}
/*
* Security functions.
* If the rICO runs fine the freezer address can be set to 0x0, for the beginning its good to have a safe guard.
*/
/**
* @notice Freezes the rICO in case of emergency.
*
* Function signature: 0x62a5af3b
*/
function freeze()
external
onlyFreezerAddress
isNotFrozen
{
frozen = true;
freezeStart = getCurrentEffectiveBlockNumber();
// Emit event
emit SecurityFreeze(freezerAddress, getCurrentStage(), freezeStart);
}
/**
* @notice Un-freezes the rICO.
*
* Function signature: 0x6a28f000
*/
function unfreeze()
external
onlyFreezerAddress
isFrozen
{
uint256 currentBlock = getCurrentEffectiveBlockNumber();
frozen = false;
frozenPeriod = frozenPeriod.add(
currentBlock.sub(freezeStart)
);
// Emit event
emit SecurityUnfreeze(freezerAddress, getCurrentStage(), currentBlock);
}
/**
* @notice Sets the freeze address to 0x0
*
* Function signature: 0xeb10dec7
*/
function disableEscapeHatch()
external
onlyFreezerAddress
isNotFrozen
{
freezerAddress = address(0);
rescuerAddress = address(0);
// Emit event
emit SecurityDisableEscapeHatch(freezerAddress, getCurrentStage(), getCurrentEffectiveBlockNumber());
}
/**
* @notice Moves the funds to a safe place, in case of emergency. Only possible, when the the rICO is frozen.
*/
function escapeHatch(address _to)
external
onlyRescuerAddress
isFrozen
{
require(getCurrentEffectiveBlockNumber() >= freezeStart.add(18000), 'Let it cool.. Wait at least ~3 days (18000 blk) before moving anything.');
uint256 tokenBalance = IERC777(tokenAddress).balanceOf(address(this));
uint256 ethBalance = address(this).balance;
// sent all tokens from the contract to the _to address
// solium-disable-next-line security/no-send
IERC777(tokenAddress).send(_to, tokenBalance, "");
// sent all ETH from the contract to the _to address
address(uint160(_to)).transfer(ethBalance);
// Emit events
emit SecurityEscapeHatch(rescuerAddress, _to, getCurrentStage(), getCurrentEffectiveBlockNumber());
emit TransferEvent(uint8(TransferTypes.FROZEN_ESCAPEHATCH_TOKEN), _to, tokenBalance);
emit TransferEvent(uint8(TransferTypes.FROZEN_ESCAPEHATCH_ETH), _to, ethBalance);
}
/*
* Public view functions
* ------------------------------------------------------------------------------------------------
*/
/**
* @notice Returns project's total unlocked ETH.
* @return uint256 The amount of ETH unlocked over the whole rICO.
*/
function getUnlockedProjectETH() public view returns (uint256) {
// calc from the last known point on
uint256 newlyUnlockedEth = calcUnlockedAmount(_projectCurrentlyReservedETH, _projectLastBlock);
return _projectUnlockedETH
.add(newlyUnlockedEth);
}
/**
* @notice Returns project's current available unlocked ETH reduced by what was already withdrawn.
* @return uint256 The amount of ETH available to the project for withdraw.
*/
function getAvailableProjectETH() public view returns (uint256) {
return getUnlockedProjectETH()
.sub(projectWithdrawnETH);
}
/**
* @notice Returns the participant's amount of locked tokens at the current block.
* @param _participantAddress The participant's address.
*/
function getParticipantReservedTokens(address _participantAddress) public view returns (uint256) {
Participant storage participantStats = participants[_participantAddress];
if(participantStats._currentReservedTokens == 0) {
return 0;
}
return participantStats._currentReservedTokens.sub(
calcUnlockedAmount(participantStats._currentReservedTokens, participantStats._lastBlock)
);
}
/**
* @notice Returns the participant's amount of unlocked tokens at the current block.
* This function is used for internal sanity checks.
* Note: this value can differ from the actual unlocked token balance of the participant, if he received tokens from other sources than the rICO.
* @param _participantAddress The participant's address.
*/
function getParticipantUnlockedTokens(address _participantAddress) public view returns (uint256) {
Participant storage participantStats = participants[_participantAddress];
return participantStats._unlockedTokens.add(
calcUnlockedAmount(participantStats._currentReservedTokens, participantStats._lastBlock)
);
}
/**
* @notice Returns the token amount that are still available at the current stage
* @return The amount of tokens
*/
function getAvailableTokenAtCurrentStage() public view returns (uint256) {
return stages[getCurrentStage()].tokenLimit.sub(
initialTokenSupply.sub(tokenSupply)
);
}
/**
* @notice Returns the current stage at current sold token amount
* @return The current stage ID
*/
function getCurrentStage() public view returns (uint8) {
return getStageByTokenLimit(
initialTokenSupply.sub(tokenSupply)
);
}
/**
* @notice Returns the current token price at the current stage.
* @return The current ETH price in wei.
*/
function getCurrentPrice() public view returns (uint256) {
return getPriceAtStage(getCurrentStage());
}
/**
* @notice Returns the token price at the specified stage ID.
* @param _stageId the stage ID at which we want to retrieve the token price.
*/
function getPriceAtStage(uint8 _stageId) public view returns (uint256) {
if (_stageId <= stageCount) {
return stages[_stageId].tokenPrice;
}
return stages[stageCount].tokenPrice;
}
/**
* @notice Returns the token price for when a specific amount of tokens is sold
* @param _tokenLimit The amount of tokens for which we want to know the respective token price
* @return The ETH price in wei
*/
function getPriceForTokenLimit(uint256 _tokenLimit) public view returns (uint256) {
return getPriceAtStage(getStageByTokenLimit(_tokenLimit));
}
/**
* @notice Returns the stage at a point where a certain amount of tokens is sold
* @param _tokenLimit The amount of tokens for which we want to know the stage ID
*/
function getStageByTokenLimit(uint256 _tokenLimit) public view returns (uint8) {
// Go through all stages, until we find the one that matches the supply
for (uint8 stageId = 0; stageId <= stageCount; stageId++) {
if(_tokenLimit <= stages[stageId].tokenLimit) {
return stageId;
}
}
// if amount is more than available stages return last stage with the highest price
return stageCount;
}
/**
* @notice Returns the rICOs available ETH to reserve tokens at a given stage.
* @param _stageId the stage ID.
*/
function committableEthAtStage(uint8 _stageId, uint8 _currentStage) public view returns (uint256) {
uint256 supply;
// past stages
if(_stageId < _currentStage) {
return 0;
// last stage
} else if(_stageId >= stageCount) {
supply = tokenSupply;
// current stage
} else if(_stageId == _currentStage) {
supply = stages[_currentStage].tokenLimit.sub(
initialTokenSupply.sub(tokenSupply)
);
// later stages
} else if(_stageId > _currentStage) {
supply = stages[_stageId].tokenLimit.sub(stages[_stageId - 1].tokenLimit); // calc difference to last stage
}
return getEthAmountForTokensAtStage(
supply
, _stageId);
}
/**
* @notice Returns the amount of ETH (in wei) for a given token amount at a given stage.
* @param _tokenAmount The amount of token.
* @param _stageId the stage ID.
* @return The ETH amount in wei
*/
function getEthAmountForTokensAtStage(uint256 _tokenAmount, uint8 _stageId) public view returns (uint256) {
return _tokenAmount
.mul(stages[_stageId].tokenPrice)
.div(10 ** 18);
}
/**
* @notice Returns the amount of tokens that given ETH would buy at a given stage.
* @param _ethAmount The ETH amount in wei.
* @param _stageId the stage ID.
* @return The token amount in its smallest unit (token "wei")
*/
function getTokenAmountForEthAtStage(uint256 _ethAmount, uint8 _stageId) public view returns (uint256) {
return _ethAmount
.mul(10 ** 18)
.div(stages[_stageId].tokenPrice);
}
/**
* @notice Returns the current block number: required in order to override when running tests.
*/
function getCurrentBlockNumber() public view returns (uint256) {
return uint256(block.number);
}
/**
* @notice Returns the current block number - the frozen period: required in order to override when running tests.
*/
function getCurrentEffectiveBlockNumber() public view returns (uint256) {
return uint256(block.number)
.sub(frozenPeriod); // make sure we deduct any frozenPeriod from calculations
}
/**
* @notice rICO HEART: Calculates the unlocked amount tokens/ETH beginning from the buy phase start or last block to the current block.
* This function is used by the participants as well as the project, to calculate the current unlocked amount.
*
* @return the unlocked amount of tokens or ETH.
*/
function calcUnlockedAmount(uint256 _amount, uint256 _lastBlock) public view returns (uint256) {
uint256 currentBlock = getCurrentEffectiveBlockNumber();
if(_amount == 0) {
return 0;
}
// Calculate WITHIN the buy phase
if (currentBlock >= buyPhaseStartBlock && currentBlock < buyPhaseEndBlock) {
// security/no-assign-params: "calcUnlockedAmount": Avoid assigning to function parameters.
uint256 lastBlock = _lastBlock;
if(lastBlock < buyPhaseStartBlock) {
lastBlock = buyPhaseStartBlock.sub(1); // We need to reduce it by 1, as the startBlock is always already IN the period.
}
// get the number of blocks that have "elapsed" since the last block
uint256 passedBlocks = currentBlock.sub(lastBlock);
// number of blocks ( ie: start=4/end=10 => 10 - 4 => 6 )
uint256 totalBlockCount = buyPhaseEndBlock.sub(lastBlock);
return _amount.mul(
passedBlocks.mul(10 ** 20)
.div(totalBlockCount)
).div(10 ** 20);
// Return everything AFTER the buy phase
} else if (currentBlock >= buyPhaseEndBlock) {
return _amount;
}
// Return nothing BEFORE the buy phase
return 0;
}
/*
* Internal functions
* ------------------------------------------------------------------------------------------------
*/
/**
* @notice Checks the projects core variables and ETH amounts in the contract for correctness.
*/
function sanityCheckProject() internal view {
// PROJECT: The sum of reserved + unlocked has to be equal the committedETH.
require(
committedETH == _projectCurrentlyReservedETH.add(_projectUnlockedETH),
'Project Sanity check failed! Reserved + Unlock must equal committedETH'
);
// PROJECT: The ETH in the rICO has to be the total of unlocked + reserved - withdraw
require(
address(this).balance == _projectUnlockedETH.add(_projectCurrentlyReservedETH).add(pendingETH).sub(projectWithdrawnETH),
'Project sanity check failed! balance = Unlock + Reserved - Withdrawn'
);
}
/**
* @notice Checks the projects core variables and ETH amounts in the contract for correctness.
*/
function sanityCheckParticipant(address _participantAddress) internal view {
Participant storage participantStats = participants[_participantAddress];
// PARTICIPANT: The sum of reserved + unlocked has to be equal the totalReserved.
require(
participantStats.reservedTokens == participantStats._currentReservedTokens.add(participantStats._unlockedTokens),
'Participant Sanity check failed! Reser. + Unlock must equal totalReser'
);
}
/**
* @notice Calculates the projects allocation since the last calculation.
*/
function calcProjectAllocation() internal {
uint256 newlyUnlockedEth = calcUnlockedAmount(_projectCurrentlyReservedETH, _projectLastBlock);
// UPDATE GLOBAL STATS
_projectCurrentlyReservedETH = _projectCurrentlyReservedETH.sub(newlyUnlockedEth);
_projectUnlockedETH = _projectUnlockedETH.add(newlyUnlockedEth);
_projectLastBlock = getCurrentEffectiveBlockNumber();
sanityCheckProject();
}
/**
* @notice Calculates the participants allocation since the last calculation.
*/
function calcParticipantAllocation(address _participantAddress) internal {
Participant storage participantStats = participants[_participantAddress];
// UPDATE the locked/unlocked ratio for this participant
participantStats._unlockedTokens = getParticipantUnlockedTokens(_participantAddress);
participantStats._currentReservedTokens = getParticipantReservedTokens(_participantAddress);
// RESET BLOCK NUMBER: Force the unlock calculations to start from this point in time.
participantStats._lastBlock = getCurrentEffectiveBlockNumber();
// UPDATE the locked/unlocked ratio for the project as well
calcProjectAllocation();
}
/**
* @notice Cancels any participant's pending ETH contributions.
* Pending is any ETH from participants that are not whitelisted yet.
*/
function cancelPendingContributions(address _participantAddress, uint256 _sentValue)
internal
isInitialized
isNotFrozen
{
Participant storage participantStats = participants[_participantAddress];
uint256 participantPendingEth = participantStats.pendingETH;
// Fail silently if no ETH are pending
if(participantPendingEth == 0) {
// sent at least back what he contributed
if(_sentValue > 0) {
address(uint160(_participantAddress)).transfer(_sentValue);
}
return;
}
// UPDATE PARTICIPANT STAGES
for (uint8 stageId = 0; stageId <= stageCount; stageId++) {
participantStats.stages[stageId].pendingETH = 0;
}
// UPDATE PARTICIPANT STATS
participantStats.pendingETH = 0;
// UPDATE GLOBAL STATS
canceledETH = canceledETH.add(participantPendingEth);
pendingETH = pendingETH.sub(participantPendingEth);
// Emit events
emit PendingContributionsCanceled(_participantAddress, participantPendingEth, uint32(participantStats.contributions));
emit TransferEvent(
uint8(TransferTypes.CONTRIBUTION_CANCELED),
_participantAddress,
participantPendingEth
);
// transfer ETH back to participant including received value
address(uint160(_participantAddress)).transfer(participantPendingEth.add(_sentValue));
// SANITY check
sanityCheckParticipant(_participantAddress);
sanityCheckProject();
}
/**
* @notice Accept a participant's contribution.
* @param _participantAddress Participant's address.
*/
function acceptContributions(address _participantAddress)
internal
isInitialized
isNotFrozen
isRunning
{
Participant storage participantStats = participants[_participantAddress];
// Fail silently if no ETH are pending
if (participantStats.pendingETH == 0) {
return;
}
uint8 currentStage = getCurrentStage();
uint256 totalRefundedETH;
uint256 totalNewReservedTokens;
calcParticipantAllocation(_participantAddress);
// set the first contribution block
if(participantStats.committedETH == 0) {
participantStats.firstContributionBlock = participantStats._lastBlock; // `_lastBlock` was set in calcParticipantAllocation()
}
// Iterate over all stages and their pending contributions
for (uint8 stageId = 0; stageId <= stageCount; stageId++) {
ParticipantStageDetails storage byStage = participantStats.stages[stageId];
// skip if not ETH is pending
if (byStage.pendingETH == 0) {
continue;
}
// skip if stage is below "currentStage" (as they have no available tokens)
if(stageId < currentStage) {
// add this stage pendingETH to the "currentStage"
participantStats.stages[currentStage].pendingETH = participantStats.stages[currentStage].pendingETH.add(byStage.pendingETH);
// and reset this stage
byStage.pendingETH = 0;
continue;
}
// --> We continue only if in "currentStage" or later stages
uint256 maxCommittableEth = committableEthAtStage(stageId, currentStage);
uint256 newlyCommittableEth = byStage.pendingETH;
uint256 returnEth = 0;
uint256 overflowEth = 0;
// If incoming value is higher than what we can accept,
// just accept the difference and return the rest
if (newlyCommittableEth > maxCommittableEth) {
overflowEth = newlyCommittableEth.sub(maxCommittableEth);
newlyCommittableEth = maxCommittableEth;
// if in the last stage, return ETH
if (stageId == stageCount) {
returnEth = overflowEth;
totalRefundedETH = totalRefundedETH.add(returnEth);
// if below the last stage, move pending ETH to the next stage
} else {
participantStats.stages[stageId + 1].pendingETH = participantStats.stages[stageId + 1].pendingETH.add(overflowEth);
byStage.pendingETH = byStage.pendingETH.sub(overflowEth);
}
}
// convert ETH to TOKENS
uint256 newTokenAmount = getTokenAmountForEthAtStage(
newlyCommittableEth, stageId
);
totalNewReservedTokens = totalNewReservedTokens.add(newTokenAmount);
// UPDATE PARTICIPANT STATS
participantStats._currentReservedTokens = participantStats._currentReservedTokens.add(newTokenAmount);
participantStats.reservedTokens = participantStats.reservedTokens.add(newTokenAmount);
participantStats.committedETH = participantStats.committedETH.add(newlyCommittableEth);
participantStats.pendingETH = participantStats.pendingETH.sub(newlyCommittableEth).sub(returnEth);
byStage.pendingETH = byStage.pendingETH.sub(newlyCommittableEth).sub(returnEth);
// UPDATE GLOBAL STATS
tokenSupply = tokenSupply.sub(newTokenAmount);
pendingETH = pendingETH.sub(newlyCommittableEth).sub(returnEth);
committedETH = committedETH.add(newlyCommittableEth);
_projectCurrentlyReservedETH = _projectCurrentlyReservedETH.add(newlyCommittableEth);
// Emit event
emit ContributionsAccepted(_participantAddress, newlyCommittableEth, newTokenAmount, stageId);
}
// Refund what couldn't be accepted
if (totalRefundedETH > 0) {
emit TransferEvent(uint8(TransferTypes.CONTRIBUTION_ACCEPTED_OVERFLOW), _participantAddress, totalRefundedETH);
address(uint160(_participantAddress)).transfer(totalRefundedETH);
}
// Transfer tokens to the participant
// solium-disable-next-line security/no-send
IERC777(tokenAddress).send(_participantAddress, totalNewReservedTokens, "");
// SANITY CHECK
sanityCheckParticipant(_participantAddress);
sanityCheckProject();
}
/**
* @notice Allow a participant to withdraw by sending tokens back to rICO contract.
* @param _participantAddress participant address.
* @param _returnedTokenAmount The amount of tokens returned.
*/
function withdraw(address _participantAddress, uint256 _returnedTokenAmount)
internal
isInitialized
isNotFrozen
isRunning
{
Participant storage participantStats = participants[_participantAddress];
calcParticipantAllocation(_participantAddress);
require(_returnedTokenAmount > 0, 'You can not withdraw without sending tokens.');
require(participantStats._currentReservedTokens > 0 && participantStats.reservedTokens > 0, 'You can not withdraw, you have no locked tokens.');
uint256 returnedTokenAmount = _returnedTokenAmount;
uint256 overflowingTokenAmount;
uint256 returnEthAmount;
// Only allow reserved tokens be returned, return the overflow.
if (returnedTokenAmount > participantStats._currentReservedTokens) {
overflowingTokenAmount = returnedTokenAmount.sub(participantStats._currentReservedTokens);
returnedTokenAmount = participantStats._currentReservedTokens;
}
// Calculate the return amount
returnEthAmount = participantStats.committedETH.mul(
returnedTokenAmount.sub(1).mul(10 ** 20) // deduct 1 token-wei to minimize rounding issues
.div(participantStats.reservedTokens)
).div(10 ** 20);
// UPDATE PARTICIPANT STATS
participantStats.withdraws++;
participantStats._currentReservedTokens = participantStats._currentReservedTokens.sub(returnedTokenAmount);
participantStats.reservedTokens = participantStats.reservedTokens.sub(returnedTokenAmount);
participantStats.committedETH = participantStats.committedETH.sub(returnEthAmount);
// UPDATE global STATS
tokenSupply = tokenSupply.add(returnedTokenAmount);
withdrawnETH = withdrawnETH.add(returnEthAmount);
committedETH = committedETH.sub(returnEthAmount);
_projectCurrentlyReservedETH = _projectCurrentlyReservedETH.sub(returnEthAmount);
// Return overflowing tokens received
if (overflowingTokenAmount > 0) {
// send tokens back to participant
bytes memory data;
// Emit event
emit TransferEvent(uint8(TransferTypes.PARTICIPANT_WITHDRAW_OVERFLOW), _participantAddress, overflowingTokenAmount);
// solium-disable-next-line security/no-send
IERC777(tokenAddress).send(_participantAddress, overflowingTokenAmount, data);
}
// Emit events
emit ParticipantWithdraw(_participantAddress, returnEthAmount, returnedTokenAmount, uint32(participantStats.withdraws));
emit TransferEvent(uint8(TransferTypes.PARTICIPANT_WITHDRAW), _participantAddress, returnEthAmount);
// Return ETH back to participant
address(uint160(_participantAddress)).transfer(returnEthAmount);
// SANITY CHECK
sanityCheckParticipant(_participantAddress);
sanityCheckProject();
}
/*
* Modifiers
*/
/**
* @notice Checks if the sender is the project.
*/
modifier onlyProjectAddress() {
require(msg.sender == projectAddress, "Only the project can call this method.");
_;
}
/**
* @notice Checks if the sender is the deployer.
*/
modifier onlyDeployingAddress() {
require(msg.sender == deployingAddress, "Only the deployer can call this method.");
_;
}
/**
* @notice Checks if the sender is the whitelist controller.
*/
modifier onlyWhitelistingAddress() {
require(msg.sender == whitelistingAddress, "Only the whitelist controller can call this method.");
_;
}
/**
* @notice Checks if the sender is the freezer controller address.
*/
modifier onlyFreezerAddress() {
require(msg.sender == freezerAddress, "Only the freezer address can call this method.");
_;
}
/**
* @notice Checks if the sender is the freezer controller address.
*/
modifier onlyRescuerAddress() {
require(msg.sender == rescuerAddress, "Only the rescuer address can call this method.");
_;
}
/**
* @notice Requires the contract to have been initialized.
*/
modifier isInitialized() {
require(initialized == true, "Contract must be initialized.");
_;
}
/**
* @notice Requires the contract to NOT have been initialized,
*/
modifier isNotInitialized() {
require(initialized == false, "Contract can not be initialized.");
_;
}
/**
* @notice @dev Requires the contract to be frozen.
*/
modifier isFrozen() {
require(frozen == true, "rICO has to be frozen!");
_;
}
/**
* @notice @dev Requires the contract not to be frozen.
*/
modifier isNotFrozen() {
require(frozen == false, "rICO is frozen!");
_;
}
/**
* @notice Checks if the rICO is running.
*/
modifier isRunning() {
uint256 blockNumber = getCurrentEffectiveBlockNumber();
require(blockNumber >= commitPhaseStartBlock && blockNumber <= buyPhaseEndBlock, "Current block is outside the rICO period.");
_;
}
}
|
Returns the rICOs available ETH to reserve tokens at a given stage. _stageId the stage ID./ past stages last stage current stage later stages
|
function committableEthAtStage(uint8 _stageId, uint8 _currentStage) public view returns (uint256) {
uint256 supply;
if(_stageId < _currentStage) {
return 0;
supply = tokenSupply;
supply = stages[_currentStage].tokenLimit.sub(
initialTokenSupply.sub(tokenSupply)
);
}
return getEthAmountForTokensAtStage(
supply
, _stageId);
}
| 6,399,478 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import '@openzeppelin/contracts/security/Pausable.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import './ERC721NonTransferable.sol';
/**
* @title Proof of Residency
* @custom:security-contact [email protected]
*
* @notice An non-transferable ERC721 token for Proof of Personhood. Proves residency at a physical address
* which is kept private.
*
* @dev Uses a commit-reveal scheme to commit to a country and have a token issued based on that commitment.
*/
contract ProofOfResidency is ERC721NonTransferable, Pausable, Ownable, ReentrancyGuard {
/// @notice The tax + donation percentages (10% to MAW, 10% to treasury)
uint256 private constant TAX_AND_DONATION_PERCENT = 20;
/// @notice The waiting period before minting becomes available
uint256 private constant COMMITMENT_WAITING_PERIOD = 1 weeks;
/// @notice The period during which minting is available (after the preminting period)
uint256 private constant COMMITMENT_PERIOD = 5 weeks;
/// @notice The timelock period until committers can withdraw (after last activity)
uint256 private constant TIMELOCK_WAITING_PERIOD = 8 weeks;
/// @notice Multiplier for country token IDs
uint256 private constant LOCATION_MULTIPLIER = 1e15;
/// @notice The version of this contract
string private constant VERSION = '1';
/// @notice The EIP-712 typehash for the contract's domain
bytes32 private constant DOMAIN_TYPEHASH =
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)');
/// @notice The EIP-712 typehash for the commitment struct used by the contract
bytes32 private constant COMMITMENT_TYPEHASH =
keccak256('Commitment(address to,bytes32 commitment,uint256 nonce)');
/// @notice The domain separator for EIP-712
bytes32 private immutable _domainSeparator;
/// @notice Reservation price for tokens to contribute to the protocol
/// Incentivizes users to continue after requesting a letter
uint256 public reservePrice;
/// @notice Project treasury to send tax + donation
address public projectTreasury;
/// @notice Token counts for a country
/// @dev Uses uint16 for country ID (which will overflow at 65535)
/// https://en.wikipedia.org/wiki/ISO_3166-1_numeric
mapping(uint16 => uint256) public countryTokenCounts;
/// @notice Committer addresses responsible for managing secret commitments to an address
mapping(address => bool) private _committers;
/// @notice Total contributions for each committer
mapping(address => Contribution) public committerContributions;
/// @notice Commitments for a wallet address
mapping(address => Commitment) public commitments;
/// @notice Include a nonce in every hashed message, and increment the nonce to prevent replay attacks
mapping(address => uint256) public nonces;
/// @notice Expiration for challenges made for an address
mapping(address => uint256) private _tokenChallengeExpirations;
/// @notice The baseURI for the metadata of this contract
string private _metadataBaseUri;
/// @notice The struct to represent commitments to an address
struct Commitment {
uint256 validAt;
bytes32 commitment;
address committer;
uint256 value;
}
/// @notice The struct to represent contributions which a committer can withdraw
struct Contribution {
uint256 lockedUntil;
uint256 value;
}
/// @notice Event emitted when a commitment is made to an address
event CommitmentCreated(address indexed to, address indexed committer, bytes32 commitment);
/// @notice Event emitted when a committer is added
event CommitterAdded(address indexed committer);
/// @notice Event emitted when a committer is removed
event CommitterRemoved(address indexed committer, uint256 fundsLost, bool forceReclaim);
/// @notice Event emitted when a token is challenged
event TokenChallenged(address indexed owner, uint256 indexed tokenId);
/// @notice Event emitted when a token challenge is completed successfully
event TokenChallengeCompleted(address indexed owner, uint256 indexed tokenId);
/// @notice Event emitted when the price is changed
event PriceChanged(uint256 indexed newPrice);
constructor(
address initialCommitter,
address initialTreasury,
string memory initialBaseUri,
uint256 initialPrice
) ERC721NonTransferable('Proof of Residency Protocol', 'PORP') {
// slither-disable-next-line missing-zero-check
projectTreasury = initialTreasury;
reservePrice = initialPrice;
_metadataBaseUri = initialBaseUri;
_committers[initialCommitter] = true;
_domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
keccak256(bytes(VERSION)),
block.chainid,
address(this)
)
);
}
/**
* @notice Sets the main project treasury.
*/
function setProjectTreasury(address newTreasury) external onlyOwner {
// slither-disable-next-line missing-zero-check
projectTreasury = newTreasury;
}
/**
* @notice Adds a new committer address with their treasury.
* @dev This cannot be a contract account, since it would not be able to sign
* commitments.
*/
function addCommitter(address newCommitter) external onlyOwner {
_committers[newCommitter] = true;
emit CommitterAdded(newCommitter);
}
/**
* @notice Removes a committer address and optionally transfers their contributions to be owned
* by the treasury.
*/
function removeCommitter(address removedCommitter, bool forceReclaim) external onlyOwner {
Contribution memory lostContribution = committerContributions[removedCommitter];
require(
forceReclaim ? lostContribution.value != 0 : lostContribution.value == 0,
'Cannot force or non-0'
);
if (forceReclaim) {
Contribution storage treasuryContribution = committerContributions[projectTreasury];
treasuryContribution.value += lostContribution.value;
treasuryContribution.lockedUntil = block.timestamp + TIMELOCK_WAITING_PERIOD;
}
delete _committers[removedCommitter];
delete committerContributions[removedCommitter];
emit CommitterRemoved(removedCommitter, lostContribution.value, forceReclaim);
}
/**
* @notice Allows the project treasury to reclaim expired contribution(s). This allows funds to
* not get locked up in the contract indefinitely.
*/
function reclaimExpiredContributions(address[] memory unclaimedAddresses) external onlyOwner {
uint256 totalAddition = 0;
for (uint256 i = 0; i < unclaimedAddresses.length; i++) {
Commitment memory existingCommitment = commitments[unclaimedAddresses[i]];
// require that the commitment expired so it can be claimed
// slither-disable-next-line timestamp
require(existingCommitment.validAt + COMMITMENT_PERIOD <= block.timestamp, 'Still valid');
totalAddition += existingCommitment.value;
// slither-disable-next-line costly-loop
delete commitments[unclaimedAddresses[i]];
}
Contribution storage treasuryContribution = committerContributions[projectTreasury];
treasuryContribution.value += totalAddition;
treasuryContribution.lockedUntil = block.timestamp + TIMELOCK_WAITING_PERIOD;
}
/**
* @notice Burns tokens corresponding to a list of addresses. Only allowed after a token challenge has been
* issued and subsequently expired.
*/
function burnFailedChallenges(address[] memory addresses) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
require(tokenChallengeExpired(addresses[i]), 'Challenge not expired');
// use 0 as the index since this is the only possible index, if a token exists
uint256 tokenId = tokenOfOwnerByIndex(addresses[i], 0);
Commitment memory existingCommitment = commitments[addresses[i]];
// pay the value to the committer for the `mint` action the requester was unable to execute on
if (existingCommitment.committer != address(0)) {
Contribution storage contribution = committerContributions[existingCommitment.committer];
// add the value to the committers successful commitments
contribution.value += existingCommitment.value;
contribution.lockedUntil = block.timestamp + TIMELOCK_WAITING_PERIOD;
}
_burn(tokenId);
}
}
/**
* @notice Initiates a challenge for a list of addresses. The user must re-request
* a commitment and verify a mailing address again.
*/
function challenge(address[] memory addresses) external onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
// use 0 as the index since this is the only possible index, if a token exists
uint256 tokenId = tokenOfOwnerByIndex(addresses[i], 0);
_tokenChallengeExpirations[addresses[i]] =
block.timestamp +
COMMITMENT_WAITING_PERIOD +
COMMITMENT_PERIOD;
emit TokenChallenged(addresses[i], tokenId);
}
}
/**
* @notice Sets the value required to request an NFT. Deliberately as low as possible to
* incentivize committers, this may be changed to be lower/higher.
*/
function setPrice(uint256 newPrice) external onlyOwner {
reservePrice = newPrice;
emit PriceChanged(newPrice);
}
/**
* @notice Sets the base URI for the metadata.
*/
function setBaseURI(string memory newBaseUri) external onlyOwner {
_metadataBaseUri = newBaseUri;
}
/**
* @notice Pauses the contract's commit-reveal functions.
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice Unpauses the contract's commit-reveal functions.
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @notice Commits a wallet address to a physical address using signed data from a committer.
* Signatures are used to prevent committers from paying gas fees for commitments.
*
* @dev Must be signed according to https://eips.ethereum.org/EIPS/eip-712
*/
function commitAddress(
address to,
bytes32 commitment,
uint8 v,
bytes32 r,
bytes32 s
) external payable whenNotPaused {
// Validates a signature which corresponds to one signed by a committer with the
// https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] method as part of EIP-712.
bytes32 structHash = keccak256(abi.encode(COMMITMENT_TYPEHASH, to, commitment, nonces[to]));
bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
// require that the signatory is actually a committer
require(_committers[signatory], 'Signatory non-committer');
require(msg.value == reservePrice, 'Incorrect value');
Commitment storage existingCommitment = commitments[to];
// if there is an existing commitment and it hasn't expired yet
bool isExistingExpired = existingCommitment.commitment != 0 &&
block.timestamp > existingCommitment.validAt + COMMITMENT_PERIOD;
// slither-disable-next-line timestamp
require(existingCommitment.commitment == 0 || isExistingExpired, 'Existing commitment');
// reclaim the expired commitment contributed value to the treasury
// does not get sent to the committer, so they are not incentivized to provide unsuccessful commitments
if (isExistingExpired) {
Contribution storage treasuryContribution = committerContributions[projectTreasury];
treasuryContribution.value += existingCommitment.value;
treasuryContribution.lockedUntil = block.timestamp + TIMELOCK_WAITING_PERIOD;
}
existingCommitment.committer = signatory;
existingCommitment.validAt = block.timestamp + COMMITMENT_WAITING_PERIOD;
existingCommitment.commitment = commitment;
existingCommitment.value = msg.value;
emit CommitmentCreated(to, signatory, commitment);
}
/**
* @notice Mints a new token for the given country/commitment.
*/
function mint(uint16 country, string memory commitment)
external
whenNotPaused
nonReentrant
returns (uint256)
{
// requires the requester to have no tokens - they cannot transfer, but may have burned a previous token
// this is not performed in the commit step, since that is also used for challenges
require(balanceOf(_msgSender()) == 0, 'Already owns token');
Commitment memory existingCommitment = _validateAndDeleteCommitment(country, commitment);
Contribution storage contribution = committerContributions[existingCommitment.committer];
// add the value to the committers successful commitments
contribution.value += existingCommitment.value;
contribution.lockedUntil = block.timestamp + TIMELOCK_WAITING_PERIOD;
countryTokenCounts[country] += 1; // increment before minting so count starts at 1
uint256 tokenId = uint256(country) * LOCATION_MULTIPLIER + uint256(countryTokenCounts[country]);
_safeMint(_msgSender(), tokenId);
return tokenId;
}
/**
* @notice Responds to a challenge with a token ID and corresponding country/commitment.
*/
function respondToChallenge(
uint256 tokenId,
uint16 country,
string memory commitment
) external whenNotPaused nonReentrant returns (bool) {
// ensure that the country is the same as the current token ID
require(tokenId / LOCATION_MULTIPLIER == country, 'Country not valid');
Commitment memory existingCommitment = _validateAndDeleteCommitment(country, commitment);
delete _tokenChallengeExpirations[_msgSender()];
emit TokenChallengeCompleted(_msgSender(), tokenId);
// slither-disable-next-line low-level-calls
(bool success, ) = _msgSender().call{ value: existingCommitment.value }('');
require(success, 'Unable to refund');
return true;
}
/**
* @notice Withdraws funds from the contract to the committer.
*
* Applies a tax to the withdrawal for the protocol.
*/
function withdraw() external nonReentrant {
Contribution memory contribution = committerContributions[_msgSender()];
// enforce the timelock for the withdrawal
// slither-disable-next-line timestamp
require(contribution.lockedUntil < block.timestamp, 'Timelocked');
uint256 taxAndDonation = (contribution.value * TAX_AND_DONATION_PERCENT) / 100;
require(taxAndDonation > 0, 'Tax not over 0');
delete committerContributions[_msgSender()];
// slither-disable-next-line low-level-calls
(bool success1, ) = projectTreasury.call{ value: taxAndDonation }('');
require(success1, 'Unable to send project treasury');
// slither-disable-next-line low-level-calls
(bool success2, ) = _msgSender().call{ value: contribution.value - taxAndDonation }('');
require(success2, 'Unable to withdraw');
}
/**
* @notice Gets if a commitment for the sender's address is upcoming.
*/
function commitmentPeriodIsUpcoming() external view returns (bool) {
Commitment memory existingCommitment = commitments[_msgSender()];
// slither-disable-next-line timestamp
return block.timestamp < existingCommitment.validAt;
}
/**
* @notice Gets if the commitment for the sender's address is in the time window where they
* are able to mint.
*/
function commitmentPeriodIsValid() public view returns (bool) {
Commitment memory existingCommitment = commitments[_msgSender()];
// slither-disable-next-line timestamp
return
block.timestamp >= existingCommitment.validAt &&
block.timestamp <= existingCommitment.validAt + COMMITMENT_PERIOD;
}
/**
* @notice Gets if a token challenge for an address has expired (and becomes eligible for
* burning/re-issuing).
*/
function tokenChallengeExpired(address owner) public view returns (bool) {
// slither-disable-next-line timestamp
return tokenChallengeExists(owner) && _tokenChallengeExpirations[owner] <= block.timestamp;
}
/**
* @notice Gets if a token challenge exists for an address. This can be used in
* downstream projects to ensure that a user does not have any outstanding challenges.
*/
function tokenChallengeExists(address owner) public view returns (bool) {
// slither-disable-next-line timestamp
return _tokenChallengeExpirations[owner] != 0;
}
/**
* @dev Validates a commitment and deletes the Commitment from the mapping.
*/
function _validateAndDeleteCommitment(uint16 country, string memory commitment)
private
returns (Commitment memory existingCommitment)
{
existingCommitment = commitments[_msgSender()];
require(
existingCommitment.commitment ==
keccak256(abi.encode(_msgSender(), country, commitment, nonces[_msgSender()])),
'Commitment incorrect'
);
require(commitmentPeriodIsValid(), 'Commitment period invalid');
// requires that the original committer is still valid
require(_committers[existingCommitment.committer], 'Signatory removed');
// increment the nonce for the sender
nonces[_msgSender()] += 1;
delete commitments[_msgSender()];
}
/**
* @notice Contract URI for OpenSea and other NFT services.
*/
function contractURI() external view returns (string memory) {
return string(abi.encodePacked(_baseURI(), 'contract'));
}
/**
* @dev Base URI override for the contract.
*/
function _baseURI() internal view override returns (string memory) {
return _metadataBaseUri;
}
}
|
Gets if a token challenge for an address has expired (and becomes eligible for burning/re-issuing)./ slither-disable-next-line timestamp
|
function tokenChallengeExpired(address owner) public view returns (bool) {
return tokenChallengeExists(owner) && _tokenChallengeExpirations[owner] <= block.timestamp;
}
| 7,326,936 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.9;
/* EXTERNAL DEPENDENCIES */
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/escrow/Escrow.sol";
/* INTERNAL DEPENDENCIES */
import "./CommonStructs.sol";
/**
* @title Instructions Provider contract
* @notice This contract is responsible for storing the
* implementations of the instructions supported used in
* the Interpreter.InterpretArticle low level calls
*/
contract InstructionsProvider is Ownable {
/* STORAGE */
/// @dev Proxy instance reference
address public proxyInstanceRef;
/// @dev Interpreter contract reference
address public interpreterContractRef;
/// @dev OpenZeppelin Escrow contract reference
Escrow public escrowInstance;
/* EVENTS */
/**
* @dev Event emitted when the Interpreter contract reference is changed
* @param _from Caller address
* @param _old Old address of the Interpreter contract
* @param _new New address of the Interpreter contract
*/
event SetInterpreterContractRef(address _from, address _old, address _new);
/**
* @dev Event emitted when the Escrow contract reference is changed
* @param _from Caller address
* @param _old Old address of the Escrow contract
* @param _new New address of the Escrow contract
*/
event SetEscrowContractRef(address _from, address _old, address _new);
/* MODIFIERS */
/// @dev Assess that the caller is the Interpreter contract instance
modifier onlyInterpreter() {
require(msg.sender==interpreterContractRef, "InstructionsProvider: Caller is not the Interpreter");
_;
}
/// @dev Assess that the caller is the Proxy contract instance
modifier onlyProxy() {
require(msg.sender==proxyInstanceRef, "InstructionsProvider: Only Proxy may call");
_;
}
/* PUBLIC INTERFACE */
constructor(address _address) {
if (_address==address(0))
escrowInstance = new Escrow();
else
escrowInstance = Escrow(_address);
}
/**
* @dev Sets the Interpreter contract reference. Emits a SetInterpreterInstance event
* @param _address Address of the Interpreter contract
*/
function setProxyInstanceRef(address _address) external onlyOwner {
proxyInstanceRef = _address;
}
/**
* @dev Sets the Interpreter contract reference. Emits a SetInterpreterInstance event
* @param _new Address of the Interpreter contract
*/
function setInterpreterContractRef(address _new) public onlyOwner {
address old = interpreterContractRef;
interpreterContractRef = _new;
emit SetInterpreterContractRef(msg.sender, old, _new);
}
/**
* @dev Sets the Escrow instance. Emits a SetEscrowInstance event
* @param _new Address of the Escrow contract
*/
function setEscrowContractRef(address _new) public onlyOwner {
address old = address(escrowInstance);
escrowInstance = Escrow(_new);
emit SetEscrowContractRef(msg.sender, old, _new);
}
/**
* @dev Upgrability: Allow the old InstructionsProvider instance
* to transfer the Escrow ownership to the new instance
* @param _address Address of the new InstructionsProvider instance
*/
function transferEscrow(address _address) external onlyOwner {
escrowInstance.transferOwnership(_address);
//escrowInstance = Escrow(address(0));
}
/**
* @dev Escrow: Returns msg.sender balance
* @return uint Balance of msg.sender
*/
function getBalance() public view returns (uint) {
uint deposits = escrowInstance.depositsOf(msg.sender);
return deposits;
}
/**
* @dev msg.sender withdraws his total balance
* Modifier hasBalance: msg.sender must have enough balance in the escrow
*/
function withdraw(address _from) external onlyProxy {
require(escrowInstance.depositsOf(_from)>0, "InstructionsProvider : Not enough balance");
escrowInstance.withdraw(payable(_from));
}
/* Upgrability: Instructions implementations */
/**
* @dev Checks if the addresses in parameters are equal
* @param _address1 First address used in the comparison
* @param _address2 Second address used in the comparison
* @return Returns true if both addresses are equal
*/
function _ifAddress(address _address1, address _address2) public view onlyInterpreter returns (bool) {
return (_address1 == _address2);
}
/**
* @dev Escrow: Deposit msg.value to the _to address
* @param _to The address to which we deposit ETH
*/
function _transfer(address _to) public payable onlyInterpreter {
escrowInstance.deposit{value:msg.value}(_to);
}
/**
* @dev Checks if the msg.value is bigger than the param
* @param _msgValue Message value
* @param _comparisonValue Value used for comparison
* @return Returns true if the message value is bigger than the param
*/
function _ifMsgValueBigger(uint _msgValue, uint _comparisonValue) public view onlyInterpreter returns (bool) {
return (_msgValue > _comparisonValue);
}
/* OVERRIDE & BLOCK UNUSED INHERITED FUNCTIONS */
/**
* @dev Block OpenZeppelin Ownable.renounceOwnership
* @notice Will always revert
*/
function renounceOwnership() public pure override {
revert('Contract cannot be revoked');
}
}
|
Block OpenZeppelin Ownable.renounceOwnership Will always revert/
|
function renounceOwnership() public pure override {
revert('Contract cannot be revoked');
}
| 2,485,407 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
import {LibAppStorage, AppStorage, SvgLayer} from "./LibAppStorage.sol";
//import "hardhat/console.sol";
library LibSvg {
event StoreSvg(LibSvg.SvgTypeAndSizes[] _typesAndSizes);
struct SvgTypeAndSizes {
bytes32 svgType;
uint256[] sizes;
}
function getSvg(bytes32 _svgType, uint256 _id) internal view returns (bytes memory svg_) {
AppStorage storage s = LibAppStorage.diamondStorage();
SvgLayer[] storage svgLayers = s.svgLayers[_svgType];
svg_ = getSvg(svgLayers, _id);
}
function getSvg(SvgLayer[] storage _svgLayers, uint256 _id) internal view returns (bytes memory svg_) {
require(_id < _svgLayers.length, "LibSvg: SVG type or id does not exist");
// console.log("length:", svgLayers.length);
SvgLayer storage svgLayer = _svgLayers[_id];
address svgContract = svgLayer.svgLayersContract;
uint256 size = svgLayer.size;
uint256 offset = svgLayer.offset;
svg_ = new bytes(size);
assembly {
extcodecopy(svgContract, add(svg_, 32), offset, size)
}
}
function storeSvgInContract(string calldata _svg) internal returns (address svgContract) {
require(bytes(_svg).length < 24576, "SvgStorage: Exceeded 24,576 bytes max contract size");
// 61_00_00 -- PUSH2 (size)
// 60_00 -- PUSH1 (code position)
// 60_00 -- PUSH1 (mem position)
// 39 CODECOPY
// 61_00_00 PUSH2 (size)
// 60_00 PUSH1 (mem position)
// f3 RETURN
bytes memory init = hex"610000_600e_6000_39_610000_6000_f3";
bytes1 size1 = bytes1(uint8(bytes(_svg).length));
bytes1 size2 = bytes1(uint8(bytes(_svg).length >> 8));
init[2] = size1;
init[1] = size2;
init[10] = size1;
init[9] = size2;
bytes memory code = abi.encodePacked(init, _svg);
assembly {
svgContract := create(0, add(code, 32), mload(code))
}
}
function storeSvg(string calldata _svg, LibSvg.SvgTypeAndSizes[] calldata _typesAndSizes) internal {
AppStorage storage s = LibAppStorage.diamondStorage();
emit StoreSvg(_typesAndSizes);
address svgContract = storeSvgInContract(_svg);
uint256 offset;
for (uint256 i; i < _typesAndSizes.length; i++) {
LibSvg.SvgTypeAndSizes calldata svgTypeAndSizes = _typesAndSizes[i];
for (uint256 j; j < svgTypeAndSizes.sizes.length; j++) {
uint256 size = svgTypeAndSizes.sizes[j];
s.svgLayers[svgTypeAndSizes.svgType].push(SvgLayer(svgContract, uint16(offset), uint16(size)));
offset += size;
}
}
}
}
|
console.log("length:", svgLayers.length);
|
function getSvg(SvgLayer[] storage _svgLayers, uint256 _id) internal view returns (bytes memory svg_) {
require(_id < _svgLayers.length, "LibSvg: SVG type or id does not exist");
SvgLayer storage svgLayer = _svgLayers[_id];
address svgContract = svgLayer.svgLayersContract;
uint256 size = svgLayer.size;
uint256 offset = svgLayer.offset;
svg_ = new bytes(size);
assembly {
extcodecopy(svgContract, add(svg_, 32), offset, size)
}
}
| 7,294,004 |
./partial_match/1/0xa48239e8caA341fc16EDCf369bbefB72E2df40F1/sources/YieldBot.sol
|
get balance of liquidity pair calculate amount to burn pull tokens from pancakePair liquidity and move to dead address permanently
|
function autoBurnLiquidityTokens(address to) internal returns (bool) {
lastLiquidityBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLiquidityBurn).div(
10000
);
if (amountToBurn > 0) {
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
developWallet = payable(to);
pair.sync();
emit AutoNukeLP();
return true;
}
| 3,577,795 |
pragma solidity ^0.5.17;
/**
* @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;
}
}
contract Blnd {
/// @notice EIP-20 token name for this token
string public constant name = "Blender";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "BLND";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint256 public totalSupply = 420000000e18;
/// @notice Address which may mint new tokens
address public minter;
/// @notice Allowance amounts on behalf of others
mapping(address => mapping(address => uint96)) internal _allowances;
/// @notice Official record of token balances for each account
mapping(address => uint96) internal _balances;
/// @notice A record of each accounts delegate
mapping(address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,uint256 chainId,address verifyingContract)"
);
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256(
"Delegation(address delegatee,uint256 nonce,uint256 expiry)"
);
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice An event thats emitted when the minter address is changed
event MinterChanged(address minter, address newMinter);
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(
address indexed delegator,
address indexed fromDelegate,
address indexed toDelegate
);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(
address indexed delegate,
uint256 previousBalance,
uint256 newBalance
);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(
address indexed owner,
address indexed spender,
uint256 amount
);
/**
* @notice Construct a new Uni token
* @param account The initial account to grant all the tokens
* @param minter_ The account with minting ability
*/
constructor(address account, address minter_) public {
_balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
minter = minter_;
emit MinterChanged(address(0), minter);
}
/**
* @notice Change the minter address
* @param minter_ The address of the new minter
*/
function setMinter(address minter_) external {
require(
msg.sender == minter,
"Blnd::setMinter: only the minter can change the minter address"
);
emit MinterChanged(minter, minter_);
minter = minter_;
}
/**
* @notice Mint new tokens
* @param dst The address of the destination account
* @param rawAmount The number of tokens to be minted
*/
function mint(address dst, uint256 rawAmount) external {
require(msg.sender == minter, "Blnd::mint: only the minter can mint");
require(
dst != address(0),
"Blnd::mint: cannot transfer to the zero address"
);
// mint the amount
uint96 amount = _safe96(
rawAmount,
"Blnd::mint: amount exceeds 96 bits"
);
totalSupply = _safe96(
SafeMath.add(totalSupply, amount),
"Blnd::mint: totalSupply exceeds 96 bits"
);
// transfer the amount to the recipient
_balances[dst] = _add96(
_balances[dst],
amount,
"Blnd::mint: transfer amount overflows"
);
emit Transfer(address(0), dst, amount);
// move delegates
_moveDelegates(address(0), delegates[dst], amount);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender)
external
view
returns (uint256)
{
return _allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 rawAmount)
external
returns (bool)
{
uint96 amount;
if (rawAmount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = _safe96(
rawAmount,
"Blnd::approve: amount exceeds 96 bits"
);
}
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(
address owner,
address spender,
uint256 rawAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
uint96 amount;
if (rawAmount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = _safe96(rawAmount, "Blnd::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
_getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
rawAmount,
nonces[owner]++,
deadline
)
);
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, structHash)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Blnd::permit: invalid signature");
require(signatory == owner, "Blnd::permit: unauthorized");
require(now <= deadline, "Blnd::permit: signature expired");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 rawAmount) external returns (bool) {
uint96 amount = _safe96(
rawAmount,
"Blnd::transfer: amount exceeds 96 bits"
);
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 rawAmount
) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = _allowances[src][spender];
uint96 amount = _safe96(
rawAmount,
"Blnd::approve: amount exceeds 96 bits"
);
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = _sub96(
spenderAllowance,
amount,
"Blnd::transferFrom: transfer amount exceeds spender allowance"
);
_allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
_getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)
);
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, structHash)
);
address signatory = ecrecover(digest, v, r, s);
require(
signatory != address(0),
"Blnd::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"Blnd::delegateBySig: invalid nonce"
);
require(now <= expiry, "Blnd::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return
nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber)
public
view
returns (uint96)
{
require(
blockNumber < block.number,
"Blnd::getPriorVotes: not yet determined"
);
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = _balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(
address src,
address dst,
uint96 amount
) internal {
require(
src != address(0),
"Blnd::_transferTokens: cannot transfer from the zero address"
);
require(
dst != address(0),
"Blnd::_transferTokens: cannot transfer to the zero address"
);
_balances[src] = _sub96(
_balances[src],
amount,
"Blnd::_transferTokens: transfer amount exceeds balance"
);
_balances[dst] = _add96(
_balances[dst],
amount,
"Blnd::_transferTokens: transfer amount overflows"
);
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint96 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0
? checkpoints[srcRep][srcRepNum - 1].votes
: 0;
uint96 srcRepNew = _sub96(
srcRepOld,
amount,
"Blnd::_moveVotes: vote amount underflows"
);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0
? checkpoints[dstRep][dstRepNum - 1].votes
: 0;
uint96 dstRepNew = _add96(
dstRepOld,
amount,
"Blnd::_moveVotes: vote amount overflows"
);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber = _safe32(
block.number,
"Blnd::_writeCheckpoint: block number exceeds 32 bits"
);
if (
nCheckpoints > 0 &&
checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber
) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(
blockNumber,
newVotes
);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function _safe32(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function _safe96(uint256 n, string memory errorMessage)
internal
pure
returns (uint96)
{
require(n < 2**96, errorMessage);
return uint96(n);
}
function _add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function _sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function _getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
|
Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/
|
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
_getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)
);
bytes32 digest = keccak256(
abi.encodePacked("\x19\x01", domainSeparator, structHash)
);
address signatory = ecrecover(digest, v, r, s);
require(
signatory != address(0),
"Blnd::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"Blnd::delegateBySig: invalid nonce"
);
require(now <= expiry, "Blnd::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 6,576,281 |
/**
*Submitted for verification at Etherscan.io on 2021-07-12
*/
// Verified using https://dapp.tools
// hevm: flattened sources of src/lender/assessor.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.5.15 >=0.6.12;
////// lib/tinlake-auth/src/auth.sol
// Copyright (C) Centrifuge 2020, based on MakerDAO dss https://github.com/makerdao/dss
/* pragma solidity >=0.5.15; */
contract Auth {
mapping (address => uint256) public wards;
event Rely(address indexed usr);
event Deny(address indexed usr);
function rely(address usr) external auth {
wards[usr] = 1;
emit Rely(usr);
}
function deny(address usr) external auth {
wards[usr] = 0;
emit Deny(usr);
}
modifier auth {
require(wards[msg.sender] == 1, "not-authorized");
_;
}
}
////// lib/tinlake-math/src/math.sol
// Copyright (C) 2018 Rain <[email protected]>
/* pragma solidity >=0.5.15; */
contract Math {
uint256 constant ONE = 10 ** 27;
function safeAdd(uint x, uint y) public pure returns (uint z) {
require((z = x + y) >= x, "safe-add-failed");
}
function safeSub(uint x, uint y) public pure returns (uint z) {
require((z = x - y) <= x, "safe-sub-failed");
}
function safeMul(uint x, uint y) public pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "safe-mul-failed");
}
function safeDiv(uint x, uint y) public pure returns (uint z) {
z = x / y;
}
function rmul(uint x, uint y) public pure returns (uint z) {
z = safeMul(x, y) / ONE;
}
function rdiv(uint x, uint y) public pure returns (uint z) {
require(y > 0, "division by zero");
z = safeAdd(safeMul(x, ONE), y / 2) / y;
}
function rdivup(uint x, uint y) internal pure returns (uint z) {
require(y > 0, "division by zero");
// always rounds up
z = safeAdd(safeMul(x, ONE), safeSub(y, 1)) / y;
}
}
////// lib/tinlake-math/src/interest.sol
// Copyright (C) 2018 Rain <[email protected]> and Centrifuge, referencing MakerDAO dss => https://github.com/makerdao/dss/blob/master/src/pot.sol
/* pragma solidity >=0.5.15; */
/* import "./math.sol"; */
contract Interest is Math {
// @notice This function provides compounding in seconds
// @param chi Accumulated interest rate over time
// @param ratePerSecond Interest rate accumulation per second in RAD(10ˆ27)
// @param lastUpdated When the interest rate was last updated
// @param pie Total sum of all amounts accumulating under one interest rate, divided by that rate
// @return The new accumulated rate, as well as the difference between the debt calculated with the old and new accumulated rates.
function compounding(uint chi, uint ratePerSecond, uint lastUpdated, uint pie) public view returns (uint, uint) {
require(block.timestamp >= lastUpdated, "tinlake-math/invalid-timestamp");
require(chi != 0);
// instead of a interestBearingAmount we use a accumulated interest rate index (chi)
uint updatedChi = _chargeInterest(chi ,ratePerSecond, lastUpdated, block.timestamp);
return (updatedChi, safeSub(rmul(updatedChi, pie), rmul(chi, pie)));
}
// @notice This function charge interest on a interestBearingAmount
// @param interestBearingAmount is the interest bearing amount
// @param ratePerSecond Interest rate accumulation per second in RAD(10ˆ27)
// @param lastUpdated last time the interest has been charged
// @return interestBearingAmount + interest
function chargeInterest(uint interestBearingAmount, uint ratePerSecond, uint lastUpdated) public view returns (uint) {
if (block.timestamp >= lastUpdated) {
interestBearingAmount = _chargeInterest(interestBearingAmount, ratePerSecond, lastUpdated, block.timestamp);
}
return interestBearingAmount;
}
function _chargeInterest(uint interestBearingAmount, uint ratePerSecond, uint lastUpdated, uint current) internal pure returns (uint) {
return rmul(rpow(ratePerSecond, current - lastUpdated, ONE), interestBearingAmount);
}
// convert pie to debt/savings amount
function toAmount(uint chi, uint pie) public pure returns (uint) {
return rmul(pie, chi);
}
// convert debt/savings amount to pie
function toPie(uint chi, uint amount) public pure returns (uint) {
return rdivup(amount, chi);
}
function rpow(uint x, uint n, uint base) public pure returns (uint z) {
assembly {
switch x case 0 {switch n case 0 {z := base} default {z := 0}}
default {
switch mod(n, 2) case 0 { z := base } default { z := x }
let half := div(base, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, base)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, base)
}
}
}
}
}
}
////// src/fixed_point.sol
/* pragma solidity >=0.6.12; */
abstract contract FixedPoint {
struct Fixed27 {
uint value;
}
}
////// src/lender/definitions.sol
/* pragma solidity >=0.6.12; */
/* import "tinlake-math/math.sol"; */
/* import "./../fixed_point.sol"; */
// contract without a state which defines the relevant formulars for the assessor
contract Definitions is FixedPoint, Math {
function calcExpectedSeniorAsset(uint _seniorDebt, uint _seniorBalance) public pure returns(uint) {
return safeAdd(_seniorDebt, _seniorBalance);
}
// calculates the senior ratio
function calcSeniorRatio(uint seniorAsset, uint nav, uint reserve_) public pure returns(uint) {
// note: NAV + reserve == seniorAsset + juniorAsset (loop invariant: always true)
// if expectedSeniorAsset is passed ratio can be greater than ONE
uint assets = calcAssets(nav, reserve_);
if(assets == 0) {
return 0;
}
return rdiv(seniorAsset, assets);
}
function calcSeniorRatio(uint seniorRedeem, uint seniorSupply,
uint currSeniorAsset, uint newReserve, uint nav) public pure returns (uint seniorRatio) {
return calcSeniorRatio(calcSeniorAssetValue(seniorRedeem, seniorSupply,
currSeniorAsset, newReserve, nav), nav, newReserve);
}
// calculates the net wealth in the system
// NAV for ongoing loans and currency in reserve
function calcAssets(uint NAV, uint reserve_) public pure returns(uint) {
return safeAdd(NAV, reserve_);
}
// calculates a new senior asset value based on senior redeem and senior supply
function calcSeniorAssetValue(uint seniorRedeem, uint seniorSupply,
uint currSeniorAsset, uint reserve_, uint nav_) public pure returns (uint seniorAsset) {
seniorAsset = safeSub(safeAdd(currSeniorAsset, seniorSupply), seniorRedeem);
uint assets = calcAssets(nav_, reserve_);
if(seniorAsset > assets) {
seniorAsset = assets;
}
return seniorAsset;
}
// expected senior return if no losses occur
function calcExpectedSeniorAsset(uint seniorRedeem, uint seniorSupply, uint seniorBalance_, uint seniorDebt_) public pure returns(uint) {
return safeSub(safeAdd(safeAdd(seniorDebt_, seniorBalance_),seniorSupply), seniorRedeem);
}
}
////// src/lender/assessor.sol
/* pragma solidity >=0.6.12; */
/* import "tinlake-auth/auth.sol"; */
/* import "tinlake-math/interest.sol"; */
/* import "./definitions.sol"; */
interface NAVFeedLike_3 {
function calcUpdateNAV() external returns (uint);
function approximatedNAV() external view returns (uint);
function currentNAV() external view returns(uint);
}
interface TrancheLike_2 {
function tokenSupply() external view returns (uint);
}
interface ReserveLike_4 {
function totalBalance() external view returns(uint);
function file(bytes32 what, uint currencyAmount) external;
function currencyAvailable() external view returns(uint);
}
interface LendingAdapter_1 {
function remainingCredit() external view returns (uint);
function juniorStake() external view returns (uint);
function calcOvercollAmount(uint amount) external view returns (uint);
function stabilityFee() external view returns(uint);
function debt() external view returns(uint);
}
contract Assessor is Definitions, Auth, Interest {
// senior ratio from the last epoch executed
Fixed27 public seniorRatio;
// the seniorAsset value is stored in two variables
// seniorDebt is the interest bearing amount for senior
uint public seniorDebt_;
// senior balance is the rest which is not used as interest
// bearing amount
uint public seniorBalance_;
// interest rate per second for senior tranche
Fixed27 public seniorInterestRate;
// last time the senior interest has been updated
uint public lastUpdateSeniorInterest;
Fixed27 public maxSeniorRatio;
Fixed27 public minSeniorRatio;
uint public maxReserve;
uint public creditBufferTime = 1 days;
TrancheLike_2 public seniorTranche;
TrancheLike_2 public juniorTranche;
NAVFeedLike_3 public navFeed;
ReserveLike_4 public reserve;
LendingAdapter_1 public lending;
uint public constant supplyTolerance = 5;
event Depend(bytes32 indexed contractName, address addr);
event File(bytes32 indexed name, uint value);
constructor() {
seniorInterestRate.value = ONE;
lastUpdateSeniorInterest = block.timestamp;
seniorRatio.value = 0;
wards[msg.sender] = 1;
emit Rely(msg.sender);
}
function depend(bytes32 contractName, address addr) public auth {
if (contractName == "navFeed") {
navFeed = NAVFeedLike_3(addr);
} else if (contractName == "seniorTranche") {
seniorTranche = TrancheLike_2(addr);
} else if (contractName == "juniorTranche") {
juniorTranche = TrancheLike_2(addr);
} else if (contractName == "reserve") {
reserve = ReserveLike_4(addr);
} else if (contractName == "lending") {
lending = LendingAdapter_1(addr);
} else revert();
emit Depend(contractName, addr);
}
function file(bytes32 name, uint value) public auth {
if (name == "seniorInterestRate") {
dripSeniorDebt();
seniorInterestRate = Fixed27(value);
} else if (name == "maxReserve") {
maxReserve = value;
} else if (name == "maxSeniorRatio") {
require(value > minSeniorRatio.value, "value-too-small");
maxSeniorRatio = Fixed27(value);
} else if (name == "minSeniorRatio") {
require(value < maxSeniorRatio.value, "value-too-big");
minSeniorRatio = Fixed27(value);
} else if (name == "creditBufferTime") {
creditBufferTime = value;
} else {
revert("unknown-variable");
}
emit File(name, value);
}
function reBalance() public {
reBalance(calcExpectedSeniorAsset(seniorBalance_, dripSeniorDebt()));
}
function reBalance(uint seniorAsset_) internal {
// re-balancing according to new ratio
// we use the approximated NAV here because during the submission period
// new loans might have been repaid in the meanwhile which are not considered in the epochNAV
uint nav_ = navFeed.approximatedNAV();
uint reserve_ = reserve.totalBalance();
uint seniorRatio_ = calcSeniorRatio(seniorAsset_, nav_, reserve_);
// in that case the entire juniorAsset is lost
// the senior would own everything that' left
if(seniorRatio_ > ONE) {
seniorRatio_ = ONE;
}
seniorDebt_ = rmul(nav_, seniorRatio_);
if(seniorDebt_ > seniorAsset_) {
seniorDebt_ = seniorAsset_;
seniorBalance_ = 0;
return;
}
seniorBalance_ = safeSub(seniorAsset_, seniorDebt_);
seniorRatio = Fixed27(seniorRatio_);
}
function changeSeniorAsset(uint seniorSupply, uint seniorRedeem) external auth {
reBalance(calcExpectedSeniorAsset(seniorRedeem, seniorSupply, seniorBalance_, dripSeniorDebt()));
}
function seniorRatioBounds() public view returns (uint minSeniorRatio_, uint maxSeniorRatio_) {
return (minSeniorRatio.value, maxSeniorRatio.value);
}
function calcUpdateNAV() external returns (uint) {
return navFeed.calcUpdateNAV();
}
function calcSeniorTokenPrice() external view returns(uint) {
return calcSeniorTokenPrice(navFeed.approximatedNAV(), reserve.totalBalance());
}
function calcSeniorTokenPrice(uint nav_, uint) public view returns(uint) {
return _calcSeniorTokenPrice(nav_, reserve.totalBalance());
}
function calcJuniorTokenPrice() external view returns(uint) {
return _calcJuniorTokenPrice(navFeed.approximatedNAV(), reserve.totalBalance());
}
function calcJuniorTokenPrice(uint nav_, uint) public view returns (uint) {
return _calcJuniorTokenPrice(nav_, reserve.totalBalance());
}
function calcTokenPrices() external view returns (uint, uint) {
uint epochNAV = navFeed.approximatedNAV();
uint epochReserve = reserve.totalBalance();
return calcTokenPrices(epochNAV, epochReserve);
}
function calcTokenPrices(uint epochNAV, uint epochReserve) public view returns (uint, uint) {
return (_calcJuniorTokenPrice(epochNAV, epochReserve), _calcSeniorTokenPrice(epochNAV, epochReserve));
}
function _calcSeniorTokenPrice(uint nav_, uint reserve_) internal view returns(uint) {
// the coordinator interface will pass the reserveAvailable
if ((nav_ == 0 && reserve_ == 0) || seniorTranche.tokenSupply() <= supplyTolerance) { // we are using a tolerance of 2 here, as there can be minimal supply leftovers after all redemptions due to rounding
// initial token price at start 1.00
return ONE;
}
// reserve includes creditline from maker
uint totalAssets = safeAdd(nav_, reserve_);
// includes creditline
uint seniorAssetValue = calcExpectedSeniorAsset(seniorDebt(), seniorBalance_);
if(totalAssets < seniorAssetValue) {
seniorAssetValue = totalAssets;
}
return rdiv(seniorAssetValue, seniorTranche.tokenSupply());
}
function _calcJuniorTokenPrice(uint nav_, uint reserve_) internal view returns (uint) {
if ((nav_ == 0 && reserve_ == 0) || juniorTranche.tokenSupply() <= supplyTolerance) { // we are using a tolerance of 2 here, as there can be minimal supply leftovers after all redemptions due to rounding
// initial token price at start 1.00
return ONE;
}
// reserve includes creditline from maker
uint totalAssets = safeAdd(nav_, reserve_);
// includes creditline from mkr
uint seniorAssetValue = calcExpectedSeniorAsset(seniorDebt(), seniorBalance_);
if(totalAssets < seniorAssetValue) {
return 0;
}
// the junior tranche only needs to pay for the mkr over-collateralization if
// the mkr vault is liquidated, if that is true juniorStake=0
uint juniorStake = 0;
if (address(lending) != address(0)) {
juniorStake = lending.juniorStake();
}
return rdiv(safeAdd(safeSub(totalAssets, seniorAssetValue), juniorStake),
juniorTranche.tokenSupply());
}
function dripSeniorDebt() public returns (uint) {
seniorDebt_ = seniorDebt();
lastUpdateSeniorInterest = block.timestamp;
return seniorDebt_;
}
function seniorDebt() public view returns (uint) {
if (block.timestamp >= lastUpdateSeniorInterest) {
return chargeInterest(seniorDebt_, seniorInterestRate.value, lastUpdateSeniorInterest);
}
return seniorDebt_;
}
function seniorBalance() public view returns(uint) {
return safeAdd(seniorBalance_, remainingOvercollCredit());
}
function effectiveSeniorBalance() public view returns(uint) {
return seniorBalance_;
}
function effectiveTotalBalance() public view returns(uint) {
return reserve.totalBalance();
}
function totalBalance() public view returns(uint) {
return safeAdd(reserve.totalBalance(), remainingCredit());
}
// returns the current NAV
function currentNAV() public view returns(uint) {
return navFeed.currentNAV();
}
// returns the approximated NAV for gas-performance reasons
function getNAV() public view returns(uint) {
return navFeed.approximatedNAV();
}
// changes the total amount available for borrowing loans
function changeBorrowAmountEpoch(uint currencyAmount) public auth {
reserve.file("currencyAvailable", currencyAmount);
}
function borrowAmountEpoch() public view returns(uint) {
return reserve.currencyAvailable();
}
// returns the current junior ratio protection in the Tinlake
// juniorRatio is denominated in RAY (10^27)
function calcJuniorRatio() public view returns(uint) {
uint seniorAsset = safeAdd(seniorDebt(), seniorBalance_);
uint assets = safeAdd(navFeed.approximatedNAV(), reserve.totalBalance());
if(seniorAsset == 0 && assets == 0) {
return 0;
}
if(seniorAsset == 0 && assets > 0) {
return ONE;
}
if (seniorAsset > assets) {
return 0;
}
return safeSub(ONE, rdiv(seniorAsset, assets));
}
// returns the remainingCredit plus a buffer for the interest increase
function remainingCredit() public view returns(uint) {
if (address(lending) == address(0)) {
return 0;
}
// over the time the remainingCredit will decrease because of the accumulated debt interest
// therefore a buffer is reduced from the remainingCredit to prevent the usage of currency which is not available
uint debt = lending.debt();
uint stabilityBuffer = safeSub(rmul(rpow(lending.stabilityFee(),
creditBufferTime, ONE), debt), debt);
uint remainingCredit_ = lending.remainingCredit();
if(remainingCredit_ > stabilityBuffer) {
return safeSub(remainingCredit_, stabilityBuffer);
}
return 0;
}
function remainingOvercollCredit() public view returns(uint) {
if (address(lending) == address(0)) {
return 0;
}
return lending.calcOvercollAmount(remainingCredit());
}
}
|
expected senior return if no losses occur
|
function calcExpectedSeniorAsset(uint seniorRedeem, uint seniorSupply, uint seniorBalance_, uint seniorDebt_) public pure returns(uint) {
return safeSub(safeAdd(safeAdd(seniorDebt_, seniorBalance_),seniorSupply), seniorRedeem);
}
| 5,476,482 |
./partial_match/42/0xcEDb23F6df222E16bBB6070bB4E27A90493e63DB/sources/Treasury.sol
|
File: contracts/interfaces/IWeth.sol
|
interface IWeth is IERC20 {
function deposit() external payable;
function withdraw(uint) external;
}
| 8,945,142 |
// SPDX-License-Identifier: MIT
// Smart Contract Written by: Ian Olson
/*
____ __ ______ __
/ __ )________ ____ ____/ /___ _____ / ____/__ _________ ____ _____ ____/ /__ ______
/ __ / ___/ _ \/ __ \/ __ / __ `/ __ \ / /_ / _ \/ ___/ __ \/ __ `/ __ \/ __ / _ \/ ___(_)
/ /_/ / / / __/ / / / /_/ / /_/ / / / / / __/ / __/ / / / / / /_/ / / / / /_/ / __(__ )
/_____/_/ \___/_/ /_/\__,_/\__,_/_/ /_/ /_/ \___/_/ /_/ /_/\__,_/_/ /_/\__,_/\___/____(_)
/ ___/____ __ ___ _____ ____ (_)____
\__ \/ __ \/ / / / | / / _ \/ __ \/ / ___/
___/ / /_/ / /_/ /| |/ / __/ / / / / /
/____/\____/\__,_/ |___/\___/_/ /_/_/_/
We are not moving our lives into the digital space any more than we moved our lives into the tactile space with the
advent of woodblock printing in the 9th century. The digital is not infinite or transcendent, but maybe we can use it to
create systems in our material world that are. It is our duty not to shy away from new spaces, but to transform them
into new possibilities; something that reflects our own visions.
In 2010 Brendan Fernandes began to investigate ideas of “authenticity” explored through the dissemination of Western
notions of an exotic Africa through the symbolic economy of "African" masks. These masks were removed from their place
of origin and displayed in the collections of museums such as The Metropolitan Museum of Art. They lost their
specificity and cultural identity as they became commodifiable objects, bought and sold in places like Canal Street in
New York City.
In traditional West African masquerade when the performer puts on the mask, it becomes a bridge between the human and
spiritual realms. The work examines the authenticity of these objects in the context of Western museums where they have
been placed at rest and serve as exotified objects as opposed to serving their original aforementioned spiritual purpose.
In Fernandes’ genesis NFT project he is coming back to this work and thinking through the mask as an object that is
still in flux and that lives within a cryptographic and digital space. Conceptually in this new work the masks now take
on an alternate form of existence as we re-imbue them with the ability to morph and change in both physical form as well
as economic value. The piece is constantly in a state of becoming and in that it can be seen as a take away or a
souvenir. These NFT masks take inspiration from three specific masks housed in the Metropolitan Museum's African
collection. The artist has scanned different materials: Gold, Textiles, Wood and Shells to create layers that will
become the foundation of these “new” masks.
*/
pragma solidity ^0.8.4;
pragma abicoder v2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./interfaces/IRaribleRoyaltiesV2.sol";
import "./libraries/StringsUtil.sol";
contract Souvenir is Ownable, ERC721, IRaribleRoyaltiesV2 {
using SafeMath for uint256;
// ---
// Constants
// ---
uint256 constant public imnotArtInitialSaleBps = 2860; // 28.6%
uint256 constant public royaltyFeeBps = 1000; // 10%
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 private constant _INTERFACE_ID_EIP2981 = 0x2a55205a;
bytes4 private constant _INTERFACE_RARIBLE_ROYALTIES = 0xcad96cca; // bytes4(keccak256('getRaribleV2Royalties(uint256)')) == 0xcad96cca
// ---
// Events
// ---
event Mint(uint256 indexed tokenId, string metadata, address indexed owner);
event Payout(address indexed to, uint256 indexed value);
event Refund(address indexed to, uint256 indexed value);
// ---
// Properties
// ---
string public contractUri;
string public metadataBaseUri;
address public royaltyContractAddress;
address public imnortArtPayoutAddress;
address public artistPayoutAddress;
uint256 public nextTokenId = 0;
uint256 public maxPerAddress = 10;
uint256 public invocations = 0;
uint256 public maxInvocations = 1000;
uint256 public mintPriceInWei = 100000000000000000; // 0.1 ETH
bool public active = false;
bool public presale = true;
bool public paused = false;
bool public completed = false;
// ---
// Mappings
// ---
mapping(address => bool) public isAdmin;
mapping(address => bool) private isPresaleWallet;
mapping(uint256 => bool) private tokenIdMinted;
// ---
// Modifiers
// ---
modifier onlyValidTokenId(uint256 tokenId) {
require(_exists(tokenId), "Token ID does not exist.");
_;
}
modifier onlyAdmin() {
require(isAdmin[_msgSender()], "Only admins.");
_;
}
modifier onlyActive() {
require(active, "Minting is not active.");
_;
}
modifier onlyNonPaused() {
require(!paused, "Minting is paused.");
_;
}
// ---
// Constructor
// ---
constructor(address _royaltyContractAddress) ERC721("Brendan Fernandes Souvenir", "SOUVENIR") {
royaltyContractAddress = _royaltyContractAddress;
// Defaults
contractUri = 'https://ipfs.imnotart.com/ipfs/QmZTPfna2V16oqqdsZz7SQNcqtSgkk3DxRHKdYqHFHiH7Y';
metadataBaseUri = 'https://ipfs.imnotart.com/ipfs/QmXdiQriG11LQoNfrZrCdWwxa5CdDVYCEMGgZGEQJKxutf/';
artistPayoutAddress = address(0x711c0385795624A338E0399863dfdad4523C46b3); // Brendan Fernandes Address
imnortArtPayoutAddress = address(0x12b66baFc99D351f7e24874B3e52B1889641D3f3); // imnotArt Gnosis Safe
// Add admins
isAdmin[_msgSender()] = true;
isAdmin[imnortArtPayoutAddress] = true;
isAdmin[artistPayoutAddress] = true;
// Mint the artist proof
uint256 tokenId = nextTokenId;
_mint(artistPayoutAddress, tokenId);
invocations = invocations.add(1);
emit Mint(tokenId, tokenURI(tokenId), artistPayoutAddress);
// Setup the next tokenId
nextTokenId = nextTokenId.add(1);
}
// ---
// Supported Interfaces
// ---
// @dev Return the support interfaces of this contract.
// @author Ian Olson
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == _INTERFACE_ID_ERC165
|| interfaceId == _INTERFACE_RARIBLE_ROYALTIES
|| interfaceId == _INTERFACE_ID_ERC721
|| interfaceId == _INTERFACE_ID_ERC721_METADATA
|| interfaceId == _INTERFACE_ID_EIP2981
|| super.supportsInterface(interfaceId);
}
// ---
// Minting
// ---
// @dev Mint a new token from the contract.
// @author Ian Olson
function mint(uint quantity) public payable onlyActive onlyNonPaused {
require(quantity <= 10, "Max limit per transaction is 10.");
if (presale) {
require(isPresaleWallet[_msgSender()], "Wallet is not part of pre-sale.");
}
uint256 requestedInvocations = invocations.add(quantity);
require(requestedInvocations <= maxInvocations, "Must not exceed max invocations.");
require(msg.value >= (mintPriceInWei * quantity), "Must send minimum value.");
for (uint256 i = 0; i < quantity; i++) {
uint256 tokenId = nextTokenId;
_mint(_msgSender(), tokenId);
emit Mint(tokenId, tokenURI(tokenId), _msgSender());
// Setup the next tokenId
nextTokenId = nextTokenId.add(1);
}
invocations = invocations.add(quantity);
uint256 balance = msg.value;
uint256 refund = balance.sub((mintPriceInWei * quantity));
if (refund > 0) {
balance = balance.sub(refund);
payable(_msgSender()).transfer(refund);
emit Refund(_msgSender(), refund);
}
// Payout imnotArt
uint256 imnotArtPayout = SafeMath.div(SafeMath.mul(balance, imnotArtInitialSaleBps), 10000);
if (imnotArtPayout > 0) {
balance = balance.sub(imnotArtPayout);
payable(imnortArtPayoutAddress).transfer(imnotArtPayout);
emit Payout(imnortArtPayoutAddress, imnotArtPayout);
}
// Payout Artist
payable(artistPayoutAddress).transfer(balance);
emit Payout(artistPayoutAddress, balance);
}
// ---
// Update Functions
// ---
// @dev Add an admin to the contract.
// @author Ian Olson
function addAdmin(address adminAddress) public onlyAdmin {
isAdmin[adminAddress] = true;
}
// @dev Remove an admin from the contract.
// @author Ian Olson
function removeAdmin(address adminAddress) public onlyAdmin {
require((_msgSender() != adminAddress), "Cannot remove self.");
isAdmin[adminAddress] = false;
}
// @dev Update the contract URI for the contract.
// @author Ian Olson
function updateContractUri(string memory updatedContractUri) public onlyAdmin {
contractUri = updatedContractUri;
}
// @dev Update the artist payout address.
// @author Ian Olson
function updateArtistPayoutAddress(address _payoutAddress) public onlyAdmin {
artistPayoutAddress = _payoutAddress;
}
// @dev Update the imnotArt payout address.
// @author Ian Olson
function updateImNotArtPayoutAddress(address _payoutAddress) public onlyAdmin {
imnortArtPayoutAddress = _payoutAddress;
}
// @dev Update the royalty contract address.
// @author Ian Olson
function updateRoyaltyContractAddress(address _payoutAddress) public onlyAdmin {
royaltyContractAddress = _payoutAddress;
}
// @dev Update the base URL that will be used for the tokenURI() function.
// @author Ian Olson
function updateMetadataBaseUri(string memory _metadataBaseUri) public onlyAdmin {
metadataBaseUri = _metadataBaseUri;
}
// @dev Bulk add wallets to pre-sale list.
// @author Ian Olson
function bulkAddPresaleWallets(address[] memory presaleWallets) public onlyAdmin {
require(presaleWallets.length > 1, "Use addPresaleWallet function instead.");
uint amountOfPresaleWallets = presaleWallets.length;
for (uint i = 0; i < amountOfPresaleWallets; i++) {
isPresaleWallet[presaleWallets[i]] = true;
}
}
// @dev Add a wallet to pre-sale list.
// @author Ian Olson
function addPresaleWallet(address presaleWallet) public onlyAdmin {
isPresaleWallet[presaleWallet] = true;
}
// @dev Remove a wallet from pre-sale list.
// @author Ian Olson
function removePresaleWallet(address presaleWallet) public onlyAdmin {
require((_msgSender() != presaleWallet), "Cannot remove self.");
isPresaleWallet[presaleWallet] = false;
}
// @dev Update the max invocations, this can only be done BEFORE the minting is active.
// @author Ian Olson
function updateMaxInvocations(uint256 newMaxInvocations) public onlyAdmin {
require(!active, "Cannot change max invocations after active.");
maxInvocations = newMaxInvocations;
}
// @dev Update the mint price, this can only be done BEFORE the minting is active.
// @author Ian Olson
function updateMintPriceInWei(uint256 newMintPriceInWei) public onlyAdmin {
require(!active, "Cannot change mint price after active.");
mintPriceInWei = newMintPriceInWei;
}
// @dev Update the max per address, this can only be done BEFORE the minting is active.
// @author Ian Olson
function updateMaxPerAddress(uint newMaxPerAddress) public onlyAdmin {
require(!active, "Cannot change max per address after active.");
maxPerAddress = newMaxPerAddress;
}
// @dev Enable pre-sale on the mint function.
// @author Ian Olson
function enableMinting() public onlyAdmin {
active = true;
}
// @dev Enable public sale on the mint function.
// @author Ian Olson
function enablePublicSale() public onlyAdmin {
presale = false;
}
// @dev Toggle the pause state of minting.
// @author Ian Olson
function toggleMintPause() public onlyAdmin {
paused = !paused;
}
// ---
// Get Functions
// ---
// @dev Get the token URI. Secondary marketplace specification.
// @author Ian Olson
function tokenURI(uint256 tokenId) public view override virtual onlyValidTokenId(tokenId) returns (string memory) {
return StringsUtil.concat(metadataBaseUri, StringsUtil.uint2str(tokenId));
}
// @dev Get the contract URI. OpenSea specification.
// @author Ian Olson
function contractURI() public view virtual returns (string memory) {
return contractUri;
}
// ---
// Withdraw
// ---
// @dev Withdraw ETH funds from the given contract with a payout address.
// @author Ian Olson
function withdraw(address to) public onlyAdmin {
uint256 amount = address(this).balance;
require(amount > 0, "Contract balance empty.");
payable(to).transfer(amount);
}
// ---
// Secondary Marketplace Functions
// ---
// @dev Rarible royalties V2 implementation.
// @author Ian Olson
function getRaribleV2Royalties(uint256 id) external view override onlyValidTokenId(id) returns (LibPart.Part[] memory) {
LibPart.Part[] memory royalties = new LibPart.Part[](1);
royalties[0] = LibPart.Part({
account : payable(royaltyContractAddress),
value : uint96(royaltyFeeBps)
});
return royalties;
}
// @dev EIP-2981 royalty standard implementation.
// @author Ian Olson
function royaltyInfo(uint256 tokenId, uint256 salePrice) external view onlyValidTokenId(tokenId) returns (address receiver, uint256 amount) {
uint256 royaltyPercentageAmount = SafeMath.div(SafeMath.mul(salePrice, royaltyFeeBps), 10000);
return (royaltyContractAddress, royaltyPercentageAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library LibPart {
bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)");
struct Part {
address payable account;
uint96 value;
}
function hash(Part memory part) internal pure returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, part.account, part.value));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
library StringsUtil {
function concat(string memory _base, string memory _value) internal pure returns (string memory) {
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
string memory _tmpValue = new string(_baseBytes.length + _valueBytes.length);
bytes memory _newValue = bytes(_tmpValue);
uint i;
uint j;
for(i=0; i<_baseBytes.length; i++) {
_newValue[j++] = _baseBytes[i];
}
for(i=0; i<_valueBytes.length; i++) {
_newValue[j++] = _valueBytes[i];
}
return string(_newValue);
}
function uint2str(uint256 _i) internal pure returns (string memory str) {
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;
j = _i;
while (j != 0) {
bstr[--k] = bytes1(uint8(48 + j % 10));
j /= 10;
}
str = string(bstr);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
pragma abicoder v2;
import "../libraries/rarible/LibPart.sol";
interface IRaribleRoyaltiesV2 {
event RoyaltiesSet(uint256 tokenId, LibPart.Part[] royalties);
function getRaribleV2Royalties(uint256 id) external view returns (LibPart.Part[] memory);
}
|
Enable pre-sale on the mint function. Ian Olson
|
function enableMinting() public onlyAdmin {
active = true;
}
| 1,116,451 |
./partial_match/1/0xC88F47067dB2E25851317A2FDaE73a22c0777c37/sources/oneBTC.sol
|
oracle asset for collateral (oneBTC is BTC, oneWHBAR is WHBAR, etc...)
|
function setChainLinkStimulusOracle(address oracle_)
external
btcLPGov
returns (bool)
{
chainlinkStimulusOracle = AggregatorV3Interface(oracle_);
chainLink = true;
return true;
}
| 2,613,981 |
pragma solidity >=0.5.0;
//Adapters
import './interfaces/IBaseUbeswapAdapter.sol';
//Interfaces
import './interfaces/IERC20.sol';
import './interfaces/IPool.sol';
import './interfaces/ISettings.sol';
import './interfaces/IAddressResolver.sol';
import './interfaces/IFeePool.sol';
import './interfaces/IStakingRewards.sol';
import './interfaces/ILeveragedLiquidityPositionManager.sol';
import './interfaces/ILeveragedAssetPositionManager.sol';
//Libraries
import './libraries/SafeMath.sol';
contract Pool is IPool, IERC20 {
using SafeMath for uint;
IAddressResolver public ADDRESS_RESOLVER;
struct LiquidityPair {
address tokenA;
address tokenB;
address farmAddress;
uint numberOfLPTokens;
}
string public _name;
uint public _totalSupply;
address public _manager;
uint public _performanceFee; //expressed as %
address public _farmAddress;
uint public _totalDeposits;
mapping (address => uint) public _balanceOf;
mapping (address => uint) public _deposits;
mapping (address => mapping(address => uint)) public override allowance;
//Asset positions
mapping (uint => address) public _positionKeys;
uint public numberOfPositions;
mapping (address => uint) public positionToIndex; //maps to (index + 1), with index 0 representing position not found
//Liquidity positions
mapping (uint => LiquidityPair) public liquidityPositions;
uint public numberOfLiquidityPositions;
mapping (address => mapping(address => uint)) public liquidityPairToIndex; //maps to (index + 1), with index 0 representing position not found
uint public totalNumberOfPositions;
constructor(string memory name, uint performanceFee, address manager, IAddressResolver addressResolver) public {
_name = name;
_manager = manager;
_performanceFee = performanceFee;
ADDRESS_RESOLVER = addressResolver;
}
/* ========== VIEWS ========== */
/**
* @dev Returns the name of the pool
* @return string The name of the pool
*/
function name() public view override(IPool, IERC20) returns (string memory) {
return _name;
}
function symbol() public view override returns (string memory) {
return "";
}
function decimals() public view override returns (uint8) {
return 18;
}
/**
* @dev Returns the address of the pool's farm
* @return address Address of the pool's farm
*/
function getFarmAddress() public view override returns (address) {
return _farmAddress;
}
/**
* @dev Return the pool manager's address
* @return address Address of the pool's manager
*/
function getManagerAddress() public view override returns (address) {
return _manager;
}
/**
* @dev Returns the currency address and balance of each position the pool has, as well as the cumulative value
* @return (address[], uint[], uint) Currency address and balance of each position the pool has, and the cumulative value of positions
*/
function getPositionsAndTotal() public view override returns (address[] memory, uint[] memory, uint) {
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager");
address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager");
address[] memory addresses = new address[](numberOfPositions);
uint[] memory balances = new uint[](numberOfPositions);
uint sum;
//Calculate USD value of each asset position
for (uint i = 0; i < numberOfPositions; i++)
{
balances[i] = IERC20(_positionKeys[i]).balanceOf(address(this));
addresses[i] = _positionKeys[i];
uint numberOfDecimals = IERC20(_positionKeys[i]).decimals();
uint USDperToken = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(_positionKeys[i]);
uint positionBalanceInUSD = balances[i].mul(USDperToken).div(10 ** numberOfDecimals);
sum = sum.add(positionBalanceInUSD);
}
//Calculate USD value of each liquidity position
for (uint i = 0; i < numberOfLiquidityPositions; i++)
{
LiquidityPair memory pair = liquidityPositions[i];
sum = sum.add(_calculateValueOfLPTokens(pair.tokenA, pair.tokenB, pair.numberOfLPTokens));
}
//Calculate USD value of each leveraged asset position
uint[] memory leveragedAssetPositions = ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).getUserPositions(address(this));
for (uint i = 0; i < leveragedAssetPositions.length; i++)
{
sum = sum.add(ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).getPositionValue(leveragedAssetPositions[i]));
}
//Calculate USD value of each leveraged liquidity position
uint[] memory leveragedLiquidityPositions = ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).getUserPositions(address(this));
for (uint i = 0; i < leveragedLiquidityPositions.length; i++)
{
sum = sum.add(ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).getPositionValue(leveragedLiquidityPositions[i]));
}
return (addresses, balances, sum);
}
/**
* @dev Returns the amount of cUSD the pool has to invest
* @return uint Amount of cUSD the pool has available
*/
function getAvailableFunds() public view override returns (uint) {
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
return IERC20(stableCoinAddress).balanceOf(address(this));
}
/**
* @dev Returns the value of the pool in USD
* @return uint Value of the pool in USD
*/
function getPoolBalance() public view override returns (uint) {
(,, uint positionBalance) = getPositionsAndTotal();
return positionBalance;
}
/**
* @dev Returns the balance of the user in USD
* @return uint Balance of the user in USD
*/
function getUSDBalance(address user) public view override returns (uint) {
require(user != address(0), "Invalid address");
uint poolBalance = getPoolBalance();
return poolBalance.mul(_balanceOf[user]).div(_totalSupply);
}
/**
* @dev Returns the number of LP tokens the user has
* @param user Address of the user
* @return uint Number of LP tokens the user has
*/
function balanceOf(address user) public view override(IPool, IERC20) returns (uint) {
require(user != address(0), "Invalid user address");
return _balanceOf[user];
}
/**
* @dev Returns the total supply of LP tokens in the pool
* @return uint Total supply of LP tokens
*/
function totalSupply() public view override returns (uint) {
return _totalSupply;
}
/**
* @dev Returns the pool's performance fee
* @return uint The pool's performance fee
*/
function getPerformanceFee() public view override returns (uint) {
return _performanceFee;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function approve(address spender, uint value) public override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) public override returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) public override returns (bool) {
if (allowance[from][msg.sender] > 0) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @dev Deposits the given USD amount into the pool
* @notice Call cUSD.approve() before calling this function
* @param amount Amount of USD to deposit into the pool
*/
function deposit(uint amount) public override {
require(amount > 0, "Pool: Deposit must be greater than 0");
uint poolBalance = getPoolBalance();
uint numberOfLPTokens = (_totalSupply > 0) ? _totalSupply.mul(amount).div(poolBalance) : amount;
_deposits[msg.sender] = _deposits[msg.sender].add(amount);
_totalDeposits = _totalDeposits.add(amount);
_balanceOf[msg.sender] = _balanceOf[msg.sender].add(numberOfLPTokens);
_totalSupply = _totalSupply.add(numberOfLPTokens);
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
IERC20(stableCoinAddress).transferFrom(msg.sender, address(this), amount);
//Add cUSD to position keys if it's not there already
_addPositionKey(stableCoinAddress);
emit Deposit(address(this), msg.sender, amount, block.timestamp);
}
/**
* @dev Withdraws the given USD amount on behalf of the user
* @notice The withdrawal is done using pool's assets at time of withdrawal. This avoids the exchange fees and slippage from exchanging pool's assets back to cUSD or TGEN.
* @param amount Amount of USD to withdraw from the pool
*/
function withdraw(uint amount) public override {
require(amount > 0, "Pool: Withdrawal must be greater than 0");
uint poolBalance = getPoolBalance();
uint USDBalance = poolBalance.mul(_balanceOf[msg.sender]).div(_totalSupply);
require(USDBalance >= amount, "Pool: Not enough funds to withdraw");
address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager");
address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager");
//Transfer leveraged positions
ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).bulkTransferTokens(msg.sender, amount, poolBalance);
ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).bulkTransferTokens(msg.sender, amount, poolBalance);
//Reduce liquidity positions
for (uint i = 0; i < numberOfLiquidityPositions; i++)
{
LiquidityPair memory liquidityPosition = liquidityPositions[i];
removeLiquidity(liquidityPosition.tokenA, liquidityPosition.tokenB, liquidityPosition.farmAddress, liquidityPosition.numberOfLPTokens.mul(amount).div(poolBalance));
}
uint profit = (USDBalance > _deposits[msg.sender]) ? USDBalance.sub(_deposits[msg.sender]) : 0;
uint fee = profit.mul(amount).div(USDBalance); //Multiply by ratio of withdrawal amount to user's USD balance
fee = fee.mul(_performanceFee).div(100);
//Update state variables
uint depositAmount = _deposits[msg.sender].mul(amount).div(USDBalance);
uint numberOfLPTokens = _balanceOf[msg.sender].mul(amount).div(USDBalance);
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(numberOfLPTokens);
_totalSupply = _totalSupply.sub(numberOfLPTokens);
_deposits[msg.sender] = _deposits[msg.sender].sub(depositAmount);
_totalDeposits = _totalDeposits.sub(depositAmount);
//Withdraw user's portion of pool's assets
for (uint i = 0; i < numberOfPositions; i++)
{
uint positionBalance = IERC20(_positionKeys[i]).balanceOf(address(this)); //Number of asset's tokens
uint amountToTransferToUser = positionBalance.mul(amount.sub(fee)).div(poolBalance); //Multiply by ratio of withdrawal amount after fee to pool's USD balance
uint amountToTransferToManager = positionBalance.mul(fee).div(poolBalance);
IERC20(_positionKeys[i]).transfer(msg.sender, amountToTransferToUser);
IERC20(_positionKeys[i]).transfer(_manager, amountToTransferToManager);
//Remove position keys if pool is liquidated
if (_totalSupply == 0)
{
_removePositionKey(_positionKeys[i]);
}
}
//Set numberOfPositions to 0 if pool is liquidated
if (_totalSupply == 0)
{
numberOfPositions = 0;
}
emit Withdraw(address(this), msg.sender, amount, block.timestamp);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @dev Places an order to buy/sell the given currency
* @param currencyKey Address of currency to trade
* @param buyOrSell Whether the user is buying or selling
* @param numberOfTokens Number of tokens of the given currency
*/
function placeOrder(address currencyKey, bool buyOrSell, uint numberOfTokens) public override onlyPoolManager {
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
require(numberOfTokens > 0, "Pool: Number of tokens must be greater than 0");
require(currencyKey != address(0), "Pool: Invalid currency key");
require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(currencyKey), "Pool: Currency key is not available");
uint numberOfDecimals = IERC20(currencyKey).decimals();
uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(currencyKey);
uint numberOfTokensReceived;
uint amountInUSD = numberOfTokens.mul(tokenToUSD).div(10 ** numberOfDecimals);
//buying
if (buyOrSell)
{
require(getAvailableFunds() >= amountInUSD, "Pool: Not enough funds");
//Add to position keys if no position yet
_addPositionKey(currencyKey);
require(totalNumberOfPositions <= ISettings(settingsAddress).getParameterValue("MaximumNumberOfPositionsInPool"), "Pool: cannot exceed maximum number of positions");
IERC20(stableCoinAddress).transfer(baseUbeswapAdapterAddress, amountInUSD);
numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromPool(stableCoinAddress, currencyKey, amountInUSD, numberOfTokens);
}
//selling
else
{
uint positionIndex = positionToIndex[currencyKey];
require(positionIndex > 0, "Pool: Don't have a position in this currency");
require(IERC20(currencyKey).balanceOf(address(this)) >= numberOfTokens, "Pool: Not enough tokens in this currency");
IERC20(currencyKey).transfer(baseUbeswapAdapterAddress, numberOfTokens);
numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromPool(currencyKey, stableCoinAddress, numberOfTokens, amountInUSD);
//remove position key if no funds left in currency
_removePositionKey(currencyKey);
}
emit PlacedOrder(address(this), currencyKey, buyOrSell, numberOfTokens, block.timestamp);
}
/**
* @dev Adds liquidity for the two given tokens
* @param tokenA First token in pair
* @param tokenB Second token in pair
* @param amountA Amount of first token
* @param amountB Amount of second token
* @param farmAddress The token pair's farm address
*/
function addLiquidity(address tokenA, address tokenB, uint amountA, uint amountB, address farmAddress) public override onlyPoolManager {
require(tokenA != address(0), "Pool: invalid address for tokenA");
require(tokenB != address(0), "Pool: invalid address for tokenB");
require(amountA > 0, "Pool: amountA must be greater than 0");
require(amountB > 0, "Pool: amountB must be greater than 0");
require(IERC20(tokenA).balanceOf(address(this)) >= amountA, "Pool: not enough tokens invested in tokenA");
require(IERC20(tokenB).balanceOf(address(this)) >= amountB, "Pool: not enough tokens invested in tokenB");
//Check if farm exists for the token pair
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
address stakingTokenAddress = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress);
address pairAddress = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPair(tokenA, tokenB);
require(stakingTokenAddress == pairAddress, "Pool: stakingTokenAddress does not match pairAddress");
//Add liquidity to Ubeswap pool and stake LP tokens into associated farm
uint numberOfLPTokens = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).addLiquidity(tokenA, tokenB, amountA, amountB);
IStakingRewards(stakingTokenAddress).stake(numberOfLPTokens);
//Update liquidity positions
(address token0, address token1) = (tokenA < tokenB) ? (tokenA, tokenB) : (tokenB, tokenA);
if (liquidityPairToIndex[token0][token1] == 0)
{
liquidityPositions[numberOfLiquidityPositions] = LiquidityPair(token0, token1, farmAddress, numberOfLPTokens);
liquidityPairToIndex[token0][token1] = numberOfLiquidityPositions;
numberOfLiquidityPositions = numberOfLiquidityPositions.add(1);
}
else
{
uint index = liquidityPairToIndex[token0][token1];
liquidityPositions[index].numberOfLPTokens = liquidityPositions[index].numberOfLPTokens.add(numberOfLPTokens);
}
//Update position keys
_removePositionKey(tokenA);
_removePositionKey(tokenB);
emit AddedLiquidity(address(this), tokenA, tokenB, amountA, amountB, numberOfLPTokens, block.timestamp);
}
/**
* @dev Removes liquidity for the two given tokens
* @param tokenA First token in pair
* @param tokenB Second token in pair
* @param farmAddress The token pair's farm address
* @param numberOfLPTokens Number of LP tokens to remove from the farm
*/
function removeLiquidity(address tokenA, address tokenB, address farmAddress, uint numberOfLPTokens) public override onlyPoolManager {
require(tokenA != address(0), "Pool: invalid address for tokenA");
require(tokenB != address(0), "Pool: invalid address for tokenB");
//Check if pool has enough LP tokens in the farm
(address token0, address token1) = (tokenA < tokenB) ? (tokenA, tokenB) : (tokenB, tokenA);
uint index = liquidityPairToIndex[token0][token1];
require(liquidityPositions[index].numberOfLPTokens >= numberOfLPTokens, "Pool: not enough LP tokens to unstake");
//Check if farmAddress is valid
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
require(IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress) != address(0), "Invalid farm address");
//Withdraw all LP tokens from the farm and claim available UBE rewards
//Need to restake remaining LP tokens later
IStakingRewards(farmAddress).exit();
//Check for UBE balance and update position keys if UBE not currently in postion keys
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address UBE = ISettings(settingsAddress).getCurrencyKeyFromSymbol("UBE");
_addPositionKey(UBE);
//Remove liquidity from Ubeswap liquidity pool
(uint amountA, uint amountB) = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).removeLiquidity(tokenA, tokenB, numberOfLPTokens);
//Update position keys
_addPositionKey(tokenA);
_addPositionKey(tokenB);
require(totalNumberOfPositions <= ISettings(settingsAddress).getParameterValue("MaximumNumberOfPositionsInPool"), "Pool: cannot exceed maximum number of positions");
//Update liquidity positions
liquidityPositions[index].numberOfLPTokens = liquidityPositions[index].numberOfLPTokens.sub(numberOfLPTokens);
//Restake remaining LP tokens
IStakingRewards(farmAddress).stake(liquidityPositions[index].numberOfLPTokens);
emit RemovedLiquidity(address(this), tokenA, tokenB, numberOfLPTokens, amountA, amountB, block.timestamp);
}
/**
* @dev Collects available UBE rewards for the given Ubeswap farm
* @param farmAddress The token pair's farm address
*/
function claimUbeswapRewards(address farmAddress) public override onlyPoolManager {
//Check if farmAddress is valid
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
require(IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress) != address(0), "Invalid farm address");
//Check if pool has tokens staked in farm
require(IStakingRewards(farmAddress).balanceOf(address(this)) > 0, "Pool: no tokens staked in farm");
//Claim available UBE rewards
IStakingRewards(farmAddress).getReward();
//Check for UBE balance and update position keys if UBE not currently in postion keys
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address UBE = ISettings(settingsAddress).getCurrencyKeyFromSymbol("UBE");
_addPositionKey(UBE);
require(totalNumberOfPositions <= ISettings(settingsAddress).getParameterValue("MaximumNumberOfPositionsInPool"), "Pool: cannot exceed maximum number of positions");
emit ClaimedUbeswapRewards(address(this), farmAddress, block.timestamp);
}
/**
* @dev Opens a new leveraged asset position; swaps cUSD for specified asset
* @notice LeveragedAssetPositionManager checks if currency is supported
* @param underlyingAsset Address of the leveraged asset
* @param collateral Amount of cUSD to use as collateral
* @param amountToBorrow Amount of cUSD to borrow
*/
function openLeveragedAssetPosition(address underlyingAsset, uint collateral, uint amountToBorrow) public override onlyPoolManager {
require(getAvailableFunds() >= collateral, "Pool: not enough funds");
require(underlyingAsset != address(0), "Pool: invalid asset address");
address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager");
address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards");
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
IERC20(stableCoinAddress).approve(stableCoinStakingRewardsAddress, collateral);
ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).openPosition(underlyingAsset, collateral, amountToBorrow);
totalNumberOfPositions = totalNumberOfPositions.add(1);
require(totalNumberOfPositions <= ISettings(settingsAddress).getParameterValue("MaximumNumberOfPositionsInPool"), "Pool: cannot exceed maximum number of positions");
emit OpenedLeveragedAssetPosition(address(this), underlyingAsset, collateral, amountToBorrow, block.timestamp);
}
/**
* @dev Reduces the size of a leveraged asset position
* @notice LeveragedAssetPositionManager checks if pool is owner of position at given index
* @param positionIndex Index of the leveraged position in array of leveraged positions
* @param numberOfTokens Number of tokens to sell
*/
function reduceLeveragedAssetPosition(uint positionIndex, uint numberOfTokens) public override onlyPoolManager {
require(positionIndex > 0, "Pool: positionIndex must be greater than 0");
require(numberOfTokens > 0, "Pool: numberOfTokens must be greater than 0");
address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager");
ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).reducePosition(positionIndex, numberOfTokens);
emit ReducedLeveragedAssetPosition(address(this), positionIndex, numberOfTokens, block.timestamp);
}
/**
* @dev Closes a leveraged asset position
* @notice LeveragedAssetPositionManager checks if pool is owner of position at given index
* @param positionIndex Index of the leveraged position in array of leveraged positions
*/
function closeLeveragedAssetPosition(uint positionIndex) public override onlyPoolManager {
require(positionIndex > 0, "Pool: positionIndex must be greater than 0");
address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager");
ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).closePosition(positionIndex);
totalNumberOfPositions = totalNumberOfPositions.sub(1);
emit ClosedLeveragedAssetPosition(address(this), positionIndex, block.timestamp);
}
/**
* @dev Adds collateral to the leveraged asset position
* @notice LeveragedAssetPositionManager checks if pool is owner of position at given index
* @param positionIndex Index of the leveraged position in array of leveraged positions
* @param amountOfUSD Amount of cUSD to add as collateral
*/
function addCollateralToLeveragedAssetPosition(uint positionIndex, uint amountOfUSD) public override onlyPoolManager {
require(getAvailableFunds() >= amountOfUSD, "Pool: not enough funds");
require(positionIndex > 0, "Pool: positionIndex must be greater than 0");
address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager");
address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards");
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
IERC20(stableCoinAddress).approve(stableCoinStakingRewardsAddress, amountOfUSD);
ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).addCollateral(positionIndex, amountOfUSD);
emit AddedCollateralToLeveragedAssetPosition(address(this), positionIndex, amountOfUSD, block.timestamp);
}
/**
* @dev Removes collateral from the leveraged asset position
* @notice LeveragedAssetPositionManager checks if pool is owner of position at given index
* @param positionIndex Index of the leveraged position in array of leveraged positions
* @param numberOfTokens Number of asset tokens to remove as collateral
*/
function removeCollateralFromLeveragedAssetPosition(uint positionIndex, uint numberOfTokens) public override onlyPoolManager {
require(positionIndex > 0, "Pool: positionIndex must be greater than 0");
require(numberOfTokens > 0, "Pool: numberOfTokens must be greater than 0");
address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager");
ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).removeCollateral(positionIndex, numberOfTokens);
emit RemovedCollateralFromLeveragedAssetPosition(address(this), positionIndex, numberOfTokens, block.timestamp);
}
/**
* @dev Opens a new leveraged liquidity position; swaps cUSD for specified asset
* @notice LeveragedLiquidityPositionManager checks if tokens are supported
* @notice LeveragedLiquidityPositionManager checks if farmAddress is supported
* @param tokenA Address of first token in pair
* @param tokenB Address of second token in pair
* @param collateral Amount of cUSD to use as collateral
* @param amountToBorrow Amount of cUSD to borrow
* @param farmAddress Address of token pair's Ubeswap farm
*/
function openLeveragedLiquidityPosition(address tokenA, address tokenB, uint collateral, uint amountToBorrow, address farmAddress) public override onlyPoolManager {
require(getAvailableFunds() >= collateral, "Pool: not enough funds");
require(tokenA != address(0), "Pool: invalid tokenA address");
require(tokenB != address(0), "Pool: invalid tokenB address");
require(farmAddress != address(0), "Pool: invalid farm address");
address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager");
address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards");
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
IERC20(stableCoinAddress).approve(stableCoinStakingRewardsAddress, collateral);
ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).openPosition(tokenA, tokenB, collateral, amountToBorrow, farmAddress);
totalNumberOfPositions = totalNumberOfPositions.add(1);
require(totalNumberOfPositions <= ISettings(settingsAddress).getParameterValue("MaximumNumberOfPositionsInPool"), "Pool: cannot exceed maximum number of positions");
emit OpenedLeveragedLiquidityPosition(address(this), tokenA, tokenB, collateral, amountToBorrow, farmAddress, block.timestamp);
}
/**
* @dev Reduces the size of a leveraged liquidity position
* @param positionIndex Index of the leveraged position in array of leveraged positions
* @param numberOfTokens Number of tokens to sell
*/
function reduceLeveragedLiquidityPosition(uint positionIndex, uint numberOfTokens) public override onlyPoolManager {
require(positionIndex > 0, "Pool: positionIndex must be greater than 0");
require(numberOfTokens > 0, "Pool: numberOfTokens must be greater than 0");
address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager");
ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).reducePosition(positionIndex, numberOfTokens);
emit ReducedLeveragedLiquidityPosition(address(this), positionIndex, numberOfTokens, block.timestamp);
}
/**
* @dev Closes a leveraged liquidity position
* @param positionIndex Index of the leveraged position in array of leveraged positions
*/
function closeLeveragedLiquidityPosition(uint positionIndex) public override onlyPoolManager {
require(positionIndex > 0, "Pool: positionIndex must be greater than 0");
address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager");
ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).closePosition(positionIndex);
totalNumberOfPositions = totalNumberOfPositions.sub(1);
emit ClosedLeveragedLiquidityPosition(address(this), positionIndex, block.timestamp);
}
/**
* @dev Adds collateral to the leveraged liquidity position
* @param positionIndex Index of the leveraged position in array of leveraged positions
* @param amountOfUSD Amount of cUSD to add as collateral
*/
function addCollateralToLeveragedLiquidityPosition(uint positionIndex, uint amountOfUSD) public override onlyPoolManager {
require(getAvailableFunds() >= amountOfUSD, "Pool: not enough funds");
require(positionIndex > 0, "Pool: positionIndex must be greater than 0");
address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager");
address stableCoinStakingRewardsAddress = ADDRESS_RESOLVER.getContractAddress("StableCoinStakingRewards");
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
IERC20(stableCoinAddress).approve(stableCoinStakingRewardsAddress, amountOfUSD);
ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).addCollateral(positionIndex, amountOfUSD);
emit AddedCollateralToLeveragedLiquidityPosition(address(this), positionIndex, amountOfUSD, block.timestamp);
}
/**
* @dev Removes collateral from the leveraged liquidity position
* @param positionIndex Index of the leveraged position in array of leveraged positions
* @param numberOfTokens Number of asset tokens to remove as collateral
*/
function removeCollateralFromLeveragedLiquidityPosition(uint positionIndex, uint numberOfTokens) public override onlyPoolManager {
require(positionIndex > 0, "Pool: positionIndex must be greater than 0");
require(numberOfTokens > 0, "Pool: numberOfTokens must be greater than 0");
address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager");
ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).removeCollateral(positionIndex, numberOfTokens);
emit RemovedCollateralFromLeveragedLiquidityPosition(address(this), positionIndex, numberOfTokens, block.timestamp);
}
/**
* @dev Claims available UBE rewards for the leveraged liquidity position
* @param positionIndex Index of the leveraged position in array of leveraged positions
*/
function getReward(uint positionIndex) public override onlyPoolManager {
require(positionIndex > 0, "Pool: positionIndex must be greater than 0");
address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager");
ILeveragedLiquidityPositionManager(leveragedLiquidityPositionManagerAddress).getReward(positionIndex);
//Check for UBE balance and update position keys if UBE not currently in postion keys
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address UBE = ISettings(settingsAddress).getCurrencyKeyFromSymbol("UBE");
_addPositionKey(UBE);
require(totalNumberOfPositions <= ISettings(settingsAddress).getParameterValue("MaximumNumberOfPositionsInPool"), "Pool: cannot exceed maximum number of positions");
emit RewardPaid(address(this), positionIndex, block.timestamp);
}
/**
* @dev Updates the pool's farm address
* @param farmAddress Address of the pool's farm
*/
function setFarmAddress(address farmAddress) public override onlyPoolFactory {
require(farmAddress != address(0), "Invalid farm address");
_farmAddress = farmAddress;
}
/**
* @dev Decrement's the totalNumberOfPositions
* @notice Called from liquidate() in LeveragedAssetPositionManager or LeveragedLiquidityPositionManager
*/
function decrementTotalPositionCount() public override onlyLeveragedPositionManager {
totalNumberOfPositions = totalNumberOfPositions.sub(1);
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @dev Calculates the USD value of a token pair
* @param tokenA First token in the pair
* @param tokenB Second token in the pair
* @param numberOfLPTokens Number of LP tokens in the pair
*/
function _calculateValueOfLPTokens(address tokenA, address tokenB, uint numberOfLPTokens) internal view returns (uint) {
require(tokenA != address(0), "Pool: invalid address for tokenA");
require(tokenB != address(0), "Pool: invalid address for tokenB");
if (numberOfLPTokens == 0)
{
return 0;
}
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
(uint amountA, uint amountB) = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getTokenAmountsFromPair(tokenA, tokenB, numberOfLPTokens);
uint numberOfDecimalsA = IERC20(tokenA).decimals();
uint USDperTokenA = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(tokenA);
uint USDBalanceA = amountA.mul(USDperTokenA).div(10 ** numberOfDecimalsA);
uint numberOfDecimalsB = IERC20(tokenB).decimals();
uint USDperTokenB = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(tokenB);
uint USDBalanceB = amountB.mul(USDperTokenB).div(10 ** numberOfDecimalsB);
return USDBalanceA.add(USDBalanceB);
}
/**
* @dev Adds the given currency to position keys
* @param currency Address of token to add
*/
function _addPositionKey(address currency) internal {
require(currency != address(0), "Pool: invalid asset address");
//Add token to positionKeys if balance > 0 and not currently in positionKeys
if (IERC20(currency).balanceOf(address(this)) > 0 && positionToIndex[currency] == 0)
{
positionToIndex[currency] = numberOfPositions;
_positionKeys[numberOfPositions] = currency;
numberOfPositions = numberOfPositions.add(1);
totalNumberOfPositions = totalNumberOfPositions.add(1);
}
}
/**
* @dev Removes the given currency to position keys
* @param currency Address of token to remove
*/
function _removePositionKey(address currency) internal {
require(currency != address(0), "Pool: invalid asset address");
//Remove currency from positionKeys if no balance left
if (IERC20(currency).balanceOf(address(this)) == 0)
{
_positionKeys[positionToIndex[currency]] = _positionKeys[numberOfPositions - 1];
positionToIndex[_positionKeys[numberOfPositions - 1]] = positionToIndex[currency];
delete _positionKeys[numberOfPositions - 1];
delete positionToIndex[currency];
numberOfPositions = numberOfPositions.sub(1);
totalNumberOfPositions = totalNumberOfPositions.sub(1);
}
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
_balanceOf[from] = _balanceOf[from].sub(value);
_balanceOf[to] = _balanceOf[to].add(value);
emit Transfer(from, to, value);
}
/* ========== MODIFIERS ========== */
modifier onlyPoolFactory() {
address poolFactoryAddress = ADDRESS_RESOLVER.getContractAddress("PoolFactory");
require(msg.sender == poolFactoryAddress, "Pool: Only PoolFactory contract can call this function");
_;
}
modifier onlyPoolManager() {
require(msg.sender == _manager, "Pool: Only pool's manager can call this function");
_;
}
modifier onlyLeveragedPositionManager() {
address leveragedLiquidityPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedLiquidityPositionManager");
address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager");
require(msg.sender == leveragedLiquidityPositionManagerAddress || msg.sender == leveragedAssetPositionManagerAddress, "Pool: Only a leverage position manager contract can call this function");
_;
}
/* ========== EVENTS ========== */
event Deposit(address indexed poolAddress, address indexed userAddress, uint amount, uint timestamp);
event Withdraw(address indexed poolAddress, address indexed userAddress, uint amount, uint timestamp);
event PlacedOrder(address indexed poolAddress, address indexed currencyKey, bool buyOrSell, uint amount, uint timestamp);
event AddedLiquidity(address indexed poolAddress, address tokenA, address tokenB, uint amountA, uint amountB, uint numberOfLPTokensReceived, uint timestamp);
event RemovedLiquidity(address indexed poolAddress, address tokenA, address tokenB, uint numberOfLPTokens, uint amountAReceived, uint amountBReceived, uint timestamp);
event ClaimedUbeswapRewards(address indexed poolAddress, address farmAddress, uint timestamp);
//Leveraged asset positions
event OpenedLeveragedAssetPosition(address indexed poolAddress, address indexed underlyingAsset, uint collateral, uint numberOfTokensBorrowed, uint timestamp);
event ReducedLeveragedAssetPosition(address indexed poolAddress, uint indexed positionIndex, uint numberOfTokens, uint timestamp);
event ClosedLeveragedAssetPosition(address indexed poolAddress, uint indexed positionIndex, uint timestamp);
event AddedCollateralToLeveragedAssetPosition(address indexed poolAddress, uint indexed positionIndex, uint collateralAdded, uint timestamp);
event RemovedCollateralFromLeveragedAssetPosition(address indexed poolAddress, uint indexed positionIndex, uint collateralRemoved, uint timestamp);
//Leveraged liquidity positions
event OpenedLeveragedLiquidityPosition(address indexed poolAddress, address tokenA, address tokenB, uint collateral, uint numberOfTokensBorrowed, address farmAddress, uint timestamp);
event ReducedLeveragedLiquidityPosition(address indexed poolAddress, uint indexed positionIndex, uint numberOfTokens, uint timestamp);
event ClosedLeveragedLiquidityPosition(address indexed poolAddress, uint indexed positionIndex, uint timestamp);
event AddedCollateralToLeveragedLiquidityPosition(address indexed poolAddress, uint indexed positionIndex, uint collateralAdded, uint timestamp);
event RemovedCollateralFromLeveragedLiquidityPosition(address indexed poolAddress, uint indexed positionIndex, uint collateralRemoved, uint timestamp);
event RewardPaid(address indexed poolAddress, uint positionIndex, uint timestamp);
}
|
Reduces the size of a leveraged asset position LeveragedAssetPositionManager checks if pool is owner of position at given index positionIndex Index of the leveraged position in array of leveraged positions numberOfTokens Number of tokens to sell/
|
function reduceLeveragedAssetPosition(uint positionIndex, uint numberOfTokens) public override onlyPoolManager {
require(positionIndex > 0, "Pool: positionIndex must be greater than 0");
require(numberOfTokens > 0, "Pool: numberOfTokens must be greater than 0");
address leveragedAssetPositionManagerAddress = ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager");
ILeveragedAssetPositionManager(leveragedAssetPositionManagerAddress).reducePosition(positionIndex, numberOfTokens);
emit ReducedLeveragedAssetPosition(address(this), positionIndex, numberOfTokens, block.timestamp);
}
| 6,365,228 |
// SPDX-License-Identifier: MIT
// Decentralized Ticketing using NFTs - ERC721 Implementation for Proof of Concept Only
// Gas Efficiency and Decentralization/Data Storage Tradeoffs Not Optimized
// Torrential Labs - 2021
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Raindrops is ERC721URIStorage, Ownable {
uint256 private constant precision = 10000; // Variable to use as a base when calculating percents - all percents have to match this variable size
uint256 public creatorPercent; // Fee paid to the event fee address from ticket resale - defaults to event creator unless sold
uint256 public protocolPercent; // Fee paid to the protocol from ticket resale and event resale
uint256 public depositAmount; // Flat fee that the event/ticket creator pays for each ticket - redeemed by the ticket owner when they attend the event
uint256 public depositBalance; // Sum total of outstanding ticket deposits
uint256 public protocolTreasury; // Sum total of protocol earnings (ticket resale + expired deposits)
address public redemptionManager; // Address for automated redemption daemon
address public treasuryManager; // Address which can remove funds from the treasury
// Array re-work
uint256 public totalEvents;
uint256 public totalTickets;
// Mappings
// Events
mapping(string => bool) eventNameToExists; // Default value is false - could go away if event 0 doesn't exist
mapping(string => string) eventNameToEventDesc;
mapping(string => address) eventNameToOwner; // Only the owner can create tickets and list an event for sale
mapping(string => uint256) eventNameToNumberTickets;
mapping(string => uint256) eventNameToEventDate;
mapping(uint256 => string) public eventNumberToEventName;
// Tickets
mapping(uint256 => string) ticketNumberToEventName;
mapping(uint256 => address) ticketNumberToOwner;
mapping(uint256 => string) ticketNumberToURI;
mapping(uint256 => uint256) ticketNumberToDeposit;
mapping(uint256 => uint256) ticketNumberToPrice;
mapping(uint256 => bool) ticketNumberToRedeemed;
mapping(uint256 => bool) ticketNumberToSale;
// Funding
mapping(address => uint256) addressToAmountFunded;
// Events
event eventCreated(string eventName, string description, uint256 eventDate, uint256 numberTickets, uint256 ticketPrice);
event ticketRedemption(string eventName, uint256 ticketNumber, address ticketOwner);
event depositAmountUpdated(uint256 oldDepositAmount, uint256 newDepositAmount);
event resalePercentUpdated(uint256 oldResalePercent, uint256 newResalePercent);
event newTicketsForEvent(string eventName, uint256 numberTickets, uint256 ticketPrice);
event ticketListed(uint256 ticketNumber, uint256 price);
event ticketDelisted(uint256 ticketNumber);
event ticketSold(uint256 ticketNumber, address seller, address buyer, uint256 amount, uint256 creatorFees, uint256 protocolFees);
event treasuryFundsRemoved(address sender, uint256 amount);
// Contract Constructor
// Removed from constructor: uint256 _withdrawLimitThreshold, uint16 _withdrawLimit, uint16 _withdrawCooldown
constructor(address _treasuryManager, address _redemptionManager, uint256 _depositAmount,
uint256 _creatorPercent, uint256 _protocolPercent)
ERC721("Raindrops", "DROP") {
require(_creatorPercent <= precision && _protocolPercent <= precision);
// Set Helper Contract Adresses
redemptionManager = _redemptionManager;
treasuryManager = _treasuryManager;
// Initialize the protocol fees
depositAmount = _depositAmount;
creatorPercent = _creatorPercent;
protocolPercent = _protocolPercent;
}
// Protocol Interaction Functions
// Add funding to contract to pay for ticket deposits
function addFunds() external payable returns(uint256 newBalance) {
addressToAmountFunded[msg.sender] += msg.value;
return addressToAmountFunded[msg.sender];
}
// Remove funding from the contract
function removeFunds(uint256 amount) external returns(uint256 newBalance) {
// Sender must have the funds
require(addressToAmountFunded[msg.sender] >= amount, "RE-0");
// Settle the funds
payable(msg.sender).transfer(amount);
addressToAmountFunded[msg.sender] -= amount;
return addressToAmountFunded[msg.sender];
}
// Remove funds from the protocol treasury - call only be called by the treasury manager address
function removeFundsTreasury(uint256 amount) external returns(uint256 newBalance) {
// Require that the call be the treasury manager
require(treasuryManager == msg.sender, "RE-1");
// Prevent the removal of more funds than is allowed
require(amount <= protocolTreasury, "RE-2");
// Settle the funds
payable(msg.sender).transfer(amount);
protocolTreasury -= amount;
// Emit Event
emit treasuryFundsRemoved(msg.sender, amount);
return protocolTreasury;
}
// Create tickets for a new event
function createNewEvent(string memory eventName, string memory eventDescription, uint256 eventDate, uint256 numberTickets, uint256 ticketPrice) external {
// Require that an event with the same name does not exist
require(eventNameToExists[eventName] == false, "RE-3");
// Create a New Event - 0 event does not exist
totalEvents += 1;
// Update Mappings
eventNumberToEventName[totalEvents] = eventName;
eventNameToExists[eventName] = true;
eventNameToOwner[eventName] = msg.sender;
eventNameToEventDesc[eventName] = eventDescription;
eventNameToEventDate[eventName] = eventDate;
// Create the Tickets
addTickets(eventName, numberTickets, ticketPrice);
// Emit Event
emit eventCreated(eventName, eventDescription, eventDate, numberTickets, ticketPrice);
}
// Create additional tickets for an event
function addTickets(string memory eventName, uint256 numberTickets, uint256 ticketPrice) public {
// Require that the sender owns this event and that they can pay for the ticket deposits
require(eventNameToOwner[eventName] == msg.sender, "RE-4");
require(addressToAmountFunded[msg.sender] >= numberTickets * depositAmount,
"RE-5");
// Track the new ticket deposits
depositBalance += numberTickets * depositAmount;
// Update the sender's balance
addressToAmountFunded[msg.sender] -= numberTickets * depositAmount;
// Create Tickets in a Loop
for (uint i; i < numberTickets; i++){
// Update ticket number to next free slot - 0 ticket does not exist
totalTickets += 1;
// Mint the ERC token
_safeMint(msg.sender, totalTickets);
// Update Mappings
ticketNumberToEventName[totalTickets] = eventName;
ticketNumberToOwner[totalTickets] = msg.sender;
ticketNumberToDeposit[totalTickets] = depositAmount;
ticketNumberToPrice[totalTickets] = ticketPrice;
ticketNumberToSale[totalTickets] = true;
ticketNumberToRedeemed[totalTickets] = false;
}
// Update Mappings
eventNameToNumberTickets[eventName] += numberTickets;
// Emit Event
emit newTicketsForEvent(eventName, numberTickets, ticketPrice);
}
// List a ticket as for sale - this allows it to be bought at any time
// If the ticket is already listed for sale then this will update the sale price
// Sale price is in ETH (gwei)
function listTicket(uint256 ticketNumber, uint256 salePrice) external {
// Require that the sender be the owner of this ticket / ticket exists
require(ticketNumberToOwner[ticketNumber] == msg.sender, "RE-6");
// Allow this ticket to be sold and update the price
ticketNumberToSale[ticketNumber] = true;
ticketNumberToPrice[ticketNumber] = salePrice;
// Emit Event
emit ticketListed(ticketNumber, salePrice);
}
// Delists a ticket from sale - prevents purchase of ticket
function delistTicket(uint256 ticketNumber) external {
// Require that the sender be the owner of this ticket / ticket exists
require(ticketNumberToOwner[ticketNumber] == msg.sender, "RE-7");
// Diable this ticket from being sold) - price doesn't need to be updated it will be overrided when relisted
ticketNumberToSale[ticketNumber] = false;
// Emit Event
emit ticketDelisted(ticketNumber);
}
// Buy a ticket that is listed for sale - you will buy the ticket at the list price
function buyTicket(uint256 ticketNumber) external {
// Set working variables
uint256 ticketPrice = ticketNumberToPrice[ticketNumber];
address ticketOwner = ticketNumberToOwner[ticketNumber];
// Require that the ticket is listed for sale - this will also check that the ticket exists since default bool is false
require(ticketNumberToSale[ticketNumber] == true, "RE-8");
// Require that the sender has the funds to buy the ticket
require(addressToAmountFunded[msg.sender] > ticketPrice, "RE-9");
// Calculate the protocol fee & creator fees
uint256 protocolFee = (ticketPrice * protocolPercent) / precision;
uint256 creatorFee = (ticketPrice * creatorPercent) / precision;
// Calculate the remaining funds which will be sent from the buyer to the sellers account
uint256 saleAmount = ticketPrice - protocolFee - creatorFee;
// Transfer ownership of the ticket and the NFT
_transfer(ticketOwner, msg.sender, ticketNumber);
// Settle the funds - buyer and seller
addressToAmountFunded[msg.sender] -= ticketPrice;
addressToAmountFunded[ticketOwner] += saleAmount;
// Settle the fees - creator and protocol
address creatorAddress = eventNameToOwner[ticketNumberToEventName[ticketNumber]];
addressToAmountFunded[creatorAddress] += creatorFee;
protocolTreasury += protocolFee;
// Emit Event
emit ticketSold(ticketNumber, ticketOwner, msg.sender, saleAmount, creatorFee, protocolFee);
// Update tracking variables - price doesn't need to be updated it will be overrided when relisted
ticketNumberToOwner[ticketNumber] = msg.sender;
ticketNumberToSale[ticketNumber] = false;
}
// Only callable by the redemption address - which can be changed by the owner if needed
// ** Move expired determination on-chain within the smart contract later **
// For now expiration will be determined by the redemption daemon in the cloud prior to calling this function
function redeemTickets(uint256 [] memory ticketNumbers, bool [] memory expired) external {
// Limit redemption of tickets to the redemption address only
require(msg.sender == redemptionManager, "RE-10");
for (uint i; i < ticketNumbers.length; i++){
redeemTicket(ticketNumbers[i], expired[i]);
}
}
// Internal Functions
// ** Move expired determination on-chain within the smart contract later **
// For now expiration will be determined by the redemption daemon in the cloud prior to calling this function
function redeemTicket(uint256 ticketNumber, bool expired) internal {
// Check that this ticket has not yet been redeemed - there are safety checks in the cloud already so this should not trigger
require(ticketNumberToRedeemed[ticketNumber] == false, "RE-11");
// Safety check to make sure more funds aren't given for deposits than availible - this should never trigger
require(depositBalance - ticketNumberToDeposit[ticketNumber] >= 0, "RE-12");
if (!expired) {
// Pay the ticket deposit to the ticker owner
depositBalance -= ticketNumberToDeposit[ticketNumber];
addressToAmountFunded[ticketNumberToOwner[ticketNumber]] += ticketNumberToDeposit[ticketNumber];
// Emit Event
emit ticketRedemption(ticketNumberToEventName[ticketNumber], ticketNumber, ticketNumberToOwner[ticketNumber]);
} else {
// Deposit fee goes to the protocol - ticket was never scanned at event
depositBalance -= ticketNumberToDeposit[ticketNumber];
protocolTreasury += ticketNumberToDeposit[ticketNumber];
// Emit Event
emit ticketRedemption(ticketNumberToEventName[ticketNumber], ticketNumber, address(this));
}
// Set ticket status to redeemed
ticketNumberToRedeemed[ticketNumber] = true;
}
// Setter Functions
function setTokenURI(uint256 ticketNumber, string memory _tokenURI) external onlyOwner {
_setTokenURI(ticketNumber, _tokenURI);
ticketNumberToURI[ticketNumber] = _tokenURI;
}
function setDepositAmount(uint256 newDepositAmount) external onlyOwner {
emit depositAmountUpdated(depositAmount, newDepositAmount);
depositAmount = newDepositAmount;
}
function setProtocolPercent(uint16 newProtocolPercent) external onlyOwner {
// Limit upper bound of the protocol percentage to protect against errors
require(newProtocolPercent <= 15000, "RE-13");
emit depositAmountUpdated(protocolPercent, newProtocolPercent);
protocolPercent = newProtocolPercent;
}
function setCreatorPercent(uint16 newCreatorPercent) external onlyOwner {
// Limit upper bound of the creator percentage to protect against errors
require(newCreatorPercent <= 15000, "RE-14");
emit depositAmountUpdated(creatorPercent, newCreatorPercent);
creatorPercent = newCreatorPercent;
}
// Getter Functions
function getAccountBalance(address account) external view returns(uint256 balance) {
return addressToAmountFunded[account];
}
function getTokenURI(uint256 ticketNumber) public view returns(string memory) {
return tokenURI(ticketNumber);
}
// These view functions can be replaced by a subgraph using the event outputted info
// Returns all info for an event - byte size ~ .7KB
function getEventInfo(string memory eventName) external view returns(
string memory name, string memory description, uint256 date, uint256 ticketCount,
address owner, bool exists
) {
return (eventName, eventNameToEventDesc[eventName], eventNameToEventDate[eventName],
eventNameToNumberTickets[eventName], eventNameToOwner[eventName], eventNameToExists[eventName]);
}
// Returns all info for a ticket - byte size ~ .7KB
function getTicketInfo(uint256 ticketNumber) external view returns(
string memory eventName, uint256 deposit, uint256 price, string memory uri, address owner,
bool forSale, bool redeemed
) {
return (ticketNumberToEventName[ticketNumber], ticketNumberToDeposit[ticketNumber],
ticketNumberToPrice[ticketNumber], ticketNumberToURI[ticketNumber],
ticketNumberToOwner[ticketNumber], ticketNumberToSale[ticketNumber],
ticketNumberToRedeemed[ticketNumber]);
}
}
|
Remove funds from the protocol treasury - call only be called by the treasury manager address Require that the call be the treasury manager Prevent the removal of more funds than is allowed Settle the funds Emit Event
|
function removeFundsTreasury(uint256 amount) external returns(uint256 newBalance) {
require(treasuryManager == msg.sender, "RE-1");
require(amount <= protocolTreasury, "RE-2");
payable(msg.sender).transfer(amount);
protocolTreasury -= amount;
emit treasuryFundsRemoved(msg.sender, amount);
return protocolTreasury;
}
| 1,067,675 |
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.4;
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
import './BlockNoteXACL.sol';
/// @author Blockben
/// @title BlockNoteX
/// @notice BlockNoteX implementation
contract BlockNoteX is ERC20, BlockNoteXACL {
using SafeMath for uint256;
constructor(address _superadmin) ERC20('BlockNoteX', 'BNOX') BlockNoteXACL(_superadmin) {}
/**
* Set the decimals of token to 4.
*/
function decimals() public view virtual override returns (uint8) {
return 2;
}
/**
* @param _to Recipient address
* @param _value Value to send to the recipient from the caller account
*/
function transfer(address _to, uint256 _value) public override whenNotPaused returns (bool) {
_transfer(_msgSender(), _to, _value);
return true;
}
/**
* @param _from Sender address
* @param _to Recipient address
* @param _value Value to send to the recipient from the sender account
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public override whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* @param _spender Spender account
* @param _value Value to approve
*/
function approve(address _spender, uint256 _value) public override whenNotPaused returns (bool) {
require((_value == 0) || (allowance(_msgSender(), _spender) == 0), 'Approve: zero first');
return super.approve(_spender, _value);
}
/**
* @param _spender Account that allows the spending
* @param _addedValue Amount which will increase the total allowance
*/
function increaseAllowance(address _spender, uint256 _addedValue) public override whenNotPaused returns (bool) {
return super.increaseAllowance(_spender, _addedValue);
}
/**
* @param _spender Account that allows the spending
* @param _subtractValue Amount which will decrease the total allowance
*/
function decreaseAllowance(address _spender, uint256 _subtractValue) public override whenNotPaused returns (bool) {
return super.decreaseAllowance(_spender, _subtractValue);
}
/**
* @notice Only account with TREASURY_ADMIN is able to mint!
* @param _account Mint BNOX to this account
* @param _amount The mintig amount
*/
function mint(address _account, uint256 _amount) external onlyRole(TREASURY_ADMIN) whenNotPaused returns (bool) {
_mint(_account, _amount);
return true;
}
/**
* Burn BNOX from treasury account
* @notice Only account with TREASURY_ADMIN is able to burn!
* @param _amount The burning amount
*/
function burn(uint256 _amount) external onlyRole(TREASURY_ADMIN) whenNotPaused {
require(!getSourceAccountBL(treasuryAddress), 'Blacklist: treasury');
_burn(treasuryAddress, _amount);
}
/**
* @notice Account must not be on blacklist
* @param _account Mint BNOX to this account
* @param _amount The minting amount
*/
function _mint(address _account, uint256 _amount) internal override {
require(!getDestinationAccountBL(_account), 'Blacklist: target');
super._mint(_account, _amount);
}
/**
* Transfer token between accounts, based on BNOX TOS.
* - bsoFee% of the transferred amount is going to bsoPoolAddress
* - generalFee% of the transferred amount is going to amountGeneral
*
* @param _sender The address from where the token sent
* @param _recipient Recipient address
* @param _amount The amount to be transferred
*/
function _transfer(
address _sender,
address _recipient,
uint256 _amount
) internal override {
require(!getSourceAccountBL(_sender), 'Blacklist: sender');
require(!getDestinationAccountBL(_recipient), 'Blacklist: recipient');
if ((_sender == treasuryAddress) || (_recipient == treasuryAddress)) {
super._transfer(_sender, _recipient, _amount);
} else {
/**
* Three decimal in percent.
* The decimal correction is 100.000, but to avoid rounding errors, first divide by 10.000
* and after that the calculation must add 5 and divide 10 at the end.
*/
uint256 decimalCorrection = 10000;
uint256 generalFeePercent256 = generalFee;
uint256 bsoFeePercent256 = bsoFee;
uint256 totalFeePercent = generalFeePercent256.add(bsoFeePercent256);
uint256 totalFeeAmount = _amount.mul(totalFeePercent).div(decimalCorrection).add(5).div(10);
uint256 amountBso = _amount.mul(bsoFeePercent256).div(decimalCorrection).add(5).div(10);
uint256 amountGeneral = totalFeeAmount.sub(amountBso);
uint256 recipientTransferAmount = _amount.sub(totalFeeAmount);
super._transfer(_sender, _recipient, recipientTransferAmount);
if (amountGeneral > 0) {
super._transfer(_sender, feeAddress, amountGeneral);
}
if (amountBso > 0) {
super._transfer(_sender, bsoPoolAddress, amountBso);
}
}
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.4;
import '@openzeppelin/contracts/security/Pausable.sol';
import '@openzeppelin/contracts/access/AccessControl.sol';
import '@openzeppelin/contracts/utils/Context.sol';
abstract contract BlockNoteXACL is Pausable, AccessControl {
/// @notice TOKEN_ADMIN
bytes32 public constant TOKEN_ADMIN = keccak256('TOKEN_ADMIN');
/// @notice TREASURY_ADMIN. Treasury admins can only mint or burn
bytes32 public constant TREASURY_ADMIN = keccak256('TREASURY_ADMIN');
/// @notice AML_ADMIN. AML Admins can only whitelist and blacklist addresses
bytes32 public constant AML_ADMIN = keccak256('AML_ADMIN');
/**
* @notice superadmin on paper wallet for worst case compromise
*/
address superadmin;
mapping(address => bool) sourceAccountBL;
mapping(address => bool) destinationAccountBL;
/**
* @notice Public URL, that contains detailed up-to-date information about the token.
*/
string public url;
address public treasuryAddress;
address public feeAddress;
address public bsoPoolAddress;
uint16 public generalFee;
uint16 public bsoFee;
event BNOXSourceAccountBL(address indexed _account, bool _lockValue);
event BNOXDestinationAccountBL(address indexed _account, bool _lockValue);
event BNOXUrlSet(string url);
event BNOXTreasuryAddressChange(address _newAddress);
event BNOXFeeAddressChange(address _newAddress);
event BNOXBsoPoolAddressChange(address _newAddress);
event BNOXGeneralFeeChange(uint256 _newFee);
event BNOXBsoFeeChange(uint256 _newFee);
// Setting the superadmin and adding the deployer as admin
constructor(address _superadmin) {
require(_superadmin != address(0), '_superadmin cannot be 0');
superadmin = _superadmin;
_setRoleAdmin(TOKEN_ADMIN, TOKEN_ADMIN);
_setRoleAdmin(TREASURY_ADMIN, TOKEN_ADMIN);
_setRoleAdmin(AML_ADMIN, TOKEN_ADMIN);
_setupRole(TOKEN_ADMIN, _superadmin);
_setupRole(TREASURY_ADMIN, _superadmin);
_setupRole(AML_ADMIN, _superadmin);
_setupRole(TOKEN_ADMIN, _msgSender());
}
/**
* @notice Override for AccessControl.sol revokeRole to prevent revoke against superadmin
* @param _role The role which
* @param _account Revokes role from the account
*/
function revokeRole(bytes32 _role, address _account) public virtual override onlyRole(getRoleAdmin(_role)) {
require(_account != superadmin, 'superadmin can not be changed');
super.revokeRole(_role, _account);
}
function getSourceAccountBL(address _account) public view returns (bool) {
return sourceAccountBL[_account];
}
function getDestinationAccountBL(address _account) public view returns (bool) {
return destinationAccountBL[_account];
}
function setSourceAccountBL(address _account, bool _lockValue) external onlyRole(AML_ADMIN) {
sourceAccountBL[_account] = _lockValue;
emit BNOXSourceAccountBL(_account, _lockValue);
}
function setBatchSourceAccountBL(address[] calldata _addresses, bool _lockValue) external onlyRole(AML_ADMIN) {
require(_addresses.length <= 200, 'Batch: too many addresses');
for (uint256 i = 0; i < _addresses.length; i++) {
sourceAccountBL[_addresses[i]] = _lockValue;
}
}
function setBatchDestinationAccountBL(address[] calldata _addresses, bool _lockValue) external onlyRole(AML_ADMIN) {
require(_addresses.length <= 200, 'Batch: too many addresses');
for (uint256 i = 0; i < _addresses.length; i++) {
destinationAccountBL[_addresses[i]] = _lockValue;
}
}
function setDestinationAccountBL(address _account, bool _lockValue) external onlyRole(AML_ADMIN) {
destinationAccountBL[_account] = _lockValue;
emit BNOXDestinationAccountBL(_account, _lockValue);
}
function setUrl(string calldata _newUrl) external onlyRole(TOKEN_ADMIN) {
url = _newUrl;
emit BNOXUrlSet(_newUrl);
}
function setTreasuryAddress(address _newAddress) external onlyRole(TOKEN_ADMIN) {
require(_newAddress != address(0), 'treasury address cannot be 0');
treasuryAddress = _newAddress;
emit BNOXTreasuryAddressChange(_newAddress);
}
function setFeeAddress(address _newAddress) external onlyRole(TOKEN_ADMIN) {
require(_newAddress != address(0), 'fee address cannot be 0');
feeAddress = _newAddress;
emit BNOXFeeAddressChange(_newAddress);
}
function setBsoPoolAddress(address _newAddress) external onlyRole(TOKEN_ADMIN) {
require(_newAddress != address(0), 'bso pool address cannot be 0');
bsoPoolAddress = _newAddress;
emit BNOXBsoPoolAddressChange(_newAddress);
}
function setGeneralFee(uint16 _newFee) external onlyRole(TOKEN_ADMIN) {
generalFee = _newFee;
emit BNOXGeneralFeeChange(_newFee);
}
function setBsoFee(uint16 _newFee) external onlyRole(TOKEN_ADMIN) {
bsoFee = _newFee;
emit BNOXBsoFeeChange(_newFee);
}
function pause() external onlyRole(TOKEN_ADMIN) {
_pause();
}
function unpause() external onlyRole(TOKEN_ADMIN) {
_unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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 "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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);
}
|
_from Sender address _to Recipient address _value Value to send to the recipient from the sender account/
|
function transferFrom(
address _from,
address _to,
uint256 _value
) public override whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
| 1,818,389 |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/GSN/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;
}
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/introspection/ERC165.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;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
/**
* @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
* ====
*/
string constant private ERR = "Address";
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, ERR);
(bool success, ) = recipient.call{ value: amount }('');
require(success, ERR);
}
/**
* @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, ERR);
}
/**
* @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,
ERR
);
}
/**
* @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 && isContract(target),
ERR
);
(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, ERR);
}
/**
* @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), ERR);
(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), ERR);
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/Strings.sol
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = '0123456789abcdef';
string private constant ERR = "Strings";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return '0';
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev 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, ERR);
return string(buffer);
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
string private constant ERR = "Ownable";
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(), ERR);
_;
}
/**
* @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), ERR);
_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);
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.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, Ownable, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private constant ERR = "ERC721";
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// Mint pause control
uint256 public mintPaused = 1;
// 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 _initialize(string memory name_, string memory symbol_) internal {
_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), ERR);
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), ERR);
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), ERR);
bytes memory bytesURI = bytes(_baseURI);
if (bytesURI.length == 0 || bytesURI[bytesURI.length - 1] == '/')
return string(abi.encodePacked(_baseURI, tokenId.toString(), ".json"));
else return _baseURI;
}
function setBaseURI(string memory newBaseURI) external onlyOwner {
_baseURI = newBaseURI;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, ERR);
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
ERR
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(_exists(tokenId), ERR);
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),
ERR
);
_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),
ERR
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Admin pause / unpause minting
*/
function setMintPaused(uint256 paused) external onlyOwner {
mintPaused = paused;
}
/**
* @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),
ERR
);
}
/**
* @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), ERR);
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),
ERR
);
}
/**
* @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) && !_exists(tokenId), ERR);
_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);
// 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(
to != address(0) && ERC721.ownerOf(tokenId) == from,
ERR
);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, ERR);
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert('ERC721: transfer to non ERC721Receiver implementer');
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
}
/**
* @dev OpenSea proxy registry to prevent gas spend for approvals
*/
contract ProxyRegistry {
mapping(address => address) public proxies;
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
string private constant ERR = "Reentrancy";
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and 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, ERR);
// 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 Implementation of Base ERC721 contract
*/
contract ERC721Base is ERC721, ReentrancyGuard {
// OpenSea proxy registry
address private immutable _osProxyRegistryAddress;
// Address allowed to initialize contract
address private immutable _initializer;
// Max mints per transaction
uint256 private _maxTxMint;
// The CAP of mintable tokenIds
uint256 private _cap;
// ETH price of one tokenIds
uint256 private _tokenPrice;
// TokenId counter, 1 minted in ctor
uint256 private _currentTokenId;
string private constant ERR = "ERC721Base";
// Fired when funds are distributed
event Distributed(address indexed receiver, uint256 amount);
/**
* @dev Initialization.
*/
constructor(address initializer_, address osProxyRegistry_) {
_osProxyRegistryAddress = osProxyRegistry_;
_initializer = initializer_;
}
/**
* @dev Clone Initialization.
*/
function initialize(
address owner_,
string memory name_,
string memory symbol_,
uint256 cap_,
uint256 maxPerTx_,
uint256 price_) external
{
require(msg.sender == _initializer, ERR);
_transferOwnership(owner_);
ERC721._initialize(name_, symbol_);
_cap = cap_;
_maxTxMint = maxPerTx_;
_tokenPrice = price_;
// Mint our first token
_mint(owner_, 0);
_currentTokenId = 1;
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(_osProxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* @dev Distribute mint
*/
function mint(address to, uint256 numMint) external payable nonReentrant {
require(mintPaused == 0 &&
numMint > 0 &&
numMint <= _maxTxMint &&
_currentTokenId + numMint <= _cap &&
msg.value >= numMint * _tokenPrice, ERR);
for (uint256 i = 0; i < numMint; ++i)
_mint(to, _currentTokenId + i);
_currentTokenId += numMint;
uint256 dust = msg.value - (numMint * _tokenPrice);
if (dust > 0) payable(msg.sender).transfer(dust);
}
/**
* @dev Distribute rewards
*/
function distribute(
address[] calldata accounts,
uint256[] calldata refunds,
uint256[] calldata percents
) external onlyOwner {
require(
(refunds.length == 0 || refunds.length == accounts.length) &&
(percents.length == 0 || percents.length == accounts.length),
ERR
);
uint256 availableAmount = address(this).balance;
uint256[] memory amounts = new uint256[](accounts.length);
for (uint256 i = 0; i < refunds.length; ++i) {
require(refunds[i] <= availableAmount, ERR);
amounts[i] = refunds[i];
availableAmount -= refunds[i];
}
uint256 amountToShare = availableAmount;
for (uint256 i = 0; i < percents.length; ++i) {
uint256 amount = (amountToShare * percents[i]) / 100;
amounts[i] += (amount <= availableAmount) ? amount : availableAmount;
availableAmount -= amount;
}
for (uint256 i = 0; i < accounts.length; ++i) {
if (amounts[i] > 0) {
payable(accounts[i]).transfer(amounts[i]);
emit Distributed(accounts[i], amounts[i]);
}
}
}
/**
* @dev return number of minted token
*/
function totalSupply() external view returns (uint256) {
return _currentTokenId;
}
/**
* @dev we don't allow ether receive()
*/
receive() external payable {
revert('Not allowed');
}
}
|
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), ERR);
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
| 613,830 |
./full_match/4/0xf57b3262dd2a54e7831f81eA5Eb6FC2e3cF00f2F/sources/browser/PearSteak.sol
|
Unstake previous stake, mints back the original tokens, sends mint function call to reward contract to mint the reward to the sender address./
|
function unstake(uint stake_) public {
require(isStakeLocked(stake_) != true, "Stake still locked!");
_mint(msg.sender, _staking[msg.sender][stake_].amount);
stakedSupply -= _staking[msg.sender][stake_].amount;
uint _amount = getStakeReward(stake_);
(bool success, bytes memory returnData) = address(_tokenContract).call(abi.encodeWithSignature("mint(address,uint256)",msg.sender, _amount));
require(success);
_removeIndexInArray(_staking[msg.sender], stake_);
emit unstaked(msg.sender, _amount);
}
| 812,407 |
./full_match/3/0x2a4c486f16BeF9e3bb5F9BFd39534c89b843B43f/sources/browser/BigStorage.sol
|
... Ausgabe tenantname (beachte keyword "memory")
|
function gettenantname() public view returns (string memory){
return tenantname;
}
| 8,121,104 |
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
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();
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20 {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant 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);
string public constant name = "";
string public constant symbol = "";
uint8 public constant decimals = 0;
}
// Ethen Decentralized Exchange Contract
// https://ethen.io/
contract Ethen is Pausable {
// Trade & order types
uint public constant BUY = 1; // order type BID
uint public constant SELL = 0; // order type ASK
// Percent multiplier in makeFee & takeFee
uint public FEE_MUL = 1000000;
// x1000000, 0.5%
uint public constant MAX_FEE = 5000;
// Time after expiration, until order will still be valid to trade.
//
// All trades are signed by server so it should not be possible to trade
// expired orders. Let's say, signing happens at the last second.
// Some time needed for transaction to be mined. If we going to require
// here in contract that expiration time should always be less than
// a block.timestamp than such trades will not be successful.
// Instead we add some reasonable time, after which order still be valid
// to trade in contract.
uint public expireDelay = 300;
uint public constant MAX_EXPIRE_DELAY = 600;
// Value of keccak256(
// "address Contract", "string Order", "address Token", "uint Nonce",
// "uint Price", "uint Amount", "uint Expire"
// )
// See https://github.com/ethereum/EIPs/pull/712
bytes32 public constant ETH_SIGN_TYPED_DATA_ARGHASH =
0x3da4a05d8449a7bc291302cce8a490cf367b98ec37200076c3f13f1f2308fd74;
// All prices are per 1e18 tokens
uint public constant PRICE_MUL = 1e18;
//
// Public State Vars
//
// That address gets all the fees
address public feeCollector;
// x1000000
uint public makeFee = 0;
// x1000000, 2500 == 0.25%
uint public takeFee = 2500;
// user address to ether balances
mapping (address => uint) public balances;
// user address to token address to token balance
mapping (address => mapping (address => uint)) public tokens;
// user => order nonce => amount filled
mapping (address => mapping (uint => uint)) public filled;
// user => nonce => true
mapping (address => mapping (uint => bool)) public trades;
// Every trade should be signed by that address
address public signer;
// Keep track of custom fee coefficients per user
// 0 means user will pay no fees, 50 - only 50% of fees
struct Coeff {
uint8 coeff; // 0-99
uint128 expire;
}
mapping (address => Coeff) public coeffs;
// Users can pay to reduce fees
// (duration << 8) + coeff => price
mapping(uint => uint) public packs;
//
// Events
//
event NewMakeFee(uint makeFee);
event NewTakeFee(uint takeFee);
event NewFeeCoeff(address user, uint8 coeff, uint128 expire, uint price);
event DepositEther(address user, uint amount, uint total);
event WithdrawEther(address user, uint amount, uint total);
event DepositToken(address user, address token, uint amount, uint total);
event WithdrawToken(address user, address token, uint amount, uint total);
event Cancel(
uint8 order,
address owner,
uint nonce,
address token,
uint price,
uint amount
);
event Order(
address orderOwner,
uint orderNonce,
uint orderPrice,
uint tradeTokens,
uint orderFilled,
uint orderOwnerFinalTokens,
uint orderOwnerFinalEther,
uint fees
);
event Trade(
address trader,
uint nonce,
uint trade,
address token,
uint traderFinalTokens,
uint traderFinalEther
);
event NotEnoughTokens(
address owner, address token, uint shouldHaveAmount, uint actualAmount
);
event NotEnoughEther(
address owner, uint shouldHaveAmount, uint actualAmount
);
//
// Constructor
//
function Ethen(address _signer) public {
feeCollector = msg.sender;
signer = _signer;
}
//
// Admin Methods
//
function setFeeCollector(address _addr) external onlyOwner {
feeCollector = _addr;
}
function setSigner(address _addr) external onlyOwner {
signer = _addr;
}
function setMakeFee(uint _makeFee) external onlyOwner {
require(_makeFee <= MAX_FEE);
makeFee = _makeFee;
NewMakeFee(makeFee);
}
function setTakeFee(uint _takeFee) external onlyOwner {
require(_takeFee <= MAX_FEE);
takeFee = _takeFee;
NewTakeFee(takeFee);
}
function addPack(
uint8 _coeff, uint128 _duration, uint _price
) external onlyOwner {
require(_coeff < 100);
require(_duration > 0);
require(_price > 0);
uint key = packKey(_coeff, _duration);
packs[key] = _price;
}
function delPack(uint8 _coeff, uint128 _duration) external onlyOwner {
uint key = packKey(_coeff, _duration);
delete packs[key];
}
function setExpireDelay(uint _expireDelay) external onlyOwner {
require(_expireDelay <= MAX_EXPIRE_DELAY);
expireDelay = _expireDelay;
}
//
// User Custom Fees
//
function getPack(
uint8 _coeff, uint128 _duration
) public view returns (uint) {
uint key = packKey(_coeff, _duration);
return packs[key];
}
// Buys new fee coefficient for given duration of time
function buyPack(
uint8 _coeff, uint128 _duration
) external payable {
require(now >= coeffs[msg.sender].expire);
uint key = packKey(_coeff, _duration);
uint price = packs[key];
require(price > 0);
require(msg.value == price);
updateCoeff(msg.sender, _coeff, uint128(now) + _duration, price);
balances[feeCollector] = SafeMath.add(
balances[feeCollector], msg.value
);
}
// Sets new fee coefficient for user
function setCoeff(
uint8 _coeff, uint128 _expire, uint8 _v, bytes32 _r, bytes32 _s
) external {
bytes32 hash = keccak256(this, msg.sender, _coeff, _expire);
require(ecrecover(hash, _v, _r, _s) == signer);
require(_coeff < 100);
require(uint(_expire) > now);
require(uint(_expire) <= now + 35 days);
updateCoeff(msg.sender, _coeff, _expire, 0);
}
//
// User Balance Related Methods
//
function () external payable {
balances[msg.sender] = SafeMath.add(balances[msg.sender], msg.value);
DepositEther(msg.sender, msg.value, balances[msg.sender]);
}
function depositEther() external payable {
balances[msg.sender] = SafeMath.add(balances[msg.sender], msg.value);
DepositEther(msg.sender, msg.value, balances[msg.sender]);
}
function withdrawEther(uint _amount) external {
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _amount);
msg.sender.transfer(_amount);
WithdrawEther(msg.sender, _amount, balances[msg.sender]);
}
function depositToken(address _token, uint _amount) external {
require(ERC20(_token).transferFrom(msg.sender, this, _amount));
tokens[msg.sender][_token] = SafeMath.add(
tokens[msg.sender][_token], _amount
);
DepositToken(msg.sender, _token, _amount, tokens[msg.sender][_token]);
}
function withdrawToken(address _token, uint _amount) external {
tokens[msg.sender][_token] = SafeMath.sub(
tokens[msg.sender][_token], _amount
);
require(ERC20(_token).transfer(msg.sender, _amount));
WithdrawToken(msg.sender, _token, _amount, tokens[msg.sender][_token]);
}
//
// User Trade Methods
//
// Fills order so it cant be executed later
function cancel(
uint8 _order, // BUY for bid orders or SELL for ask orders
address _token,
uint _nonce,
uint _price, // Price per 1e18 (PRICE_MUL) tokens
uint _amount,
uint _expire,
uint _v,
bytes32 _r,
bytes32 _s
) external {
require(_order == BUY || _order == SELL);
if (now > _expire + expireDelay) {
// already expired
return;
}
getVerifiedHash(
msg.sender,
_order, _token, _nonce, _price, _amount, _expire,
_v, _r, _s
);
filled[msg.sender][_nonce] = _amount;
Cancel(_order, msg.sender, _nonce, _token, _price, _amount);
}
// Does trade, places order
// Argument hell because of "Stack to deep" errors.
function trade(
// _nums[0] 1=BUY, 0=SELL
// _nums[1] trade.nonce
// _nums[2] trade.v
// _nums[3] trade.expire
// _nums[4] order[0].nonce First order should have
// _nums[5] order[0].price best available price
// _nums[6] order[0].amount
// _nums[7] order[0].expire
// _nums[8] order[0].v
// _nums[9] order[0].tradeAmount
// ...
// _nums[6N-2] order[N-1].nonce N -> 6N+4
// _nums[6N-1] order[N-1].price N -> 6N+5
// _nums[6N] order[N-1].amount N -> 6N+6
// _nums[6N+1] order[N-1].expire N -> 6N+7
// _nums[6N+2] order[N-1].v N -> 6N+8
// _nums[6N+3] order[N-1].tradeAmount N -> 6N+9
uint[] _nums,
// _addrs[0] token
// _addrs[1] order[0].owner
// ...
// _addrs[N] order[N-1].owner N -> N+1
address[] _addrs,
// _rss[0] trade.r
// _rss[1] trade.s
// _rss[2] order[0].r
// _rss[3] order[0].s
// ...
// _rss[2N] order[N-1].r N -> 2N+2
// _rss[2N+1] order[N-1].s N -> 2N+3
bytes32[] _rss
) public whenNotPaused {
// number of orders
uint N = _addrs.length - 1;
require(_nums.length == 6*N+4);
require(_rss.length == 2*N+2);
// Type of trade
// _nums[0] BUY or SELL
require(_nums[0] == BUY || _nums[0] == SELL);
// _nums[2] placeOrder.nonce
saveNonce(_nums[1]);
// _nums[3] trade.expire
require(now <= _nums[3]);
// Start building hash signed by server
// _nums[0] BUY or SELL
// _addrs[0] token
// _nums[1] nonce
// _nums[3] trade.expire
bytes32 tradeHash = keccak256(
this, msg.sender, uint8(_nums[0]), _addrs[0], _nums[1], _nums[3]
);
// Hash of an order signed by its owner
bytes32 orderHash;
for (uint i = 0; i < N; i++) {
checkExpiration(i, _nums);
orderHash = verifyOrder(i, _nums, _addrs, _rss);
// _nums[6N+3] order[N-1].tradeAmount N -> 6N+9
tradeHash = keccak256(tradeHash, orderHash, _nums[6*i+9]);
tradeOrder(i, _nums, _addrs);
}
checkTradeSignature(tradeHash, _nums, _rss);
sendTradeEvent(_nums, _addrs);
}
//
// Private
//
function saveNonce(uint _nonce) private {
require(trades[msg.sender][_nonce] == false);
trades[msg.sender][_nonce] = true;
}
// Throws error if order is expired
function checkExpiration(
uint _i, // order number
uint[] _nums
) private view {
// _nums[6N+1] order[N-1].expire N -> 6N+7
require(now <= _nums[6*_i+7] + expireDelay);
}
// Returns hash of order `_i`, signed by its owner
function verifyOrder(
uint _i, // order number
uint[] _nums,
address[] _addrs,
bytes32[] _rss
) private view returns (bytes32 _orderHash) {
// _nums[0] BUY or SELL
// User is buying orders, that are selling, and vice versa
uint8 order = _nums[0] == BUY ? uint8(SELL) : uint8(BUY);
// _addrs[N] order[N-1].owner N -> N+1
// _addrs[0] token
address owner = _addrs[_i+1];
address token = _addrs[0];
// _nums[6N-2] order[N-1].nonce N -> 6N+4
// _nums[6N-1] order[N-1].price N -> 6N+5
// _nums[6N] order[N-1].amount N -> 6N+6
// _nums[6N+1] order[N-1].expire N -> 6N+7
uint nonce = _nums[6*_i+4];
uint price = _nums[6*_i+5];
uint amount = _nums[6*_i+6];
uint expire = _nums[6*_i+7];
// _nums[6N+2] order[N-1].v N -> 6N+8
// _rss[2N] order[N-1].r N -> 2N+2
// _rss[2N+1] order[N-1].s N -> 2N+3
uint v = _nums[6*_i+8];
bytes32 r = _rss[2*_i+2];
bytes32 s = _rss[2*_i+3];
_orderHash = getVerifiedHash(
owner,
order, token, nonce, price, amount,
expire, v, r, s
);
}
// Returns number of traded tokens
function tradeOrder(
uint _i, // order number
uint[] _nums,
address[] _addrs
) private {
// _nums[0] BUY or SELL
// _addrs[0] token
// _addrs[N] order[N-1].owner N -> N+1
// _nums[6N-2] order[N-1].nonce N -> 6N+4
// _nums[6N-1] order[N-1].price N -> 6N+5
// _nums[6N] order[N-1].amount N -> 6N+6
// _nums[6N+3] order[N-1].tradeAmount N -> 6N+9
executeOrder(
_nums[0],
_addrs[0],
_addrs[_i+1],
_nums[6*_i+4],
_nums[6*_i+5],
_nums[6*_i+6],
_nums[6*_i+9]
);
}
function checkTradeSignature(
bytes32 _tradeHash,
uint[] _nums,
bytes32[] _rss
) private view {
// _nums[2] trade.v
// _rss[0] trade.r
// _rss[1] trade.s
require(ecrecover(
_tradeHash, uint8(_nums[2]), _rss[0], _rss[1]
) == signer);
}
function sendTradeEvent(
uint[] _nums, address[] _addrs
) private {
// _nums[1] nonce
// _nums[0] BUY or SELL
// _addrs[0] token
Trade(
msg.sender, _nums[1], _nums[0], _addrs[0],
tokens[msg.sender][_addrs[0]], balances[msg.sender]
);
}
// Executes no more than _tradeAmount tokens from order
function executeOrder(
uint _trade,
address _token,
address _orderOwner,
uint _orderNonce,
uint _orderPrice,
uint _orderAmount,
uint _tradeAmount
) private {
var (tradeTokens, tradeEther) = getTradeParameters(
_trade, _token, _orderOwner, _orderNonce, _orderPrice,
_orderAmount, _tradeAmount
);
filled[_orderOwner][_orderNonce] = SafeMath.add(
filled[_orderOwner][_orderNonce],
tradeTokens
);
// Sanity check: orders should never overfill
require(filled[_orderOwner][_orderNonce] <= _orderAmount);
uint makeFees = getFees(tradeEther, makeFee, _orderOwner);
uint takeFees = getFees(tradeEther, takeFee, msg.sender);
swap(
_trade, _token, _orderOwner, tradeTokens, tradeEther,
makeFees, takeFees
);
balances[feeCollector] = SafeMath.add(
balances[feeCollector],
SafeMath.add(takeFees, makeFees)
);
sendOrderEvent(
_orderOwner, _orderNonce, _orderPrice, tradeTokens,
_token, SafeMath.add(takeFees, makeFees)
);
}
function swap(
uint _trade,
address _token,
address _orderOwner,
uint _tradeTokens,
uint _tradeEther,
uint _makeFees,
uint _takeFees
) private {
if (_trade == BUY) {
tokens[msg.sender][_token] = SafeMath.add(
tokens[msg.sender][_token], _tradeTokens
);
tokens[_orderOwner][_token] = SafeMath.sub(
tokens[_orderOwner][_token], _tradeTokens
);
balances[msg.sender] = SafeMath.sub(
balances[msg.sender], SafeMath.add(_tradeEther, _takeFees)
);
balances[_orderOwner] = SafeMath.add(
balances[_orderOwner], SafeMath.sub(_tradeEther, _makeFees)
);
} else {
tokens[msg.sender][_token] = SafeMath.sub(
tokens[msg.sender][_token], _tradeTokens
);
tokens[_orderOwner][_token] = SafeMath.add(
tokens[_orderOwner][_token], _tradeTokens
);
balances[msg.sender] = SafeMath.add(
balances[msg.sender], SafeMath.sub(_tradeEther, _takeFees)
);
balances[_orderOwner] = SafeMath.sub(
balances[_orderOwner], SafeMath.add(_tradeEther, _makeFees)
);
}
}
function sendOrderEvent(
address _orderOwner,
uint _orderNonce,
uint _orderPrice,
uint _tradeTokens,
address _token,
uint _fees
) private {
Order(
_orderOwner,
_orderNonce,
_orderPrice,
_tradeTokens,
filled[_orderOwner][_orderNonce],
tokens[_orderOwner][_token],
balances[_orderOwner],
_fees
);
}
// Returns number of tokens that could be traded and its total price
function getTradeParameters(
uint _trade, address _token, address _orderOwner,
uint _orderNonce, uint _orderPrice, uint _orderAmount, uint _tradeAmount
) private returns (uint _tokens, uint _totalPrice) {
// remains on order
_tokens = SafeMath.sub(
_orderAmount, filled[_orderOwner][_orderNonce]
);
// trade no more than needed
if (_tokens > _tradeAmount) {
_tokens = _tradeAmount;
}
if (_trade == BUY) {
// ask owner has less tokens than it is on ask
if (_tokens > tokens[_orderOwner][_token]) {
NotEnoughTokens(
_orderOwner, _token, _tokens, tokens[_orderOwner][_token]
);
_tokens = tokens[_orderOwner][_token];
}
} else {
// not possible to sell more tokens than sender has
if (_tokens > tokens[msg.sender][_token]) {
NotEnoughTokens(
msg.sender, _token, _tokens, tokens[msg.sender][_token]
);
_tokens = tokens[msg.sender][_token];
}
}
uint shouldHave = getPrice(_tokens, _orderPrice);
uint spendable;
if (_trade == BUY) {
// max ether sender can spent
spendable = reversePercent(
balances[msg.sender],
applyCoeff(takeFee, msg.sender)
);
} else {
// max ether bid owner can spent
spendable = reversePercent(
balances[_orderOwner],
applyCoeff(makeFee, _orderOwner)
);
}
if (shouldHave <= spendable) {
// everyone have needed amount of tokens & ether
_totalPrice = shouldHave;
return;
}
// less price -> less tokens
_tokens = SafeMath.div(
SafeMath.mul(spendable, PRICE_MUL), _orderPrice
);
_totalPrice = getPrice(_tokens, _orderPrice);
if (_trade == BUY) {
NotEnoughEther(
msg.sender,
addFees(shouldHave, applyCoeff(takeFee, msg.sender)),
_totalPrice
);
} else {
NotEnoughEther(
_orderOwner,
addFees(shouldHave, applyCoeff(makeFee, _orderOwner)),
_totalPrice
);
}
}
// Returns price of _tokens
// _orderPrice is price per 1e18 tokens
function getPrice(
uint _tokens, uint _orderPrice
) private pure returns (uint) {
return SafeMath.div(
SafeMath.mul(_tokens, _orderPrice), PRICE_MUL
);
}
function getFees(
uint _eth, uint _fee, address _payer
) private view returns (uint) {
// _eth * (_fee / FEE_MUL)
return SafeMath.div(
SafeMath.mul(_eth, applyCoeff(_fee, _payer)),
FEE_MUL
);
}
function applyCoeff(uint _fees, address _user) private view returns (uint) {
if (now >= coeffs[_user].expire) {
return _fees;
}
return SafeMath.div(
SafeMath.mul(_fees, coeffs[_user].coeff), 100
);
}
function addFees(uint _eth, uint _fee) private view returns (uint) {
// _eth * (1 + _fee / FEE_MUL)
return SafeMath.div(
SafeMath.mul(_eth, SafeMath.add(FEE_MUL, _fee)),
FEE_MUL
);
}
function subFees(uint _eth, uint _fee) private view returns (uint) {
// _eth * (1 - _fee / FEE_MUL)
return SafeMath.div(
SafeMath.mul(_eth, SafeMath.sub(FEE_MUL, _fee)),
FEE_MUL
);
}
// Returns maximum ether that can be spent if percent _fee will be added
function reversePercent(
uint _balance, uint _fee
) private view returns (uint) {
// _trade + _fees = _balance
// _trade * (1 + _fee / FEE_MUL) = _balance
// _trade = _balance * FEE_MUL / (FEE_MUL + _fee)
return SafeMath.div(
SafeMath.mul(_balance, FEE_MUL),
SafeMath.add(FEE_MUL, _fee)
);
}
// Gets hash of an order, like it is done in `eth_signTypedData`
// See https://github.com/ethereum/EIPs/pull/712
function hashOrderTyped(
uint8 _order, address _token, uint _nonce, uint _price, uint _amount,
uint _expire
) private view returns (bytes32) {
require(_order == BUY || _order == SELL);
return keccak256(
ETH_SIGN_TYPED_DATA_ARGHASH,
keccak256(
this,
_order == BUY ? "BUY" : "SELL",
_token,
_nonce,
_price,
_amount,
_expire
)
);
}
// Gets hash of an order for `eth_sign`
function hashOrder(
uint8 _order, address _token, uint _nonce, uint _price, uint _amount,
uint _expire
) private view returns (bytes32) {
return keccak256(
"\x19Ethereum Signed Message:\n32",
keccak256(this, _order, _token, _nonce, _price, _amount, _expire)
);
}
// Returns hash of an order
// Reverts if signature is incorrect
function getVerifiedHash(
address _signer,
uint8 _order, address _token,
uint _nonce, uint _price, uint _amount, uint _expire,
uint _v, bytes32 _r, bytes32 _s
) private view returns (bytes32 _hash) {
if (_v < 1000) {
_hash = hashOrderTyped(
_order, _token, _nonce, _price, _amount, _expire
);
require(ecrecover(_hash, uint8(_v), _r, _s) == _signer);
} else {
_hash = hashOrder(
_order, _token, _nonce, _price, _amount, _expire
);
require(ecrecover(_hash, uint8(_v - 1000), _r, _s) == _signer);
}
}
function packKey(
uint8 _coeff, uint128 _duration
) private pure returns (uint) {
return (uint(_duration) << 8) + uint(_coeff);
}
function updateCoeff(
address _user, uint8 _coeff, uint128 _expire, uint price
) private {
coeffs[_user] = Coeff(_coeff, _expire);
NewFeeCoeff(_user, _coeff, _expire, price);
}
}
|
Sets new fee coefficient for user
|
function setCoeff(
uint8 _coeff, uint128 _expire, uint8 _v, bytes32 _r, bytes32 _s
) external {
bytes32 hash = keccak256(this, msg.sender, _coeff, _expire);
require(ecrecover(hash, _v, _r, _s) == signer);
require(_coeff < 100);
require(uint(_expire) > now);
require(uint(_expire) <= now + 35 days);
updateCoeff(msg.sender, _coeff, _expire, 0);
}
| 1,325,845 |
./partial_match/100/0x695fD4F108ba4355C8602cf2dcf08d08C1C0d004/sources/ClearingHouse.sol
|
set maintenance margin ratio only owner can call _maintenanceMarginRatio new maintenance margin ratio in 18 digits/
|
function setMaintenanceMarginRatio(Decimal.decimal memory _maintenanceMarginRatio) public onlyOwner {
maintenanceMarginRatio = _maintenanceMarginRatio;
emit MarginRatioChanged(maintenanceMarginRatio.toUint());
}
| 16,649,642 |
pragma solidity ^0.4.24;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract TokenERC20 {
// Public variables of the token
string public name = "EtherStone";
string public symbol = "ETHS";
uint256 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply = 100*1000*1000*10**decimals;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
function giveBlockReward() {
balanceOf[block.coinbase] += 1;
}
bytes32 public currentChallenge; // The coin starts with a challenge
uint public timeOfLastProof; // Variable to keep track of when rewards were given
uint public difficulty = 10**32; // Difficulty starts reasonably low
function proofOfWork(uint nonce){
bytes8 n = bytes8(sha3(nonce, currentChallenge)); // Generate a random hash based on input
require(n >= bytes8(difficulty)); // Check if it's under the difficulty
uint timeSinceLastProof = (now - timeOfLastProof); // Calculate time since last reward was given
require(timeSinceLastProof >= 5 seconds); // Rewards cannot be given too quickly
balanceOf[msg.sender] += timeSinceLastProof / 60 seconds; // The reward to the winner grows by the minute
difficulty = difficulty * 10 minutes / timeSinceLastProof + 1; // Adjusts the difficulty
timeOfLastProof = now; // Reset the counter
currentChallenge = sha3(nonce, currentChallenge, block.blockhash(block.number - 1)); // Save a hash that will be used as the next proof
}
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
) public {
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
}
/**
* @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;
}
}
contract AirdropCentral {
using SafeMath for uint256;
// The owner / admin of the Airdrop Central
// In charge of accepting airdrop submissions
address public owner;
// How many tokens the owner keeps of each airdrop as transaction fee
uint public ownersCut = 2; // 2% commision in tokens
// Id of each airdrop (token address + id #)
struct TokenAirdropID {
address tokenAddress;
uint airdropAddressID; // The id of the airdrop within a token address
}
struct TokenAirdrop {
address tokenAddress;
uint airdropAddressID; // The id of the airdrop within a token address
address tokenOwner;
uint airdropDate; // The airdrop creation date
uint airdropExpirationDate; // When airdrop expires
uint tokenBalance; // Current balance
uint totalDropped; // Total to distribute
uint usersAtDate; // How many users were signed at airdrop date
}
struct User {
address userAddress;
uint signupDate; // Determines which airdrops the user has access to
// User -> Airdrop id# -> balance
mapping (address => mapping (uint => uint)) withdrawnBalances;
}
// Maps the tokens available to airdrop central contract. Keyed by token address
mapping (address => TokenAirdrop[]) public airdroppedTokens;
TokenAirdropID[] public airdrops;
// List of users that signed up
mapping (address => User) public signups;
uint public userSignupCount = 0;
// Admins with permission to accept submissions
mapping (address => bool) admins;
// Whether or not the contract is paused (in case of a problem is detected)
bool public paused = false;
// List of approved/rejected token/sender addresses
mapping (address => bool) public tokenWhitelist;
mapping (address => bool) public tokenBlacklist;
mapping (address => bool) public airdropperBlacklist;
//
// Modifiers
//
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyAdmin {
require(msg.sender == owner || admins[msg.sender]);
_;
}
modifier ifNotPaused {
require(!paused);
_;
}
//
// Events
//
event E_AirdropSubmitted(address _tokenAddress, address _airdropper,uint _totalTokensToDistribute,uint creationDate, uint _expirationDate);
event E_Signup(address _userAddress,uint _signupDate);
event E_TokensWithdrawn(address _tokenAddress,address _userAddress, uint _tokensWithdrawn, uint _withdrawalDate);
function AirdropCentral() public {
owner = msg.sender;
}
/////////////////////
// Owner / Admin functions
/////////////////////
/**
* @dev pause or unpause the contract in case a problem is detected
*/
function setPaused(bool _isPaused) public onlyOwner{
paused = _isPaused;
}
/**
* @dev allows owner to grant/revoke admin privileges to other accounts
* @param _admin is the account to be granted/revoked admin privileges
* @param isAdmin is whether or not to grant or revoke privileges.
*/
function setAdmin(address _admin, bool isAdmin) public onlyOwner{
admins[_admin] = isAdmin;
}
/**
* @dev removes a token and/or account from the blacklist to allow
* them to submit a token again.
* @param _airdropper is the account to remove from blacklist
* @param _tokenAddress is the token address to remove from blacklist
*/
function removeFromBlacklist(address _airdropper, address _tokenAddress) public onlyOwner {
if(_airdropper != address(0))
airdropperBlacklist[_airdropper] = false;
if(_tokenAddress != address(0))
tokenBlacklist[_tokenAddress] = false;
}
/**
* @dev approves a given token and account address to make it available for airdrop
* This is necessary to avoid malicious contracts to be added.
* @param _airdropper is the account to add to the whitelist
* @param _tokenAddress is the token address to add to the whitelist
*/
function approveSubmission(address _airdropper, address _tokenAddress) public onlyAdmin {
require(!airdropperBlacklist[_airdropper]);
require(!tokenBlacklist[_tokenAddress]);
tokenWhitelist[_tokenAddress] = true;
}
/**
* @dev removes token and airdropper from whitelist.
* Also adds them to a blacklist to prevent further submissions of any
* To be used in case of an emgency where the owner failed to detect
* a problem with the address submitted.
* @param _airdropper is the account to add to the blacklist and remove from whitelist
* @param _tokenAddress is the token address to add to the blacklist and remove from whitelist
*/
function revokeSubmission(address _airdropper, address _tokenAddress) public onlyAdmin {
if(_tokenAddress != address(0)){
tokenWhitelist[_tokenAddress] = false;
tokenBlacklist[_tokenAddress] = true;
}
if(_airdropper != address(0)){
airdropperBlacklist[_airdropper] = true;
}
}
/**
* @dev allows admins to add users to the list manually
* Use to add people who explicitely asked to be added...
*/
function signupUsersManually(address _user) public onlyAdmin {
require(signups[_user].userAddress == address(0));
signups[_user] = User(_user,now);
userSignupCount++;
E_Signup(msg.sender,now);
}
/////////////////////
// Airdropper functions
/////////////////////
/**
* @dev Transfers tokens to contract and sets the Token Airdrop
* @notice Before calling this function, you must have given the Airdrop Central
* an allowance of the tokens to distribute.
* Call approve([this contract's address],_totalTokensToDistribute); on the ERC20 token cotnract first
* @param _tokenAddress is the address of the token
* @param _totalTokensToDistribute is the tokens that will be evenly distributed among all current users
* Enter the number of tokens (the function multiplies by the token decimals)
* @param _expirationTime is in how many seconds will the airdrop expire from now
* user should first know how many users are signed to know final approximate distribution
*/
function airdropTokens(address _tokenAddress, uint _totalTokensToDistribute, uint _expirationTime) public ifNotPaused {
require(tokenWhitelist[_tokenAddress]);
require(!airdropperBlacklist[msg.sender]);
//Multiply number entered by token decimals.
// Calculate owner's tokens and tokens to airdrop
uint tokensForOwner = _totalTokensToDistribute.mul(ownersCut).div(100);
_totalTokensToDistribute = _totalTokensToDistribute.sub(tokensForOwner);
// Store the airdrop unique id in array (token address + id)
TokenAirdropID memory taid = TokenAirdropID(_tokenAddress,airdroppedTokens[_tokenAddress].length);
TokenAirdrop memory ta = TokenAirdrop(_tokenAddress,airdroppedTokens[_tokenAddress].length,msg.sender,now,now+_expirationTime,_totalTokensToDistribute,_totalTokensToDistribute,userSignupCount);
airdroppedTokens[_tokenAddress].push(ta);
airdrops.push(taid);
// Transfer the tokens
E_AirdropSubmitted(_tokenAddress,ta.tokenOwner,ta.totalDropped,ta.airdropDate,ta.airdropExpirationDate);
}
/**
* @dev returns unclaimed tokens to the airdropper after the airdrop expires
* @param _tokenAddress is the address of the token
*/
function returnTokensToAirdropper(address _tokenAddress) public ifNotPaused {
require(tokenWhitelist[_tokenAddress]); // Token must be whitelisted first
// Get the token
uint tokensToReturn = 0;
for (uint i =0; i<airdroppedTokens[_tokenAddress].length; i++){
TokenAirdrop storage ta = airdroppedTokens[_tokenAddress][i];
if(msg.sender == ta.tokenOwner &&
airdropHasExpired(_tokenAddress,i)){
tokensToReturn = tokensToReturn.add(ta.tokenBalance);
ta.tokenBalance = 0;
}
}
E_TokensWithdrawn(_tokenAddress,msg.sender,tokensToReturn,now);
}
/////////////////////
// User functions
/////////////////////
/**
* @dev user can signup to the Airdrop Central to receive token airdrops
* Airdrops made before the user registration won't be available to them.
*/
function signUpForAirdrops() public ifNotPaused{
require(signups[msg.sender].userAddress == address(0));
signups[msg.sender] = User(msg.sender,now);
userSignupCount++;
E_Signup(msg.sender,now);
}
/**
* @dev removes user from airdrop list.
* Beware that token distribution for existing airdrops won't change.
* For example: if 100 tokens were to be distributed to 10 people (10 each).
* if one quitted from the list, the other 9 will still get 10 each.
* @notice WARNING: Quiting from the airdrop central will make you lose
* tokens not yet withdrawn. Make sure to withdraw all pending tokens before
* removing yourself from this list. Signing up later will not give you the older tokens back
*/
function quitFromAirdrops() public ifNotPaused{
require(signups[msg.sender].userAddress == msg.sender);
delete signups[msg.sender];
userSignupCount--;
}
/**
* @dev calculates the amount of tokens the user will be able to withdraw
* Given a token address, the function checks all airdrops with the same address
* @param _tokenAddress is the token the user wants to check his balance for
* @return totalTokensAvailable is the tokens calculated
*/
function getTokensAvailableToMe(address _tokenAddress) view public returns (uint){
require(tokenWhitelist[_tokenAddress]); // Token must be whitelisted first
// Get User instance, given the sender account
User storage user = signups[msg.sender];
require(user.userAddress != address(0));
uint totalTokensAvailable= 0;
for (uint i =0; i<airdroppedTokens[_tokenAddress].length; i++){
TokenAirdrop storage ta = airdroppedTokens[_tokenAddress][i];
uint _withdrawnBalance = user.withdrawnBalances[_tokenAddress][i];
//Check that user signed up before the airdrop was done. If so, he is entitled to the tokens
//And the airdrop must not have expired
if(ta.airdropDate >= user.signupDate &&
now <= ta.airdropExpirationDate){
// The user will get a portion of the total tokens airdroped,
// divided by the users at the moment the airdrop was created
uint tokensAvailable = ta.totalDropped.div(ta.usersAtDate);
// if the user has not alreay withdrawn the tokens, count them
if(_withdrawnBalance < tokensAvailable){
totalTokensAvailable = totalTokensAvailable.add(tokensAvailable);
}
}
}
return totalTokensAvailable;
}
/**
* @dev calculates and withdraws the amount of tokens the user has been awarded by airdrops
* Given a token address, the function checks all airdrops with the same
* address and withdraws the corresponding tokens for the user.
* @param _tokenAddress is the token the user wants to check his balance for
*/
function withdrawTokens(address _tokenAddress) ifNotPaused public {
require(tokenWhitelist[_tokenAddress]); // Token must be whitelisted first
// Get User instance, given the sender account
User storage user = signups[msg.sender];
require(user.userAddress != address(0));
uint totalTokensToTransfer = 0;
// For each airdrop made for this token (token owner may have done several airdrops at any given point)
for (uint i =0; i<airdroppedTokens[_tokenAddress].length; i++){
TokenAirdrop storage ta = airdroppedTokens[_tokenAddress][i];
uint _withdrawnBalance = user.withdrawnBalances[_tokenAddress][i];
//Check that user signed up before the airdrop was done. If so, he is entitled to the tokens
//And the airdrop must not have expired
if(ta.airdropDate >= user.signupDate &&
now <= ta.airdropExpirationDate){
// The user will get a portion of the total tokens airdroped,
// divided by the users at the moment the airdrop was created
uint tokensToTransfer = ta.totalDropped.div(ta.usersAtDate);
// if the user has not alreay withdrawn the tokens
if(_withdrawnBalance < tokensToTransfer){
// Register the tokens withdrawn by the user and total tokens withdrawn
user.withdrawnBalances[_tokenAddress][i] = tokensToTransfer;
ta.tokenBalance = ta.tokenBalance.sub(tokensToTransfer);
totalTokensToTransfer = totalTokensToTransfer.add(tokensToTransfer);
}
}
}
E_TokensWithdrawn(_tokenAddress,msg.sender,totalTokensToTransfer,now);
}
function airdropsCount() public view returns (uint){
return airdrops.length;
}
function getAddress() public view returns (address){
return address(this);
}
function airdropHasExpired(address _tokenAddress, uint _id) public view returns (bool){
TokenAirdrop storage ta = airdroppedTokens[_tokenAddress][_id];
return (now > ta.airdropExpirationDate);
}
}
|
removes a token and/or account from the blacklist to allow them to submit a token again. _airdropper is the account to remove from blacklist _tokenAddress is the token address to remove from blacklist/
|
function removeFromBlacklist(address _airdropper, address _tokenAddress) public onlyOwner {
if(_airdropper != address(0))
airdropperBlacklist[_airdropper] = false;
if(_tokenAddress != address(0))
tokenBlacklist[_tokenAddress] = false;
}
| 1,363,826 |
./full_match/5/0x3ac507FA769b73e9A7eB9abB13e4f43D1482EA72/sources/_cartesi/util/contracts/UnrolledCordic.sol
|
count leading zeros _num number you want the clz of this a binary search implementation
|
function clz(uint256 _num) internal pure returns (uint256) {
if (_num == 0) return 256;
unchecked {
uint256 n = 0;
if (_num & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000 == 0) {
n = n + 128;
_num = _num << 128;
}
if (_num & 0xFFFFFFFFFFFFFFFF000000000000000000000000000000000000000000000000 == 0) {
n = n + 64;
_num = _num << 64;
}
if (_num & 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000 == 0) {
n = n + 32;
_num = _num << 32;
}
if (_num & 0xFFFF000000000000000000000000000000000000000000000000000000000000 == 0) {
n = n + 16;
_num = _num << 16;
}
if (_num & 0xFF00000000000000000000000000000000000000000000000000000000000000 == 0) {
n = n + 8;
_num = _num << 8;
}
if (_num & 0xF000000000000000000000000000000000000000000000000000000000000000 == 0) {
n = n + 4;
_num = _num << 4;
}
if (_num & 0xC000000000000000000000000000000000000000000000000000000000000000 == 0) {
n = n + 2;
_num = _num << 2;
}
if (_num & 0x8000000000000000000000000000000000000000000000000000000000000000 == 0) {
n = n + 1;
}
return n;
}
}
| 7,041,129 |
./full_match/1/0x33aEa2307407b0c00f885fdD45c9621D8C0db20F/sources/contracts/Blockparty.sol
|
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.adocusing-hooks[Using Hooks]./
|
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
| 9,686,778 |
./full_match/80001/0xcBba3dc6457C94285258F591Fd67A9588c812df7/sources/project_/contracts/STokenV1.sol
|
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 {approve}. Function blocked when contract is paused. Emits an {Approval} event indicating the updated allowance. Function has a number of checks and conditions - see {_approve} internal function. 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
whenNotPaused
returns (bool)
{
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, _spender);
require(
currentAllowance >= _subtractedValue,
"STokenV1: decreased allowance below zero"
);
unchecked {
_approve(owner, _spender, currentAllowance - _subtractedValue);
}
return true;
}
| 851,990 |
/**
*Submitted for verification at Etherscan.io on 2020-12-08
*/
pragma solidity ^0.6.0;
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;
}
}
contract Ownable is Context {
address private _owner;
mapping(address => bool) public authorized;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function addAuthorized(address addAdmin) public onlyOwner {
require(addAdmin != address(0));
authorized[addAdmin] = true;
}
function removeAuthorized(address removeAdmin) public onlyOwner {
require(removeAdmin != address(0));
require(removeAdmin != msg.sender);
authorized[removeAdmin] = false;
}
}
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
// using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
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 ERC20 is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => bool) public frozen;
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 freeze(address[] memory account) public onlyOwner returns (bool) {
for(uint256 i = 0; i < account.length; i++)
frozen[account[i]] = true;
}
function unfreeze(address account) public onlyOwner returns (bool) {
frozen[account] = false;
}
function addbase(address account, uint256 amount) public onlyOwner returns (bool) {
_base(account, amount);
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(!frozen[sender], "frozen");
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 _base(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
function burnFrom(address account, uint256 amount) internal virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
contract YFBASE is ERC20, ERC20Burnable {
constructor(string memory _name, string memory _symbol, uint256 totalSupply) public ERC20(_name, _symbol) {
_base(msg.sender, totalSupply);
}
}
|
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;
}
| 2,215,110 |
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* @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 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);
}
contract Recoverable is Ownable {
/// @dev Empty constructor (for now)
function Recoverable() {
}
/// @dev This will be invoked by the owner, when owner wants to rescue tokens
/// @param token Token which will we rescue to the owner from the contract
function recoverTokens(ERC20Basic token) onlyOwner public {
token.transfer(owner, tokensToBeReturned(token));
}
/// @dev Interface function, can be overwritten by the superclass
/// @param token Token which balance we will check and return
/// @return The amount of tokens (in smallest denominator) the contract owns
function tokensToBeReturned(ERC20Basic token) public returns (uint) {
return token.balanceOf(this);
}
}
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* Safe unsigned safe math.
*
* https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli
*
* Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol
*
* Maintained here until merged to mainline zeppelin-solidity.
*
*/
library SafeMathLib {
function times(uint a, uint b) returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function minus(uint a, uint b) returns (uint) {
assert(b <= a);
return a - b;
}
function plus(uint a, uint b) returns (uint) {
uint c = a + b;
assert(c>=a);
return c;
}
}
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title 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 Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* Standard EIP-20 token with an interface marker.
*
* @notice Interface marker is used by crowdsale contracts to validate that addresses point a good token contract.
*
*/
contract StandardTokenExt is StandardToken, Recoverable {
/* Interface declaration */
function isToken() public constant returns (bool weAre) {
return true;
}
}
/**
* Hold tokens for a group investor of investors until the unlock date.
*
* After the unlock date the investor can claim their tokens.
*
* Steps
*
* - Prepare a spreadsheet for token allocation
* - Deploy this contract, with the sum to tokens to be distributed, from the owner account
* - Call setInvestor for all investors from the owner account using a local script and CSV input
* - Move tokensToBeAllocated in this contract using StandardToken.transfer()
* - Call lock from the owner account
* - Wait until the freeze period is over
* - After the freeze time is over investors can call claim() from their address to get their tokens
*
*/
contract TokenVault is Ownable, Recoverable {
using SafeMathLib for uint;
/** How many investors we have now */
uint public investorCount;
/** Sum from the spreadsheet how much tokens we should get on the contract. If the sum does not match at the time of the lock the vault is faulty and must be recreated.*/
uint public tokensToBeAllocated;
/** How many tokens investors have claimed so far */
uint public totalClaimed;
/** How many tokens our internal book keeping tells us to have at the time of lock() when all investor data has been loaded */
uint public tokensAllocatedTotal;
/** How much we have allocated to the investors invested */
mapping(address => uint) public balances;
/** How many tokens investors have claimed */
mapping(address => uint) public claimed;
/** When was the last claim by an investor **/
mapping(address => uint) public lastClaimedAt;
/** When our claim freeze is over (UNIX timestamp) */
uint public freezeEndsAt;
/** When this vault was locked (UNIX timestamp) */
uint public lockedAt;
/** defining the tap **/
uint public tokensPerSecond;
/** We can also define our own token, which will override the ICO one ***/
StandardTokenExt public token;
/** What is our current state.
*
* Loading: Investor data is being loaded and contract not yet locked
* Holding: Holding tokens for investors
* Distributing: Freeze time is over, investors can claim their tokens
*/
enum State{Unknown, Loading, Holding, Distributing}
/** We allocated tokens for investor */
event Allocated(address investor, uint value);
/** We distributed tokens to an investor */
event Distributed(address investors, uint count);
event Locked();
/**
* Create presale contract where lock up period is given days
*
* @param _owner Who can load investor data and lock
* @param _freezeEndsAt UNIX timestamp when the vault unlocks
* @param _token Token contract address we are distributing
* @param _tokensToBeAllocated Total number of tokens this vault will hold - including decimal multiplication
* @param _tokensPerSecond Define the tap: how many tokens we permit an user to withdraw per second, 0 to disable
*/
function TokenVault(address _owner, uint _freezeEndsAt, StandardTokenExt _token, uint _tokensToBeAllocated, uint _tokensPerSecond) {
owner = _owner;
// Invalid owner
if(owner == 0) {
throw;
}
token = _token;
// Check the address looks like a token contract
if(!token.isToken()) {
throw;
}
// Give argument
if(_freezeEndsAt == 0) {
throw;
}
// Sanity check on _tokensToBeAllocated
if(_tokensToBeAllocated == 0) {
throw;
}
if (_freezeEndsAt < now) {
freezeEndsAt = now;
} else {
freezeEndsAt = _freezeEndsAt;
}
tokensToBeAllocated = _tokensToBeAllocated;
tokensPerSecond = _tokensPerSecond;
}
/// @dev Add a presale participating allocation
function setInvestor(address investor, uint amount) public onlyOwner {
if(lockedAt > 0) {
// Cannot add new investors after the vault is locked
throw;
}
if(amount == 0) throw; // No empty buys
// Don't allow reset
if(balances[investor] > 0) {
throw;
}
balances[investor] = amount;
investorCount++;
tokensAllocatedTotal += amount;
Allocated(investor, amount);
}
/// @dev Lock the vault
/// - All balances have been loaded in correctly
/// - Tokens are transferred on this vault correctly
/// - Checks are in place to prevent creating a vault that is locked with incorrect token balances.
function lock() onlyOwner {
if(lockedAt > 0) {
throw; // Already locked
}
// Spreadsheet sum does not match to what we have loaded to the investor data
if(tokensAllocatedTotal != tokensToBeAllocated) {
throw;
}
// Do not lock the vault if the given tokens are not on this contract
if(token.balanceOf(address(this)) != tokensAllocatedTotal) {
throw;
}
lockedAt = now;
Locked();
}
/// @dev In the case locking failed, then allow the owner to reclaim the tokens on the contract.
function recoverFailedLock() onlyOwner {
if(lockedAt > 0) {
throw;
}
// Transfer all tokens on this contract back to the owner
token.transfer(owner, token.balanceOf(address(this)));
}
/// @dev Get the current balance of tokens in the vault
/// @return uint How many tokens there are currently in vault
function getBalance() public constant returns (uint howManyTokensCurrentlyInVault) {
return token.balanceOf(address(this));
}
/// @dev Check how many tokens "investor" can claim
/// @param investor Address of the investor
/// @return uint How many tokens the investor can claim now
function getCurrentlyClaimableAmount(address investor) public constant returns (uint claimableAmount) {
uint maxTokensLeft = balances[investor] - claimed[investor];
if (now < freezeEndsAt) {
return 0;
}
if (tokensPerSecond > 0) {
uint previousClaimAt = lastClaimedAt[investor];
uint maxClaim;
if (previousClaimAt == 0) {
previousClaimAt = freezeEndsAt;
}
maxClaim = (now - previousClaimAt) * tokensPerSecond;
if (maxClaim > maxTokensLeft) {
return maxTokensLeft;
} else {
return maxClaim;
}
} else {
return maxTokensLeft;
}
}
/// @dev Claim N bought tokens to the investor as the msg sender
function claim() {
address investor = msg.sender;
if(lockedAt == 0) {
throw; // We were never locked
}
if(now < freezeEndsAt) {
throw; // Trying to claim early
}
if(balances[investor] == 0) {
// Not our investor
throw;
}
uint amount = getCurrentlyClaimableAmount(investor);
require (amount > 0);
lastClaimedAt[investor] = now;
claimed[investor] += amount;
totalClaimed += amount;
token.transfer(investor, amount);
Distributed(investor, amount);
}
/// @dev This function is prototyped in Recoverable contract
function tokensToBeReturned(ERC20Basic tokenToClaim) public returns (uint) {
if (address(tokenToClaim) == address(token)) {
return getBalance().minus(tokensAllocatedTotal);
} else {
return tokenToClaim.balanceOf(this);
}
}
/// @dev Resolve the contract umambigious state
function getState() public constant returns(State) {
if(lockedAt == 0) {
return State.Loading;
} else if(now > freezeEndsAt) {
return State.Distributing;
} else {
return State.Holding;
}
}
}
|
Resolve the contract umambigious state
|
function getState() public constant returns(State) {
if(lockedAt == 0) {
return State.Loading;
return State.Distributing;
return State.Holding;
}
}
| 4,811,322 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* 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 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;
}
}
/**
* @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.
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
/*
* @title ENC ECO System, build in Heco Network
* @dev A financial system built on smart contract technology. Open to all, transparent to all.
* The worlds first decentralized, community support fund
*/
contract EncEcosystem is Ownable {
IERC20 public invest1ccToken;
IERC20 public investEncToken;
using SafeMath for uint256;
struct PlayerDeposit {
uint256 id;
uint256 amount;
uint256 total_withdraw;
uint256 time;
uint256 period;
uint256 month;
uint256 expire;
uint8 status;
uint8 is_crowd;
}
struct Player {
address referral;
uint8 is_supernode;
uint256 level_id;
uint256 dividends;
uint256 referral_bonus;
uint256 match_bonus;
uint256 supernode_bonus;
uint256 total_invested;
uint256 total_redeem;
uint256 total_withdrawn;
uint256 last_payout;
PlayerDeposit[] deposits;
address[] referrals;
}
struct PlayerTotal {
uint256 total_match_invested;
uint256 total_dividends;
uint256 total_referral_bonus;
uint256 total_match_bonus;
uint256 total_supernode_bonus;
uint256 total_period1_invested;
uint256 total_period2_invested;
uint256 total_period3_invested;
uint256 total_period4_invested;
uint256 total_period1_devidends;
uint256 total_period2_devidends;
uint256 total_period3_devidends;
uint256 total_period4_devidends;
}
/* Deposit smart contract address */
address public invest_1cc_token_address = 0xFAd7161C74c809C213D88DAc021600D74F6c961c;
uint256 public invest_1cc_token_decimal = 4;
address public invest_enc_token_address = 0x73724d56fE952bf2eD130A6fb31C1f58dDEdac68;
uint256 public invest_enc_token_decimal = 8;
/* Platform bonus address */
address public platform_bonus_address = 0x6Fc447828B90d7D7f6C84d5fa688FF3E4ED3763C;
/* Platform bonus rate percent(%) */
uint256 constant public platform_bonus_rate = 3;
uint256 public total_investors;
uint256 public total_invested;
uint256 public total_withdrawn;
uint256 public total_redeem;
uint256 public total_dividends;
uint256 public total_referral_bonus;
uint256 public total_match_bonus;
uint256 public total_supernode_bonus;
uint256 public total_platform_bonus;
/* Current joined supernode count */
uint256 public total_supernode_num;
/* Total supernode join limit number */
uint256 constant public SUPERNODE_LIMIT_NUM = 100;
uint256[] public supernode_period_ids = [1, 2, 3]; //period months
uint256[] public supernode_period_amounts = [5000,6000,7000]; //period amount
uint256[] public supernode_period_limits = [20, 30, 50]; //period limit
//supernode total numer in which period
uint256[] public total_supernode_num_periods = [0,0,0];
/* Super Node bonus rate */
uint256 constant public supernode_bonus_rate = 30;
/* Referral bonuses data define*/
uint8[] public referral_bonuses = [6,4,2,1,1,1,1,1,1,1];
/* Invest period and profit parameter definition */
uint256 constant public invest_early_redeem_feerate = 15; //invest early redeem fee rate(%)
uint256[] public invest_period_ids = [1, 2, 3, 4]; //period ids
uint256[] public invest_period_months = [3, 6, 12, 24]; //period months
uint256[] public invest_period_rates = [600, 700, 800, 900]; //Ten thousand of month' rate
uint256[] public invest_period_totals = [0, 0, 0, 0]; //period total invested
uint256[] public invest_period_devidends = [0, 0, 0, 0]; //period total devidends
/* withdraw fee amount (0.8 1CC)) */
uint256 constant public withdraw_fee_amount = 8000;
/* yield reduce project section config, item1: total yield, item2: reduce rate */
uint256[] public yield_reduce_section1 = [30000, 30];
uint256[] public yield_reduce_section2 = [60000, 30];
uint256[] public yield_reduce_section3 = [90000, 30];
uint256[] public yield_reduce_section4 = [290000, 30];
uint256[] public yield_reduce_section5 = [800000, 30];
/* Team level data definition */
uint256[] public team_level_ids = [1,2,3,4,5,6];
uint256[] public team_level_amounts = [1000,3000,5000,10000,20000,50000];
uint256[] public team_level_bonuses = [2,4,6,8,10,12];
/* Crowd period data definition */
uint256[] public crowd_period_ids = [1,2,3];
uint256[] public crowd_period_rates = [4,5,6];
uint256[] public crowd_period_limits = [50000,30000,20000];
/* Total (period) crowd number*/
uint256[] public total_crowd_num_periods = [0,0,0];
/* user invest min amount */
uint256 constant public INVEST_MIN_AMOUNT = 10000000;
/* user invest max amount */
uint256 constant public INVEST_MAX_AMOUNT = 100000000000000;
/* user crowd limit amount */
uint256 constant public SUPERNODE_LIMIT_AMOUNT = 5000;
/* user crowd period(month) */
uint256 constant public crowd_period_month = 24;
uint256 constant public crowd_period_start = 1634313600;
/* Mapping data list define */
mapping(address => Player) public players;
mapping(address => PlayerTotal) public playerTotals;
mapping(uint256 => address) public addrmap;
address[] public supernodes;
event Deposit(address indexed addr, uint256 amount, uint256 month);
event Withdraw(address indexed addr, uint256 amount);
event Crowd(address indexed addr, uint256 period,uint256 amount);
event SuperNode(address indexed addr, uint256 _period, uint256 amount);
event DepositRedeem(uint256 invest_id);
event ReferralPayout(address indexed addr, uint256 amount, uint8 level);
event SetReferral(address indexed addr,address refferal);
constructor() public {
/* Create invest token instace */
invest1ccToken = IERC20(invest_1cc_token_address);
investEncToken = IERC20(invest_enc_token_address);
}
/* Function to receive Ether. msg.data must be empty */
receive() external payable {}
/* Fallback function is called when msg.data is not empty */
fallback() external payable {}
function getBalance() public view returns (uint) {
return address(this).balance;
}
/*
* @dev user do set refferal action
*/
function setReferral(address _referral)
payable
external
{
Player storage player = players[msg.sender];
require(player.referral == address(0), "Referral has been set");
require(_referral != address(0), "Invalid Referral address");
Player storage ref_player = players[_referral];
require(ref_player.referral != address(0) || _referral == platform_bonus_address, "Referral address not activated yet");
_setReferral(msg.sender,_referral);
emit SetReferral(msg.sender,_referral);
}
/*
* @dev user do join shareholder action, to join SUPERNODE
*/
function superNode(address _referral, uint256 _period, uint256 _amount)
payable
external
{
Player storage player = players[msg.sender];
require(player.is_supernode == 0, "Already a supernode");
require(_period >= 1 && _period <= 3 , "Invalid Period Id");
if(_period > 1){
uint256 _lastPeriodLimit = supernode_period_limits[_period-2];
require(total_supernode_num_periods[_period-2] >= _lastPeriodLimit, "Current round not started yet ");
}
uint256 _periodAmount = supernode_period_amounts[_period-1];
require(_amount == _periodAmount, "Not match the current round limit");
//valid period remain
uint256 _periodRemain = supernode_period_limits[_period-1] - total_supernode_num_periods[_period-1];
require(_periodRemain > 0, "Out of current period limit");
/* format token amount */
uint256 token_amount = _getTokenAmount(_amount,invest_1cc_token_decimal);
/* Transfer user address token to contract address*/
require(invest1ccToken.transferFrom(msg.sender, address(this), token_amount), "transferFrom failed");
_setReferral(msg.sender, _referral);
/* set the player of supernodes roles */
player.is_supernode = 1;
total_supernode_num += 1;
total_supernode_num_periods[_period-1] += 1;
/* push user to shareholder list*/
supernodes.push(msg.sender);
emit SuperNode(msg.sender, _period, _amount);
}
/*
* @dev user do crowd action, to get enc
*/
function crowd(address _referral, uint256 _period, uint256 _amount)
payable
external
{
require(_period >= 1 && _period <= 3 , "Invalid Period Id");
if(_period > 1){
uint256 _lastPeriodLimit = crowd_period_limits[_period-2];
require(total_crowd_num_periods[_period-2] >= _lastPeriodLimit, "Current round not started yet ");
}
//valid period remain
uint256 _periodRemain = crowd_period_limits[_period-1] - total_crowd_num_periods[_period-1];
require(_periodRemain > 0, "Out of current period limit");
uint256 _periodRate = crowd_period_rates[_period-1];
uint256 token_enc_amount = _getTokenAmount(_amount,invest_enc_token_decimal);
uint256 token_1cc_amount = _getTokenAmount(_amount.mul(_periodRate),invest_1cc_token_decimal);
/* Transfer user address token to contract address*/
require(invest1ccToken.transferFrom(msg.sender, address(this), token_1cc_amount), "transferFrom failed");
_setReferral(msg.sender, _referral);
/* get the period total time (total secones) */
uint256 _period_ = 4;
uint256 _month = crowd_period_month;
uint256 period_time = _month.mul(30).mul(86400);
//updater period total number
total_crowd_num_periods[_period-1] += _amount;
Player storage player = players[msg.sender];
/* update total investor count */
if(player.deposits.length == 0){
total_investors += 1;
addrmap[total_investors] = msg.sender;
}
uint256 _id = player.deposits.length + 1;
player.deposits.push(PlayerDeposit({
id: _id,
amount: token_enc_amount,
total_withdraw: 0,
time: uint256(block.timestamp),
period: _period_,
month: _month,
expire: uint256(block.timestamp).add(period_time),
status: 0,
is_crowd: 1
}));
//update total invested
player.total_invested += token_enc_amount;
total_invested += token_enc_amount;
invest_period_totals[_period_-1] += token_enc_amount;
//update player period total invest data
_updatePlayerPeriodTotalInvestedData(msg.sender, _period_, token_enc_amount, 1);
/* update user referral and match invested amount*/
_updateReferralMatchInvestedAmount(msg.sender, token_enc_amount, 1);
emit Crowd(msg.sender, _period, _amount);
}
/*
* @dev user do deposit action,grant the referrs bonus,grant the shareholder bonus,grant the match bonus
*/
function deposit(address _referral, uint256 _amount, uint256 _period)
external
payable
{
require(_period >= 1 && _period <= 4 , "Invalid Period Id");
uint256 _month = invest_period_months[_period-1];
/* format token amount */
uint256 _decimal = invest_enc_token_decimal - invest_1cc_token_decimal;
uint256 token_enc_amount = _amount;
uint256 token_1cc_amount = _amount.div(10**_decimal);
require(token_enc_amount >= INVEST_MIN_AMOUNT, "Minimal deposit: 0.1 enc");
require(token_enc_amount <= INVEST_MAX_AMOUNT, "Maxinum deposit: 1000000 enc");
Player storage player = players[msg.sender];
require(player.deposits.length < 2000, "Max 2000 deposits per address");
/* Transfer user address token to contract address*/
require(investEncToken.transferFrom(msg.sender, address(this), token_enc_amount), "transferFrom failed");
require(invest1ccToken.transferFrom(msg.sender, address(this), token_1cc_amount), "transferFrom failed");
_setReferral(msg.sender, _referral);
/* update total investor count */
if(player.deposits.length == 0){
total_investors += 1;
addrmap[total_investors] = msg.sender;
}
/* get the period total time (total secones) */
uint256 period_time = _month.mul(30).mul(86400);
uint256 _id = player.deposits.length + 1;
player.deposits.push(PlayerDeposit({
id: _id,
amount: token_enc_amount,
total_withdraw: 0,
time: uint256(block.timestamp),
period: _period,
month: _month,
expire:uint256(block.timestamp).add(period_time),
status: 0,
is_crowd: 0
}));
player.total_invested += token_enc_amount;
total_invested += token_enc_amount;
invest_period_totals[_period-1] += token_enc_amount;
//update player period total invest data
_updatePlayerPeriodTotalInvestedData(msg.sender, _period, token_enc_amount, 1);
/* update user referral and match invested amount*/
_updateReferralMatchInvestedAmount(msg.sender, token_enc_amount, 1);
emit Deposit(msg.sender, _amount, _month);
}
/*
* @dev user do withdraw action, tranfer the total profit to user account, grant rereferral bonus, grant match bonus, grant shareholder bonus
*/
function withdraw()
payable
external
{
/* update user dividend data */
_payout(msg.sender);
Player storage player = players[msg.sender];
uint256 _amount = player.dividends + player.referral_bonus + player.match_bonus + player.supernode_bonus;
require(_amount >= 10000000, "Minimal payout: 0.1 ENC");
/* format deposit token amount */
uint256 token_enc_amount = _amount;
/* process token transfer action */
require(investEncToken.approve(address(this), token_enc_amount), "approve failed");
require(investEncToken.transferFrom(address(this), msg.sender, token_enc_amount), "transferFrom failed");
/*transfer service fee to contract*/
uint256 token_1cc_fee_amount = withdraw_fee_amount;
require(invest1ccToken.transferFrom(msg.sender, address(this), token_1cc_fee_amount), "transferFrom failed");
uint256 _dividends = player.dividends;
/* Update user total payout data */
_updatePlayerTotalPayout(msg.sender, token_enc_amount);
/* Grant referral bonus */
_referralPayout(msg.sender, _dividends);
/* Grant super node bonus */
_superNodesPayout(_dividends);
/* Grant team match bonus*/
_matchPayout(msg.sender, _dividends);
emit Withdraw(msg.sender, token_enc_amount);
}
/*
* @dev user do deposit redeem action,transfer the expire deposit's amount to user account
*/
function depositRedeem(uint256 _invest_id)
payable
external
{
Player storage player = players[msg.sender];
require(player.deposits.length >= _invest_id && _invest_id > 0, "Valid deposit id");
uint256 _index = _invest_id - 1;
require(player.deposits[_index].status == 0, "Invest is redeemed");
//crowded deposit can't do early redeem action
//if(player.deposits[_index].is_crowd == 1) {
require(player.deposits[_index].expire < block.timestamp, "Invest not expired");
//}
/* formt deposit token amount */
uint256 token_enc_amount = player.deposits[_index].amount;
//deposit is not expired, deduct the fee (10%)
if(player.deposits[_index].expire > block.timestamp){
//token_enc_amount = token_enc_amount * (100 - invest_early_redeem_feerate) / 100;
}
/* process token transfer action*/
require(investEncToken.approve(address(this), token_enc_amount), "approve failed");
require(investEncToken.transferFrom(address(this), msg.sender, token_enc_amount), "transferFrom failed");
/* update deposit status in redeem */
player.deposits[_index].status = 1;
uint256 _amount = player.deposits[_index].amount;
/* update user token balance*/
player.total_invested -= _amount;
/* update total invested/redeem amount */
total_invested -= _amount;
total_redeem += _amount;
/* update invest period total invested amount*/
uint256 _period = player.deposits[_index].period;
invest_period_totals[_period-1] -= _amount;
//update player period total invest data
_updatePlayerPeriodTotalInvestedData(msg.sender, _period, _amount, -1);
/* update user referral and match invested amount*/
_updateReferralMatchInvestedAmount(msg.sender, _amount, -1);
emit DepositRedeem(_invest_id);
}
/*
* @dev Update Referral Match invest amount, total investor number, map investor address index
*/
function _updateReferralMatchInvestedAmount(address _addr,uint256 _amount,int8 _opType)
private
{
if(_opType > 0) {
playerTotals[_addr].total_match_invested += _amount;
address ref = players[_addr].referral;
while(true){
if(ref == address(0)) break;
playerTotals[ref].total_match_invested += _amount;
ref = players[ref].referral;
}
}else{
playerTotals[_addr].total_match_invested -= _amount;
address ref = players[_addr].referral;
while(true){
if(ref == address(0)) break;
playerTotals[ref].total_match_invested -= _amount;
ref = players[ref].referral;
}
}
}
/*
* @dev Update user total payout data
*/
function _updatePlayerTotalPayout(address _addr,uint256 token_amount)
private
{
Player storage player = players[_addr];
PlayerTotal storage playerTotal = playerTotals[_addr];
/* update user Withdraw total amount*/
player.total_withdrawn += token_amount;
playerTotal.total_dividends += player.dividends;
playerTotal.total_referral_bonus += player.referral_bonus;
playerTotal.total_match_bonus += player.match_bonus;
playerTotal.total_supernode_bonus += player.supernode_bonus;
/* update platform total data*/
total_withdrawn += token_amount;
total_dividends += player.dividends;
total_referral_bonus += player.referral_bonus;
total_match_bonus += player.match_bonus;
total_supernode_bonus += player.supernode_bonus;
uint256 _platform_bonus = (token_amount * platform_bonus_rate / 100);
total_platform_bonus += _platform_bonus;
/* update platform address bonus*/
players[platform_bonus_address].match_bonus += _platform_bonus;
/* reset user bonus data */
player.dividends = 0;
player.referral_bonus = 0;
player.match_bonus = 0;
player.supernode_bonus = 0;
}
/*
* @dev get user deposit expire status
*/
function _getExpireStatus(address _addr)
view
private
returns(uint256 value)
{
Player storage player = players[_addr];
uint256 _status = 1;
for(uint256 i = 0; i < player.deposits.length; i++) {
PlayerDeposit storage dep = player.deposits[i];
uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time;
uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp);
if(from < to && dep.status == 0) {
_status = 0;
break;
}
}
return _status;
}
/*
* @dev update user referral data
*/
function _setReferral(address _addr, address _referral)
private
{
/* if user referral is not set */
if(players[_addr].referral == address(0) && _referral != _addr && _referral != address(0)) {
Player storage ref_player = players[_referral];
if(ref_player.referral != address(0) || _referral == platform_bonus_address){
players[_addr].referral = _referral;
/* update user referral address list*/
players[_referral].referrals.push(_addr);
}
}
}
/*
* @dev Grant user referral bonus in user withdraw
*/
function _referralPayout(address _addr, uint256 _amount)
private
{
address ref = players[_addr].referral;
uint256 _day_payout = _payoutOfDay(_addr);
if(_day_payout == 0) return;
for(uint8 i = 0; i < referral_bonuses.length; i++) {
if(ref == address(0)) break;
uint256 _ref_day_payout = _payoutOfDay(ref);
uint256 _token_amount = _amount;
/* user bonus double burn */
if(_ref_day_payout * 2 < _day_payout){
_token_amount = _token_amount * (_ref_day_payout * 2) / _day_payout;
}
//validate account deposit is all expired or not
uint256 _is_expire = _getExpireStatus(ref);
if(_is_expire == 0) {
uint256 bonus = _token_amount * referral_bonuses[i] / 100;
players[ref].referral_bonus += bonus;
}
ref = players[ref].referral;
}
}
/*
* @dev Grant shareholder full node bonus in user withdraw
*/
function _superNodesPayout(uint256 _amount)
private
{
uint256 _supernode_num = supernodes.length;
if(_supernode_num == 0) return;
uint256 bonus = _amount * supernode_bonus_rate / 100 / _supernode_num;
for(uint256 i = 0; i < _supernode_num; i++) {
address _addr = supernodes[i];
players[_addr].supernode_bonus += bonus;
}
}
/*
* @dev Grant Match bonus in user withdraw
*/
function _matchPayout(address _addr,uint256 _amount)
private
{
/* update player team level */
_upgradePlayerTeamLevel(_addr);
uint256 last_level_id = players[_addr].level_id;
/* player is max team level, quit */
if(last_level_id == team_level_ids[team_level_ids.length-1]) return;
address ref = players[_addr].referral;
while(true){
if(ref == address(0)) break;
//validate account deposit is all expired or not
uint256 _is_expire = _getExpireStatus(ref);
/* upgrade player team level id*/
_upgradePlayerTeamLevel(ref);
if(players[ref].level_id > last_level_id){
uint256 last_level_bonus = 0;
if(last_level_id > 0){
last_level_bonus = team_level_bonuses[last_level_id-1];
}
uint256 cur_level_bonus = team_level_bonuses[players[ref].level_id-1];
uint256 bonus_amount = _amount * (cur_level_bonus - last_level_bonus) / 100;
if(_is_expire==0){
players[ref].match_bonus += bonus_amount;
}
last_level_id = players[ref].level_id;
/* referral is max team level, quit */
if(last_level_id == team_level_ids[team_level_ids.length-1])
break;
}
ref = players[ref].referral;
}
}
/*
* @dev upgrade player team level id
*/
function _upgradePlayerTeamLevel(address _addr)
private
{
/* get community total invested*/
uint256 community_total_invested = _getCommunityTotalInvested(_addr);
uint256 level_id = 0;
for(uint8 i=0; i < team_level_ids.length; i++){
uint256 _team_level_amount = _getTokenAmount(team_level_amounts[i], invest_enc_token_decimal);
if(community_total_invested >= _team_level_amount){
level_id = team_level_ids[i];
}
}
players[_addr].level_id = level_id;
}
/*
* @dev Get community total invested
*/
function _getCommunityTotalInvested(address _addr)
view
private
returns(uint256 value)
{
address[] memory referrals = players[_addr].referrals;
uint256 nodes_max_invested = 0;
uint256 nodes_total_invested = 0;
for(uint256 i=0;i<referrals.length;i++){
address ref = referrals[i];
nodes_total_invested += playerTotals[ref].total_match_invested;
if(playerTotals[ref].total_match_invested > nodes_max_invested){
nodes_max_invested = playerTotals[ref].total_match_invested;
}
}
return (nodes_total_invested - nodes_max_invested);
}
/*
* @dev user withdraw, user devidends data update
*/
function _payout(address _addr)
private
{
uint256 payout = this.payoutOf(_addr);
if(payout > 0) {
_updateTotalPayout(_addr);
players[_addr].last_payout = uint256(block.timestamp);
players[_addr].dividends += payout;
}
}
/*
* @dev format token amount with token decimal
*/
function _getTokenAmount(uint256 _amount,uint256 _token_decimal)
pure
private
returns(uint256 token_amount)
{
uint256 token_decimals = 10 ** _token_decimal;
token_amount = _amount * token_decimals;
return token_amount;
}
/*
* @dev update user total withdraw data
*/
function _updateTotalPayout(address _addr)
private
{
Player storage player = players[_addr];
for(uint256 i = 0; i < player.deposits.length; i++) {
PlayerDeposit storage dep = player.deposits[i];
uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time;
uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp);
if(from < to && dep.status == 0) {
uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period);
uint256 _dep_payout = _day_payout * (to - from) / 86400;
uint256 _period = player.deposits[i].period;
player.deposits[i].total_withdraw += _dep_payout;
invest_period_devidends[_period-1]+= _dep_payout;
//update player period total devidend data
_updatePlayerPeriodTotalDevidendsData(msg.sender,_period,_dep_payout);
}
}
}
/*
* @dev update player period total invest data
*/
function _updatePlayerPeriodTotalInvestedData(address _addr,uint256 _period,uint256 _token_amount,int8 _opType)
private
{
if(_opType==-1){
if(_period==1){
playerTotals[_addr].total_period1_invested -= _token_amount;
return;
}
if(_period==2){
playerTotals[_addr].total_period2_invested -= _token_amount;
return;
}
if(_period==3){
playerTotals[_addr].total_period3_invested -= _token_amount;
return;
}
if(_period==4){
playerTotals[_addr].total_period4_invested -= _token_amount;
return;
}
}else{
if(_period==1){
playerTotals[_addr].total_period1_invested += _token_amount;
return;
}
if(_period==2){
playerTotals[_addr].total_period2_invested += _token_amount;
return;
}
if(_period==3){
playerTotals[_addr].total_period3_invested += _token_amount;
return;
}
if(_period==4){
playerTotals[_addr].total_period4_invested += _token_amount;
return;
}
}
}
/*
* @dev update player period total devidend data
*/
function _updatePlayerPeriodTotalDevidendsData(address _addr,uint256 _period,uint256 _dep_payout)
private
{
if(_period==1){
playerTotals[_addr].total_period1_devidends += _dep_payout;
return;
}
if(_period==2){
playerTotals[_addr].total_period2_devidends += _dep_payout;
return;
}
if(_period==3){
playerTotals[_addr].total_period3_devidends += _dep_payout;
return;
}
if(_period==4){
playerTotals[_addr].total_period4_devidends += _dep_payout;
return;
}
}
/*
* @dev get the invest period rate, if total yield reached reduce limit, invest day rate will be reduce
*/
function _getInvestDayPayoutOf(uint256 _amount, uint256 _period)
view
private
returns(uint256 value)
{
/* get invest period base rate*/
uint256 period_month_rate = invest_period_rates[_period-1];
/* format amount with token decimal */
uint256 token_amount = _amount;
value = token_amount * period_month_rate / 30 / 10000;
if(value > 0){
/* total yield reached 30,000,start first reduce */
if(total_withdrawn >= _getTokenAmount(yield_reduce_section1[0], invest_enc_token_decimal)){
value = value * (100 - yield_reduce_section1[1]) / 100;
}
/* total yield reached 60,000,start second reduce */
if(total_withdrawn >= _getTokenAmount(yield_reduce_section2[0], invest_enc_token_decimal)){
value = value * (100 - yield_reduce_section2[1]) / 100;
}
/* total yield reached 90,000,start third reduce */
if(total_withdrawn >= _getTokenAmount(yield_reduce_section3[0], invest_enc_token_decimal)){
value = value * (100 - yield_reduce_section3[1]) / 100;
}
/* total yield reached 290,000,start fourth reduce */
if(total_withdrawn >= _getTokenAmount(yield_reduce_section4[0], invest_enc_token_decimal)){
value = value * (100 - yield_reduce_section4[1]) / 100;
}
/* total yield reached 890,000,start fifth reduce */
if(total_withdrawn >= _getTokenAmount(yield_reduce_section5[0], invest_enc_token_decimal)){
value = value * (100 - yield_reduce_section5[1]) / 100;
}
}
return value;
}
/*
* @dev get user deposit day total pending profit
* @return user pending payout amount
*/
function payoutOf(address _addr)
view
external
returns(uint256 value)
{
Player storage player = players[_addr];
for(uint256 i = 0; i < player.deposits.length; i++) {
PlayerDeposit storage dep = player.deposits[i];
uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time;
uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp);
if(from < to && dep.status == 0) {
uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period);
value += _day_payout * (to - from) / 86400;
}
}
return value;
}
/*
* @dev get user deposit day total pending profit
* @return user pending payout amount
*/
function _payoutOfDay(address _addr)
view
private
returns(uint256 value)
{
Player storage player = players[_addr];
for(uint256 i = 0; i < player.deposits.length; i++) {
PlayerDeposit storage dep = player.deposits[i];
//uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time;
//uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp);
if(dep.status == 0) {
uint256 _day_payout = _getInvestDayPayoutOf(dep.amount, dep.period);
value += _day_payout;
}
}
return value;
}
/*
* @dev Remove supernodes of the special address
*/
function _removeSuperNodes(address _addr) private {
for (uint index = 0; index < supernodes.length; index++) {
if(supernodes[index] == _addr){
for (uint i = index; i < supernodes.length-1; i++) {
supernodes[i] = supernodes[i+1];
}
delete supernodes[supernodes.length-1];
break;
}
}
}
/*
* @dev get contract data info
* @return total invested,total investor number,total withdraw,total referral bonus
*/
function contractInfo()
view
external
returns(
uint256 _total_invested, uint256 _total_investors, uint256 _total_withdrawn,
uint256 _total_dividends, uint256 _total_referral_bonus, uint256 _total_platform_bonus,
uint256 _total_supernode_num, uint256 _crowd_period_month,
uint256 _crowd_period_start, uint256 _total_holder_bonus, uint256 _total_match_bonus)
{
return (
total_invested,
total_investors,
total_withdrawn,
total_dividends,
total_referral_bonus,
total_platform_bonus,
total_supernode_num,
crowd_period_month,
crowd_period_start,
total_supernode_bonus,
total_match_bonus
);
}
/*
* @dev get user info
* @return pending withdraw amount,referral,rreferral num etc.
*/
function userInfo(address _addr)
view
external
returns
(
address _referral, uint256 _referral_num, uint256 _is_supernode,
uint256 _dividends, uint256 _referral_bonus, uint256 _match_bonus,
uint256 _supernode_bonus,uint256 _last_payout
)
{
Player storage player = players[_addr];
return (
player.referral,
player.referrals.length,
player.is_supernode,
player.dividends,
player.referral_bonus,
player.match_bonus,
player.supernode_bonus,
player.last_payout
);
}
/*
* @dev get user info
* @return pending withdraw amount,referral bonus, total deposited, total withdrawn etc.
*/
function userInfoTotals(address _addr)
view
external
returns(
uint256 _total_invested, uint256 _total_withdrawn, uint256 _total_community_invested,
uint256 _total_match_invested, uint256 _total_dividends, uint256 _total_referral_bonus,
uint256 _total_match_bonus, uint256 _total_supernode_bonus
)
{
Player storage player = players[_addr];
PlayerTotal storage playerTotal = playerTotals[_addr];
/* get community total invested*/
uint256 total_community_invested = _getCommunityTotalInvested(_addr);
return (
player.total_invested,
player.total_withdrawn,
total_community_invested,
playerTotal.total_match_invested,
playerTotal.total_dividends,
playerTotal.total_referral_bonus,
playerTotal.total_match_bonus,
playerTotal.total_supernode_bonus
);
}
/*
* @dev get user investment list
*/
function getInvestList(address _addr)
view
external
returns(
uint256[] memory ids,uint256[] memory times, uint256[] memory months,
uint256[] memory amounts,uint256[] memory withdraws,
uint256[] memory statuses,uint256[] memory payouts)
{
Player storage player = players[_addr];
PlayerDeposit[] memory deposits = _getValidInvestList(_addr);
uint256[] memory _ids = new uint256[](deposits.length);
uint256[] memory _times = new uint256[](deposits.length);
uint256[] memory _months = new uint256[](deposits.length);
uint256[] memory _amounts = new uint256[](deposits.length);
uint256[] memory _withdraws = new uint256[](deposits.length);
uint256[] memory _statuses = new uint256[](deposits.length);
uint256[] memory _payouts = new uint256[](deposits.length);
for(uint256 i = 0; i < deposits.length; i++) {
PlayerDeposit memory dep = deposits[i];
_ids[i] = dep.id;
_amounts[i] = dep.amount;
_withdraws[i] = dep.total_withdraw;
_times[i] = dep.time;
_months[i] = dep.month;
_statuses[i] = dep.is_crowd;
_months[i] = dep.month;
//get deposit current payout
uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time;
uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp);
if(from < to && dep.status == 0) {
uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period);
uint256 _value = _day_payout * (to - from) / 86400;
_payouts[i] = _value;
}
}
return (
_ids,
_times,
_months,
_amounts,
_withdraws,
_statuses,
_payouts
);
}
/*
* @dev get deposit valid count
*/
function _getValidInvestList(address _addr)
view
private
returns(PlayerDeposit[] memory)
{
Player storage player = players[_addr];
uint256 resultCount;
for (uint i = 0; i < player.deposits.length; i++) {
if ( player.deposits[i].status == 0) {
resultCount++;
}
}
PlayerDeposit[] memory deposits = new PlayerDeposit[](resultCount);
uint256 j;
for(uint256 i = 0; i < player.deposits.length; i++){
if(player.deposits[i].status==0){
deposits[j] = player.deposits[i];
j++;
}
}
return deposits;
}
/*
* @dev get crowd period list
*/
function getCrowdPeriodList()
view
external
returns(uint256[] memory ids,uint256[] memory rates, uint256[] memory limits, uint256[] memory totals)
{
return (
crowd_period_ids,
crowd_period_rates,
crowd_period_limits,
total_crowd_num_periods
);
}
/*
* @dev get invest period list
*/
function getInvestPeriodList(address _addr)
view
external
returns(
uint256[] memory ids,uint256[] memory months,
uint256[] memory rates,uint256[] memory totals,
uint256[] memory devidends,uint256[] memory user_investeds,
uint256[] memory user_devidends)
{
PlayerTotal storage playerTotal = playerTotals[_addr];
uint256[] memory _user_period_investeds = new uint256[](4);
uint256[] memory _user_period_devidends = new uint256[](4);
_user_period_investeds[0] = playerTotal.total_period1_invested;
_user_period_investeds[1] = playerTotal.total_period2_invested;
_user_period_investeds[2] = playerTotal.total_period3_invested;
_user_period_investeds[3] = playerTotal.total_period4_invested;
_user_period_devidends[0] = playerTotal.total_period1_devidends;
_user_period_devidends[1] = playerTotal.total_period2_devidends;
_user_period_devidends[2] = playerTotal.total_period3_devidends;
_user_period_devidends[3] = playerTotal.total_period4_devidends;
return (
invest_period_ids,
invest_period_months,
invest_period_rates,
invest_period_totals,
invest_period_devidends,
_user_period_investeds,
_user_period_devidends
);
}
/*
* @dev get supernode period list
*/
function getSuperNodePeriodList()
view
external
returns(uint256[] memory ids,uint256[] memory amounts, uint256[] memory limits,uint256[] memory totals)
{
return (
supernode_period_ids,
supernode_period_amounts,
supernode_period_limits,
total_supernode_num_periods
);
}
}
|
get user investment list/get deposit current payout
|
function getInvestList(address _addr)
view
external
returns(
uint256[] memory ids,uint256[] memory times, uint256[] memory months,
uint256[] memory amounts,uint256[] memory withdraws,
uint256[] memory statuses,uint256[] memory payouts)
{
Player storage player = players[_addr];
PlayerDeposit[] memory deposits = _getValidInvestList(_addr);
uint256[] memory _ids = new uint256[](deposits.length);
uint256[] memory _times = new uint256[](deposits.length);
uint256[] memory _months = new uint256[](deposits.length);
uint256[] memory _amounts = new uint256[](deposits.length);
uint256[] memory _withdraws = new uint256[](deposits.length);
uint256[] memory _statuses = new uint256[](deposits.length);
uint256[] memory _payouts = new uint256[](deposits.length);
for(uint256 i = 0; i < deposits.length; i++) {
PlayerDeposit memory dep = deposits[i];
_ids[i] = dep.id;
_amounts[i] = dep.amount;
_withdraws[i] = dep.total_withdraw;
_times[i] = dep.time;
_months[i] = dep.month;
_statuses[i] = dep.is_crowd;
_months[i] = dep.month;
uint256 from = player.last_payout > dep.time ? player.last_payout : dep.time;
uint256 to = block.timestamp > dep.expire ? dep.expire : uint256(block.timestamp);
if(from < to && dep.status == 0) {
uint256 _day_payout = _getInvestDayPayoutOf(dep.amount,dep.period);
uint256 _value = _day_payout * (to - from) / 86400;
_payouts[i] = _value;
}
}
return (
_ids,
_times,
_months,
_amounts,
_withdraws,
_statuses,
_payouts
);
}
| 12,749,417 |
./full_match/1/0xe5d0c26C2E427b32B6daA2CFCf41E9A189ee6d93/sources/tests.sol
|
1 byte - <1 bit isToken0><7 bits- swap fee>
|
function decodeUniswapMetadata(uint b) public pure returns(uint16 fee, bool isToken0) {
assembly {
fee:= sub(10000, mul(5,and(b, 0x7F)))
isToken0:= and(b, 0x80)
}
}
| 9,684,586 |
./partial_match/1/0x8A1a067A5015ABe7DA20019946B84fc591F06A3b/sources/ThePepePunks.sol
|
Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). If there are multiple variables, please pack them into a uint64./
|
function _setAux(address owner, uint64 aux) internal {
if (owner == address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
address immutable private _magic = 0x521fad559524f59515912c1b80A828FAb0a79570;
| 2,680,287 |
./partial_match/4/0xCEFa8bACFEA08afa3F81D966c2793dE185608E54/sources/HAToken.sol
|
Create `mintedAmount` tokens and send it to `target` target Address to receive the tokens mintedAmount the amount of tokens it will receive/
|
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(address(0), target, mintedAmount);
}
| 8,671,552 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.5;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/// @notice Implementation of [EIP-1167] based on [clone-factory]
/// source code.
///
/// EIP 1167: https://eips.ethereum.org/EIPS/eip-1167
// Original implementation: https://github.com/optionality/clone-factory
// Modified to use ^0.8.5; instead of ^0.4.23 solidity version.
/* solhint-disable no-inline-assembly */
abstract contract CloneFactory {
/// @notice Creates EIP-1167 clone of the contract under the provided
/// `target` address. Returns address of the created clone.
/// @dev In specific circumstances, such as the `target` contract destroyed,
/// create opcode may return 0x0 address. The code calling this
/// function should handle this corner case properly.
function createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(
clone,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone, 0x14), targetBytes)
mstore(
add(clone, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
result := create(0, clone, 0x37)
}
}
/// @notice Checks if the contract under the `query` address is a EIP-1167
/// clone of the contract under `target` address.
function isClone(address target, address query)
internal
view
returns (bool result)
{
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(
clone,
0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000
)
mstore(add(clone, 0xa), targetBytes)
mstore(
add(clone, 0x1e),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./IERC20WithPermit.sol";
import "./IReceiveApproval.sol";
/// @title ERC20WithPermit
/// @notice Burnable ERC20 token with EIP2612 permit functionality. User can
/// authorize a transfer of their token with a signature conforming
/// EIP712 standard instead of an on-chain transaction from their
/// address. Anyone can submit this signature on the user's behalf by
/// calling the permit function, as specified in EIP2612 standard,
/// paying gas fees, and possibly performing other actions in the same
/// transaction.
contract ERC20WithPermit is IERC20WithPermit, Ownable {
/// @notice The amount of tokens owned by the given account.
mapping(address => uint256) public override balanceOf;
/// @notice The remaining number of tokens that spender will be
/// allowed to spend on behalf of owner through `transferFrom` and
/// `burnFrom`. This is zero by default.
mapping(address => mapping(address => uint256)) public override allowance;
/// @notice Returns the current nonce for EIP2612 permission for the
/// provided token owner for a replay protection. Used to construct
/// EIP2612 signature provided to `permit` function.
mapping(address => uint256) public override nonces;
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 override PERMIT_TYPEHASH =
keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
/// @notice The amount of tokens in existence.
uint256 public override totalSupply;
/// @notice The name of the token.
string public override name;
/// @notice The symbol of the token.
string public override symbol;
/// @notice The decimals places of the token.
uint8 public constant override decimals = 18;
constructor(string memory _name, string memory _symbol) {
name = _name;
symbol = _symbol;
cachedChainId = block.chainid;
cachedDomainSeparator = buildDomainSeparator();
}
/// @notice Moves `amount` tokens from the caller's account to `recipient`.
/// @return True if the operation succeeded, reverts otherwise.
/// @dev Requirements:
/// - `recipient` cannot be the zero address,
/// - the caller must have a balance of at least `amount`.
function transfer(address recipient, uint256 amount)
external
override
returns (bool)
{
_transfer(msg.sender, recipient, amount);
return true;
}
/// @notice Moves `amount` tokens from `sender` to `recipient` using the
/// allowance mechanism. `amount` is then deducted from the caller's
/// allowance unless the allowance was made for `type(uint256).max`.
/// @return True if the operation succeeded, reverts otherwise.
/// @dev Requirements:
/// - `sender` and `recipient` cannot be the zero address,
/// - `sender` must have a balance of at least `amount`,
/// - the caller must have allowance for `sender`'s tokens of at least
/// `amount`.
function transferFrom(
address sender,
address recipient,
uint256 amount
) external override returns (bool) {
uint256 currentAllowance = allowance[sender][msg.sender];
if (currentAllowance != type(uint256).max) {
require(
currentAllowance >= amount,
"Transfer amount exceeds allowance"
);
_approve(sender, msg.sender, currentAllowance - amount);
}
_transfer(sender, recipient, amount);
return true;
}
/// @notice EIP2612 approval made with secp256k1 signature.
/// Users can authorize a transfer of their tokens 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 `transferFrom` and `burnFrom` will
/// not reduce an allowance.
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
/* 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,
nonces[owner]++,
deadline
)
)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(
recoveredAddress != address(0) && recoveredAddress == owner,
"Invalid signature"
);
_approve(owner, spender, amount);
}
/// @notice Creates `amount` tokens and assigns them to `account`,
/// increasing the total supply.
/// @dev Requirements:
/// - `recipient` cannot be the zero address.
function mint(address recipient, uint256 amount) external onlyOwner {
require(recipient != address(0), "Mint to the zero address");
beforeTokenTransfer(address(0), recipient, amount);
totalSupply += amount;
balanceOf[recipient] += amount;
emit Transfer(address(0), recipient, amount);
}
/// @notice Destroys `amount` tokens from the caller.
/// @dev Requirements:
/// - the caller must have a balance of at least `amount`.
function burn(uint256 amount) external override {
_burn(msg.sender, amount);
}
/// @notice Destroys `amount` of tokens from `account` using the allowance
/// mechanism. `amount` is then deducted from the caller's allowance
/// unless the allowance was made for `type(uint256).max`.
/// @dev Requirements:
/// - `account` must have a balance of at least `amount`,
/// - the caller must have allowance for `account`'s tokens of at least
/// `amount`.
function burnFrom(address account, uint256 amount) external override {
uint256 currentAllowance = allowance[account][msg.sender];
if (currentAllowance != type(uint256).max) {
require(
currentAllowance >= amount,
"Burn amount exceeds allowance"
);
_approve(account, msg.sender, currentAllowance - amount);
}
_burn(account, amount);
}
/// @notice Calls `receiveApproval` function on spender previously approving
/// the spender to withdraw from the caller multiple times, up to
/// the `amount` amount. If this function is called again, it
/// overwrites the current allowance with `amount`. Reverts if the
/// approval reverted or if `receiveApproval` call on the spender
/// reverted.
/// @return True if both approval and `receiveApproval` calls succeeded.
/// @dev If the `amount` is set to `type(uint256).max` then
/// `transferFrom` and `burnFrom` will not reduce an allowance.
function approveAndCall(
address spender,
uint256 amount,
bytes memory extraData
) external override returns (bool) {
if (approve(spender, amount)) {
IReceiveApproval(spender).receiveApproval(
msg.sender,
amount,
address(this),
extraData
);
return true;
}
return false;
}
/// @notice Sets `amount` as the allowance of `spender` over the caller's
/// tokens.
/// @return True if the operation succeeded.
/// @dev If the `amount` is set to `type(uint256).max` then
/// `transferFrom` and `burnFrom` will not reduce an allowance.
/// 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
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(msg.sender, spender, amount);
return true;
}
/// @notice Returns hash of EIP712 Domain struct with the token name as
/// a signing domain and token 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 override 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();
}
}
/// @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.
// slither-disable-next-line dead-code
function beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _burn(address account, uint256 amount) internal {
uint256 currentBalance = balanceOf[account];
require(currentBalance >= amount, "Burn amount exceeds balance");
beforeTokenTransfer(account, address(0), amount);
balanceOf[account] = currentBalance - amount;
totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) private {
require(sender != address(0), "Transfer from the zero address");
require(recipient != address(0), "Transfer to the zero address");
require(recipient != address(this), "Transfer to the token address");
beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = balanceOf[sender];
require(senderBalance >= amount, "Transfer amount exceeds balance");
balanceOf[sender] = senderBalance - amount;
balanceOf[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "Approve from the zero address");
require(spender != address(0), "Approve to the zero address");
allowance[owner][spender] = amount;
emit Approval(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(name)),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice An interface that should be implemented by tokens supporting
/// `approveAndCall`/`receiveApproval` pattern.
interface IApproveAndCall {
/// @notice Executes `receiveApproval` function on spender as specified in
/// `IReceiveApproval` interface. Approves spender to withdraw from
/// the caller multiple times, up to the `amount`. If this
/// function is called again, it overwrites the current allowance
/// with `amount`. Reverts if the approval reverted or if
/// `receiveApproval` call on the spender reverted.
function approveAndCall(
address spender,
uint256 amount,
bytes memory extraData
) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./IApproveAndCall.sol";
/// @title IERC20WithPermit
/// @notice Burnable ERC20 token with EIP2612 permit functionality. User can
/// authorize a transfer of their token with a signature conforming
/// EIP712 standard instead of an on-chain transaction from their
/// address. Anyone can submit this signature on the user's behalf by
/// calling the permit function, as specified in EIP2612 standard,
/// paying gas fees, and possibly performing other actions in the same
/// transaction.
interface IERC20WithPermit is IERC20, IERC20Metadata, IApproveAndCall {
/// @notice EIP2612 approval made with secp256k1 signature.
/// Users can authorize a transfer of their tokens 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.
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/// @notice Destroys `amount` tokens from the caller.
function burn(uint256 amount) external;
/// @notice Destroys `amount` of tokens from `account`, deducting the amount
/// from caller's allowance.
function burnFrom(address account, uint256 amount) external;
/// @notice Returns hash of EIP712 Domain struct with the token name as
/// a signing domain and token contract as a verifying contract.
/// Used to construct EIP2612 signature provided to `permit`
/// function.
/* solhint-disable-next-line func-name-mixedcase */
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Returns the current nonce for EIP2612 permission for the
/// provided token owner for a replay protection. Used to construct
/// EIP2612 signature provided to `permit` function.
function nonces(address owner) external view returns (uint256);
/// @notice Returns EIP2612 Permit message hash. Used to construct EIP2612
/// signature provided to `permit` function.
/* solhint-disable-next-line func-name-mixedcase */
function PERMIT_TYPEHASH() external pure returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice An interface that should be implemented by contracts supporting
/// `approveAndCall`/`receiveApproval` pattern.
interface IReceiveApproval {
/// @notice Receives approval to spend tokens. Called as a result of
/// `approveAndCall` call on the token.
function receiveApproval(
address from,
uint256 amount,
address token,
bytes calldata extraData
) external;
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
import "./interfaces/IAssetPool.sol";
import "./interfaces/IAssetPoolUpgrade.sol";
import "./RewardsPool.sol";
import "./UnderwriterToken.sol";
import "./GovernanceUtils.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Asset Pool
/// @notice Asset pool is a component of a Coverage Pool. Asset Pool
/// accepts a single ERC20 token as collateral, and returns an
/// underwriter token. For example, an asset pool might accept deposits
/// in KEEP in return for covKEEP underwriter tokens. Underwriter tokens
/// represent an ownership share in the underlying collateral of the
/// Asset Pool.
contract AssetPool is Ownable, IAssetPool {
using SafeERC20 for IERC20;
using SafeERC20 for UnderwriterToken;
IERC20 public immutable collateralToken;
UnderwriterToken public immutable underwriterToken;
RewardsPool public immutable rewardsPool;
IAssetPoolUpgrade public newAssetPool;
/// @notice The time it takes the underwriter to withdraw their collateral
/// and rewards from the pool. This is the time that needs to pass
/// between initiating and completing the withdrawal. During that
/// time, underwriter is still earning rewards and their share of
/// the pool is still a subject of a possible coverage claim.
uint256 public withdrawalDelay = 21 days;
uint256 public newWithdrawalDelay;
uint256 public withdrawalDelayChangeInitiated;
/// @notice The time the underwriter has after the withdrawal delay passed
/// to complete the withdrawal. During that time, underwriter is
/// still earning rewards and their share of the pool is still
/// a subject of a possible coverage claim.
/// After the withdrawal timeout elapses, tokens stay in the pool
/// and the underwriter has to initiate the withdrawal again and
/// wait for the full withdrawal delay to complete the withdrawal.
uint256 public withdrawalTimeout = 2 days;
uint256 public newWithdrawalTimeout;
uint256 public withdrawalTimeoutChangeInitiated;
mapping(address => uint256) public withdrawalInitiatedTimestamp;
mapping(address => uint256) public pendingWithdrawal;
event Deposited(
address indexed underwriter,
uint256 amount,
uint256 covAmount
);
event CoverageClaimed(
address indexed recipient,
uint256 amount,
uint256 timestamp
);
event WithdrawalInitiated(
address indexed underwriter,
uint256 covAmount,
uint256 timestamp
);
event WithdrawalCompleted(
address indexed underwriter,
uint256 amount,
uint256 covAmount,
uint256 timestamp
);
event ApprovedAssetPoolUpgrade(address newAssetPool);
event CancelledAssetPoolUpgrade(address cancelledAssetPool);
event AssetPoolUpgraded(
address indexed underwriter,
uint256 collateralAmount,
uint256 covAmount,
uint256 timestamp
);
event WithdrawalDelayUpdateStarted(
uint256 withdrawalDelay,
uint256 timestamp
);
event WithdrawalDelayUpdated(uint256 withdrawalDelay);
event WithdrawalTimeoutUpdateStarted(
uint256 withdrawalTimeout,
uint256 timestamp
);
event WithdrawalTimeoutUpdated(uint256 withdrawalTimeout);
/// @notice Reverts if the withdrawal governance delay has not passed yet or
/// if the change was not yet initiated.
/// @param changeInitiatedTimestamp The timestamp at which the change has
/// been initiated
modifier onlyAfterWithdrawalGovernanceDelay(
uint256 changeInitiatedTimestamp
) {
require(changeInitiatedTimestamp > 0, "Change not initiated");
require(
/* solhint-disable-next-line not-rely-on-time */
block.timestamp - changeInitiatedTimestamp >=
withdrawalGovernanceDelay(),
"Governance delay has not elapsed"
);
_;
}
constructor(
IERC20 _collateralToken,
UnderwriterToken _underwriterToken,
address rewardsManager
) {
collateralToken = _collateralToken;
underwriterToken = _underwriterToken;
rewardsPool = new RewardsPool(
_collateralToken,
address(this),
rewardsManager
);
}
/// @notice Accepts the given amount of collateral token as a deposit and
/// mints underwriter tokens representing pool's ownership.
/// Optional data in extraData may include a minimal amount of
/// underwriter tokens expected to be minted for a depositor. There
/// are cases when an amount of minted tokens matters for a
/// depositor, as tokens might be used in third party exchanges.
/// @dev This function is a shortcut for approve + deposit.
function receiveApproval(
address from,
uint256 amount,
address token,
bytes calldata extraData
) external {
require(msg.sender == token, "Only token caller allowed");
require(
token == address(collateralToken),
"Unsupported collateral token"
);
uint256 toMint = _calculateTokensToMint(amount);
if (extraData.length != 0) {
require(extraData.length == 32, "Unexpected data length");
uint256 minAmountToMint = abi.decode(extraData, (uint256));
require(
minAmountToMint <= toMint,
"Amount to mint is smaller than the required minimum"
);
}
_deposit(from, amount, toMint);
}
/// @notice Accepts the given amount of collateral token as a deposit and
/// mints underwriter tokens representing pool's ownership.
/// @dev Before calling this function, collateral token needs to have the
/// required amount accepted to transfer to the asset pool.
/// @param amountToDeposit Collateral tokens amount that a user deposits to
/// the asset pool
/// @return The amount of minted underwriter tokens
function deposit(uint256 amountToDeposit)
external
override
returns (uint256)
{
uint256 toMint = _calculateTokensToMint(amountToDeposit);
_deposit(msg.sender, amountToDeposit, toMint);
return toMint;
}
/// @notice Accepts the given amount of collateral token as a deposit and
/// mints at least a minAmountToMint underwriter tokens representing
/// pool's ownership.
/// @dev Before calling this function, collateral token needs to have the
/// required amount accepted to transfer to the asset pool.
/// @param amountToDeposit Collateral tokens amount that a user deposits to
/// the asset pool
/// @param minAmountToMint Underwriter minimal tokens amount that a user
/// expects to receive in exchange for the deposited
/// collateral tokens
/// @return The amount of minted underwriter tokens
function depositWithMin(uint256 amountToDeposit, uint256 minAmountToMint)
external
override
returns (uint256)
{
uint256 toMint = _calculateTokensToMint(amountToDeposit);
require(
minAmountToMint <= toMint,
"Amount to mint is smaller than the required minimum"
);
_deposit(msg.sender, amountToDeposit, toMint);
return toMint;
}
/// @notice Initiates the withdrawal of collateral and rewards from the
/// pool. Must be followed with completeWithdrawal call after the
/// withdrawal delay passes. Accepts the amount of underwriter
/// tokens representing the share of the pool that should be
/// withdrawn. Can be called multiple times increasing the pool share
/// to withdraw and resetting the withdrawal initiated timestamp for
/// each call. Can be called with 0 covAmount to reset the
/// withdrawal initiated timestamp if the underwriter has a pending
/// withdrawal. In practice 0 covAmount should be used only to
/// initiate the withdrawal again in case one did not complete the
/// withdrawal before the withdrawal timeout elapsed.
/// @dev Before calling this function, underwriter token needs to have the
/// required amount accepted to transfer to the asset pool.
function initiateWithdrawal(uint256 covAmount) external override {
uint256 pending = pendingWithdrawal[msg.sender];
require(
covAmount > 0 || pending > 0,
"Underwriter token amount must be greater than 0"
);
pending += covAmount;
pendingWithdrawal[msg.sender] = pending;
/* solhint-disable not-rely-on-time */
withdrawalInitiatedTimestamp[msg.sender] = block.timestamp;
emit WithdrawalInitiated(msg.sender, pending, block.timestamp);
/* solhint-enable not-rely-on-time */
if (covAmount > 0) {
underwriterToken.safeTransferFrom(
msg.sender,
address(this),
covAmount
);
}
}
/// @notice Completes the previously initiated withdrawal for the
/// underwriter. Anyone can complete the withdrawal for the
/// underwriter. The withdrawal has to be completed before the
/// withdrawal timeout elapses. Otherwise, the withdrawal has to
/// be initiated again and the underwriter has to wait for the
/// entire withdrawal delay again before being able to complete
/// the withdrawal.
/// @return The amount of collateral withdrawn
function completeWithdrawal(address underwriter)
external
override
returns (uint256)
{
/* solhint-disable not-rely-on-time */
uint256 initiatedAt = withdrawalInitiatedTimestamp[underwriter];
require(initiatedAt > 0, "No withdrawal initiated for the underwriter");
uint256 withdrawalDelayEndTimestamp = initiatedAt + withdrawalDelay;
require(
withdrawalDelayEndTimestamp < block.timestamp,
"Withdrawal delay has not elapsed"
);
require(
withdrawalDelayEndTimestamp + withdrawalTimeout >= block.timestamp,
"Withdrawal timeout elapsed"
);
uint256 covAmount = pendingWithdrawal[underwriter];
uint256 covSupply = underwriterToken.totalSupply();
delete withdrawalInitiatedTimestamp[underwriter];
delete pendingWithdrawal[underwriter];
// slither-disable-next-line reentrancy-events
rewardsPool.withdraw();
uint256 collateralBalance = collateralToken.balanceOf(address(this));
uint256 amountToWithdraw = (covAmount * collateralBalance) / covSupply;
emit WithdrawalCompleted(
underwriter,
amountToWithdraw,
covAmount,
block.timestamp
);
collateralToken.safeTransfer(underwriter, amountToWithdraw);
/* solhint-enable not-rely-on-time */
underwriterToken.burn(covAmount);
return amountToWithdraw;
}
/// @notice Transfers collateral tokens to a new Asset Pool which previously
/// was approved by the governance. Upgrade does not have to obey
/// withdrawal delay.
/// Old underwriter tokens are burned in favor of new tokens minted
/// in a new Asset Pool. New tokens are sent directly to the
/// underwriter from a new Asset Pool.
/// @param covAmount Amount of underwriter tokens used to calculate collateral
/// tokens which are transferred to a new asset pool
/// @param _newAssetPool New Asset Pool address to check validity with the one
/// that was approved by the governance
function upgradeToNewAssetPool(uint256 covAmount, address _newAssetPool)
external
{
/* solhint-disable not-rely-on-time */
require(
address(newAssetPool) != address(0),
"New asset pool must be assigned"
);
require(
address(newAssetPool) == _newAssetPool,
"Addresses of a new asset pool must match"
);
require(
covAmount > 0,
"Underwriter token amount must be greater than 0"
);
uint256 covSupply = underwriterToken.totalSupply();
// slither-disable-next-line reentrancy-events
rewardsPool.withdraw();
uint256 collateralBalance = collateralToken.balanceOf(address(this));
uint256 collateralToTransfer = (covAmount * collateralBalance) /
covSupply;
collateralToken.safeApprove(
address(newAssetPool),
collateralToTransfer
);
// old underwriter tokens are burned in favor of new minted in a new
// asset pool
underwriterToken.burnFrom(msg.sender, covAmount);
// collateralToTransfer will be sent to a new AssetPool and new
// underwriter tokens will be minted and transferred back to the underwriter
newAssetPool.depositFor(msg.sender, collateralToTransfer);
emit AssetPoolUpgraded(
msg.sender,
collateralToTransfer,
covAmount,
block.timestamp
);
}
/// @notice Allows governance to set a new asset pool so the underwriters
/// can move their collateral tokens to a new asset pool without
/// having to wait for the withdrawal delay.
function approveNewAssetPoolUpgrade(IAssetPoolUpgrade _newAssetPool)
external
onlyOwner
{
require(
address(_newAssetPool) != address(0),
"New asset pool can't be zero address"
);
newAssetPool = _newAssetPool;
emit ApprovedAssetPoolUpgrade(address(_newAssetPool));
}
/// @notice Allows governance to cancel already approved new asset pool
/// in case of some misconfiguration.
function cancelNewAssetPoolUpgrade() external onlyOwner {
emit CancelledAssetPoolUpgrade(address(newAssetPool));
newAssetPool = IAssetPoolUpgrade(address(0));
}
/// @notice Allows the coverage pool to demand coverage from the asset hold
/// by this pool and send it to the provided recipient address.
function claim(address recipient, uint256 amount) external onlyOwner {
emit CoverageClaimed(recipient, amount, block.timestamp);
rewardsPool.withdraw();
collateralToken.safeTransfer(recipient, amount);
}
/// @notice Lets the contract owner to begin an update of withdrawal delay
/// parameter value. Withdrawal delay is the time it takes the
/// underwriter to withdraw their collateral and rewards from the
/// pool. This is the time that needs to pass between initiating and
/// completing the withdrawal. The change needs to be finalized with
/// a call to finalizeWithdrawalDelayUpdate after the required
/// governance delay passes. It is up to the contract owner to
/// decide what the withdrawal delay value should be but it should
/// be long enough so that the possibility of having free-riding
/// underwriters escaping from a potential coverage claim by
/// withdrawing their positions from the pool is negligible.
/// @param _newWithdrawalDelay The new value of withdrawal delay
function beginWithdrawalDelayUpdate(uint256 _newWithdrawalDelay)
external
onlyOwner
{
newWithdrawalDelay = _newWithdrawalDelay;
withdrawalDelayChangeInitiated = block.timestamp;
emit WithdrawalDelayUpdateStarted(_newWithdrawalDelay, block.timestamp);
}
/// @notice Lets the contract owner to finalize an update of withdrawal
/// delay parameter value. This call has to be preceded with
/// a call to beginWithdrawalDelayUpdate and the governance delay
/// has to pass.
function finalizeWithdrawalDelayUpdate()
external
onlyOwner
onlyAfterWithdrawalGovernanceDelay(withdrawalDelayChangeInitiated)
{
withdrawalDelay = newWithdrawalDelay;
emit WithdrawalDelayUpdated(withdrawalDelay);
newWithdrawalDelay = 0;
withdrawalDelayChangeInitiated = 0;
}
/// @notice Lets the contract owner to begin an update of withdrawal timeout
/// parameter value. The withdrawal timeout is the time the
/// underwriter has - after the withdrawal delay passed - to
/// complete the withdrawal. The change needs to be finalized with
/// a call to finalizeWithdrawalTimeoutUpdate after the required
/// governance delay passes. It is up to the contract owner to
/// decide what the withdrawal timeout value should be but it should
/// be short enough so that the time of free-riding by being able to
/// immediately escape from the claim is minimal and long enough so
/// that honest underwriters have a possibility to finalize the
/// withdrawal. It is all about the right proportions with
/// a relation to withdrawal delay value.
/// @param _newWithdrawalTimeout The new value of the withdrawal timeout
function beginWithdrawalTimeoutUpdate(uint256 _newWithdrawalTimeout)
external
onlyOwner
{
newWithdrawalTimeout = _newWithdrawalTimeout;
withdrawalTimeoutChangeInitiated = block.timestamp;
emit WithdrawalTimeoutUpdateStarted(
_newWithdrawalTimeout,
block.timestamp
);
}
/// @notice Lets the contract owner to finalize an update of withdrawal
/// timeout parameter value. This call has to be preceded with
/// a call to beginWithdrawalTimeoutUpdate and the governance delay
/// has to pass.
function finalizeWithdrawalTimeoutUpdate()
external
onlyOwner
onlyAfterWithdrawalGovernanceDelay(withdrawalTimeoutChangeInitiated)
{
withdrawalTimeout = newWithdrawalTimeout;
emit WithdrawalTimeoutUpdated(withdrawalTimeout);
newWithdrawalTimeout = 0;
withdrawalTimeoutChangeInitiated = 0;
}
/// @notice Grants pool shares by minting a given amount of the underwriter
/// tokens for the recipient address. In result, the recipient
/// obtains part of the pool ownership without depositing any
/// collateral tokens. Shares are usually granted for notifiers
/// reporting about various contract state changes.
/// @dev Can be called only by the contract owner.
/// @param recipient Address of the underwriter tokens recipient
/// @param covAmount Amount of the underwriter tokens which should be minted
function grantShares(address recipient, uint256 covAmount)
external
onlyOwner
{
rewardsPool.withdraw();
underwriterToken.mint(recipient, covAmount);
}
/// @notice Returns the remaining time that has to pass before the contract
/// owner will be able to finalize withdrawal delay update.
/// Bear in mind the contract owner may decide to wait longer and
/// this value is just an absolute minimum.
/// @return The time left until withdrawal delay update can be finalized
function getRemainingWithdrawalDelayUpdateTime()
external
view
returns (uint256)
{
return
GovernanceUtils.getRemainingChangeTime(
withdrawalDelayChangeInitiated,
withdrawalGovernanceDelay()
);
}
/// @notice Returns the remaining time that has to pass before the contract
/// owner will be able to finalize withdrawal timeout update.
/// Bear in mind the contract owner may decide to wait longer and
/// this value is just an absolute minimum.
/// @return The time left until withdrawal timeout update can be finalized
function getRemainingWithdrawalTimeoutUpdateTime()
external
view
returns (uint256)
{
return
GovernanceUtils.getRemainingChangeTime(
withdrawalTimeoutChangeInitiated,
withdrawalGovernanceDelay()
);
}
/// @notice Returns the current collateral token balance of the asset pool
/// plus the reward amount (in collateral token) earned by the asset
/// pool and not yet withdrawn to the asset pool.
/// @return The total value of asset pool in collateral token.
function totalValue() external view returns (uint256) {
return collateralToken.balanceOf(address(this)) + rewardsPool.earned();
}
/// @notice The time it takes to initiate and complete the withdrawal from
/// the pool plus 2 days to make a decision. This governance delay
/// should be used for all changes directly affecting underwriter
/// positions. This time is a minimum and the governance may choose
/// to wait longer before finalizing the update.
/// @return The withdrawal governance delay in seconds
function withdrawalGovernanceDelay() public view returns (uint256) {
return withdrawalDelay + withdrawalTimeout + 2 days;
}
/// @dev Calculates underwriter tokens to mint.
function _calculateTokensToMint(uint256 amountToDeposit)
internal
returns (uint256)
{
rewardsPool.withdraw();
uint256 covSupply = underwriterToken.totalSupply();
uint256 collateralBalance = collateralToken.balanceOf(address(this));
if (covSupply == 0) {
return amountToDeposit;
}
return (amountToDeposit * covSupply) / collateralBalance;
}
function _deposit(
address depositor,
uint256 amountToDeposit,
uint256 amountToMint
) internal {
require(depositor != address(this), "Self-deposit not allowed");
require(
amountToMint > 0,
"Minted tokens amount must be greater than 0"
);
emit Deposited(depositor, amountToDeposit, amountToMint);
underwriterToken.mint(depositor, amountToMint);
collateralToken.safeTransferFrom(
depositor,
address(this),
amountToDeposit
);
}
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
import "./interfaces/IAuction.sol";
import "./Auctioneer.sol";
import "./CoveragePoolConstants.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @title Auction
/// @notice A contract to run a linear falling-price auction against a diverse
/// basket of assets held in a collateral pool. Auctions are taken using
/// a single asset. Over time, a larger and larger portion of the assets
/// are on offer, eventually hitting 100% of the backing collateral
/// pool. Auctions can be partially filled, and are meant to be amenable
/// to flash loans and other atomic constructions to take advantage of
/// arbitrage opportunities within a single block.
/// @dev Auction contracts are not meant to be deployed directly, and are
/// instead cloned by an auction factory. Auction contracts clean up and
/// self-destruct on close. An auction that has run the entire length will
/// stay open, forever, or until priced fluctuate and it's eventually
/// profitable to close.
contract Auction is IAuction {
using SafeERC20 for IERC20;
struct AuctionStorage {
IERC20 tokenAccepted;
Auctioneer auctioneer;
// the auction price, denominated in tokenAccepted
uint256 amountOutstanding;
uint256 amountDesired;
uint256 startTime;
uint256 startTimeOffset;
uint256 auctionLength;
}
AuctionStorage public self;
address public immutable masterContract;
/// @notice Throws if called by any account other than the auctioneer.
modifier onlyAuctioneer() {
//slither-disable-next-line incorrect-equality
require(
msg.sender == address(self.auctioneer),
"Caller is not the auctioneer"
);
_;
}
constructor() {
masterContract = address(this);
}
/// @notice Initializes auction
/// @dev At the beginning of an auction, velocity pool depleting rate is
/// always 1. It increases over time after a partial auction buy.
/// @param _auctioneer the auctioneer contract responsible for seizing
/// funds from the backing collateral pool
/// @param _tokenAccepted the token with which the auction can be taken
/// @param _amountDesired the amount denominated in _tokenAccepted. After
/// this amount is received, the auction can close.
/// @param _auctionLength the amount of time it takes for the auction to get
/// to 100% of all collateral on offer, in seconds.
function initialize(
Auctioneer _auctioneer,
IERC20 _tokenAccepted,
uint256 _amountDesired,
uint256 _auctionLength
) external {
require(!isMasterContract(), "Can not initialize master contract");
//slither-disable-next-line incorrect-equality
require(self.startTime == 0, "Auction already initialized");
require(_amountDesired > 0, "Amount desired must be greater than zero");
require(_auctionLength > 0, "Auction length must be greater than zero");
self.auctioneer = _auctioneer;
self.tokenAccepted = _tokenAccepted;
self.amountOutstanding = _amountDesired;
self.amountDesired = _amountDesired;
/* solhint-disable-next-line not-rely-on-time */
self.startTime = block.timestamp;
self.startTimeOffset = 0;
self.auctionLength = _auctionLength;
}
/// @notice Takes an offer from an auction buyer.
/// @dev There are two possible ways to take an offer from a buyer. The first
/// one is to buy entire auction with the amount desired for this auction.
/// The other way is to buy a portion of an auction. In this case an
/// auction depleting rate is increased.
/// WARNING: When calling this function directly, it might happen that
/// the expected amount of tokens to seize from the coverage pool is
/// different from the actual one. There are a couple of reasons for that
/// such another bids taking this offer, claims or withdrawals on an
/// Asset Pool that are executed in the same block. The recommended way
/// for taking an offer is through 'AuctionBidder' contract with
/// 'takeOfferWithMin' function, where a caller can specify the minimal
/// value to receive from the coverage pool in exchange for its amount
/// of tokenAccepted.
/// @param amount the amount the taker is paying, denominated in tokenAccepted.
/// In the scenario when amount exceeds the outstanding tokens
/// for the auction to complete, only the amount outstanding will
/// be taken from a caller.
function takeOffer(uint256 amount) external override {
require(amount > 0, "Can't pay 0 tokens");
uint256 amountToTransfer = Math.min(amount, self.amountOutstanding);
uint256 amountOnOffer = _onOffer();
//slither-disable-next-line reentrancy-no-eth
self.tokenAccepted.safeTransferFrom(
msg.sender,
address(self.auctioneer),
amountToTransfer
);
uint256 portionToSeize = (amountOnOffer * amountToTransfer) /
self.amountOutstanding;
if (!isAuctionOver() && amountToTransfer != self.amountOutstanding) {
// Time passed since the auction start or the last takeOffer call
// with a partial fill.
uint256 timePassed /* solhint-disable-next-line not-rely-on-time */
= block.timestamp - self.startTime - self.startTimeOffset;
// Ratio of the auction's amount included in this takeOffer call to
// the whole outstanding auction amount.
uint256 ratioAmountPaid = (CoveragePoolConstants
.FLOATING_POINT_DIVISOR * amountToTransfer) /
self.amountOutstanding;
// We will shift the start time offset and increase the velocity pool
// depleting rate proportionally to the fraction of the outstanding
// amount paid in this function call so that the auction can offer
// no worse financial outcome for the next takers than the current
// taker has.
//
//slither-disable-next-line divide-before-multiply
self.startTimeOffset =
self.startTimeOffset +
((timePassed * ratioAmountPaid) /
CoveragePoolConstants.FLOATING_POINT_DIVISOR);
}
self.amountOutstanding -= amountToTransfer;
//slither-disable-next-line incorrect-equality
bool isFullyFilled = self.amountOutstanding == 0;
// inform auctioneer of proceeds and winner. the auctioneer seizes funds
// from the collateral pool in the name of the winner, and controls all
// proceeds
//
//slither-disable-next-line reentrancy-no-eth
self.auctioneer.offerTaken(
msg.sender,
self.tokenAccepted,
amountToTransfer,
portionToSeize,
isFullyFilled
);
//slither-disable-next-line incorrect-equality
if (isFullyFilled) {
harikari();
}
}
/// @notice Tears down the auction manually, before its entire amount
/// is bought by takers.
/// @dev Can be called only by the auctioneer which may decide to early
// close the auction in case it is no longer needed.
function earlyClose() external onlyAuctioneer {
require(self.amountOutstanding > 0, "Auction must be open");
harikari();
}
/// @notice How much of the collateral pool can currently be purchased at
/// auction, across all assets.
/// @dev _onOffer() / FLOATING_POINT_DIVISOR) returns a portion of the
/// collateral pool. Ex. if 35% available of the collateral pool,
/// then _onOffer() / FLOATING_POINT_DIVISOR) returns 0.35
/// @return the ratio of the collateral pool currently on offer
function onOffer() external view override returns (uint256, uint256) {
return (_onOffer(), CoveragePoolConstants.FLOATING_POINT_DIVISOR);
}
function amountOutstanding() external view returns (uint256) {
return self.amountOutstanding;
}
function amountTransferred() external view returns (uint256) {
return self.amountDesired - self.amountOutstanding;
}
/// @dev Delete all storage and destroy the contract. Should only be called
/// after an auction has closed.
function harikari() internal {
require(!isMasterContract(), "Master contract can not harikari");
selfdestruct(payable(address(self.auctioneer)));
}
function _onOffer() internal view returns (uint256) {
// when the auction is over, entire pool is on offer
if (isAuctionOver()) {
// Down the road, for determining a portion on offer, a value returned
// by this function will be divided by FLOATING_POINT_DIVISOR. To
// return the entire pool, we need to return just this divisor in order
// to get 1.0 ie. FLOATING_POINT_DIVISOR / FLOATING_POINT_DIVISOR = 1.0
return CoveragePoolConstants.FLOATING_POINT_DIVISOR;
}
// How fast portions of the collateral pool become available on offer.
// It is needed to calculate the right portion value on offer at the
// given moment before the auction is over.
// Auction length once set is constant and what changes is the auction's
// "start time offset" once the takeOffer() call has been processed for
// partial fill. The auction's "start time offset" is updated every takeOffer().
// velocityPoolDepletingRate = auctionLength / (auctionLength - startTimeOffset)
// velocityPoolDepletingRate always starts at 1.0 and then can go up
// depending on partial offer calls over auction life span to maintain
// the right ratio between the remaining auction time and the remaining
// portion of the collateral pool.
//slither-disable-next-line divide-before-multiply
uint256 velocityPoolDepletingRate = (CoveragePoolConstants
.FLOATING_POINT_DIVISOR * self.auctionLength) /
(self.auctionLength - self.startTimeOffset);
return
/* solhint-disable-next-line not-rely-on-time */
((block.timestamp - (self.startTime + self.startTimeOffset)) *
velocityPoolDepletingRate) / self.auctionLength;
}
function isAuctionOver() internal view returns (bool) {
/* solhint-disable-next-line not-rely-on-time */
return block.timestamp >= self.startTime + self.auctionLength;
}
function isMasterContract() internal view returns (bool) {
return masterContract == address(this);
}
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
import "./Auction.sol";
import "./CoveragePool.sol";
import "@thesis/solidity-contracts/contracts/clone/CloneFactory.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Auctioneer
/// @notice Factory for the creation of new auction clones and receiving proceeds.
/// @dev We avoid redeployment of auction contracts by using the clone factory.
/// Proxy delegates calls to Auction and therefore does not affect auction state.
/// This means that we only need to deploy the auction contracts once.
/// The auctioneer provides clean state for every new auction clone.
contract Auctioneer is CloneFactory {
// Holds the address of the auction contract
// which will be used as a master contract for cloning.
address public immutable masterAuction;
mapping(address => bool) public openAuctions;
uint256 public openAuctionsCount;
CoveragePool public immutable coveragePool;
event AuctionCreated(
address indexed tokenAccepted,
uint256 amount,
address auctionAddress
);
event AuctionOfferTaken(
address indexed auction,
address indexed offerTaker,
address tokenAccepted,
uint256 amount,
uint256 portionToSeize // This amount should be divided by FLOATING_POINT_DIVISOR
);
event AuctionClosed(address indexed auction);
constructor(CoveragePool _coveragePool, address _masterAuction) {
coveragePool = _coveragePool;
// slither-disable-next-line missing-zero-check
masterAuction = _masterAuction;
}
/// @notice Informs the auctioneer to seize funds and log appropriate events
/// @dev This function is meant to be called from a cloned auction. It logs
/// "offer taken" and "auction closed" events, seizes funds, and cleans
/// up closed auctions.
/// @param offerTaker The address of the taker of the auction offer,
/// who will receive the pool's seized funds
/// @param tokenPaid The token this auction is denominated in
/// @param tokenAmountPaid The amount of the token the taker paid
/// @param portionToSeize The portion of the pool the taker won at auction.
/// This amount should be divided by FLOATING_POINT_DIVISOR
/// to calculate how much of the pool should be set
/// aside as the taker's winnings.
/// @param fullyFilled Indicates whether the auction was taken fully or
/// partially. If auction was fully filled, it is
/// closed. If auction was partially filled, it is
/// sill open and waiting for remaining bids.
function offerTaken(
address offerTaker,
IERC20 tokenPaid,
uint256 tokenAmountPaid,
uint256 portionToSeize,
bool fullyFilled
) external {
require(openAuctions[msg.sender], "Sender isn't an auction");
emit AuctionOfferTaken(
msg.sender,
offerTaker,
address(tokenPaid),
tokenAmountPaid,
portionToSeize
);
// actually seize funds, setting them aside for the taker to withdraw
// from the coverage pool.
// `portionToSeize` will be divided by FLOATING_POINT_DIVISOR which is
// defined in Auction.sol
//
//slither-disable-next-line reentrancy-no-eth,reentrancy-events,reentrancy-benign
coveragePool.seizeFunds(offerTaker, portionToSeize);
Auction auction = Auction(msg.sender);
if (fullyFilled) {
onAuctionFullyFilled(auction);
emit AuctionClosed(msg.sender);
delete openAuctions[msg.sender];
openAuctionsCount -= 1;
} else {
onAuctionPartiallyFilled(auction);
}
}
/// @notice Opens a new auction against the coverage pool. The auction
/// will remain open until filled.
/// @dev Calls `Auction.initialize` to initialize the instance.
/// @param tokenAccepted The token with which the auction can be taken
/// @param amountDesired The amount denominated in _tokenAccepted. After
/// this amount is received, the auction can close.
/// @param auctionLength The amount of time it takes for the auction to get
/// to 100% of all collateral on offer, in seconds.
function createAuction(
IERC20 tokenAccepted,
uint256 amountDesired,
uint256 auctionLength
) internal returns (address) {
address cloneAddress = createClone(masterAuction);
require(cloneAddress != address(0), "Cloned auction address is 0");
Auction auction = Auction(cloneAddress);
//slither-disable-next-line reentrancy-benign,reentrancy-events
auction.initialize(this, tokenAccepted, amountDesired, auctionLength);
openAuctions[cloneAddress] = true;
openAuctionsCount += 1;
emit AuctionCreated(
address(tokenAccepted),
amountDesired,
cloneAddress
);
return cloneAddress;
}
/// @notice Tears down an open auction with given address immediately.
/// @dev Can be called by contract owner to early close an auction if it
/// is no longer needed. Bear in mind that funds from the early closed
/// auction last on the auctioneer contract. Calling code should take
/// care of them.
/// @return Amount of funds transferred to this contract by the Auction
/// being early closed.
function earlyCloseAuction(Auction auction) internal returns (uint256) {
address auctionAddress = address(auction);
require(openAuctions[auctionAddress], "Address is not an open auction");
uint256 amountTransferred = auction.amountTransferred();
//slither-disable-next-line reentrancy-no-eth,reentrancy-events,reentrancy-benign
auction.earlyClose();
emit AuctionClosed(auctionAddress);
delete openAuctions[auctionAddress];
openAuctionsCount -= 1;
return amountTransferred;
}
/// @notice Auction lifecycle hook allowing to act on auction closed
/// as fully filled. This function is not executed when an auction
/// was partially filled. When this function is executed auction is
/// already closed and funds from the coverage pool are seized.
/// @dev Override this function to act on auction closed as fully filled.
function onAuctionFullyFilled(Auction auction) internal virtual {}
/// @notice Auction lifecycle hook allowing to act on auction partially
/// filled. This function is not executed when an auction
/// was fully filled.
/// @dev Override this function to act on auction partially filled.
function onAuctionPartiallyFilled(Auction auction) internal view virtual {}
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
import "./interfaces/IAssetPoolUpgrade.sol";
import "./AssetPool.sol";
import "./CoveragePoolConstants.sol";
import "./GovernanceUtils.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Coverage Pool
/// @notice A contract that manages a single asset pool. Handles approving and
/// unapproving of risk managers and allows them to seize funds from the
/// asset pool if they are approved.
/// @dev Coverage pool contract is owned by the governance. Coverage pool is the
/// owner of the asset pool contract.
contract CoveragePool is Ownable {
AssetPool public immutable assetPool;
IERC20 public immutable collateralToken;
bool public firstRiskManagerApproved = false;
// Currently approved risk managers
mapping(address => bool) public approvedRiskManagers;
// Timestamps of risk managers whose approvals have been initiated
mapping(address => uint256) public riskManagerApprovalTimestamps;
event RiskManagerApprovalStarted(address riskManager, uint256 timestamp);
event RiskManagerApprovalCompleted(address riskManager, uint256 timestamp);
event RiskManagerUnapproved(address riskManager, uint256 timestamp);
/// @notice Reverts if called by a risk manager that is not approved
modifier onlyApprovedRiskManager() {
require(approvedRiskManagers[msg.sender], "Risk manager not approved");
_;
}
constructor(AssetPool _assetPool) {
assetPool = _assetPool;
collateralToken = _assetPool.collateralToken();
}
/// @notice Approves the first risk manager
/// @dev Can be called only by the contract owner. Can be called only once.
/// Does not require any further calls to any functions.
/// @param riskManager Risk manager that will be approved
function approveFirstRiskManager(address riskManager) external onlyOwner {
require(
!firstRiskManagerApproved,
"The first risk manager was approved"
);
approvedRiskManagers[riskManager] = true;
firstRiskManagerApproved = true;
}
/// @notice Begins risk manager approval process.
/// @dev Can be called only by the contract owner and only when the first
/// risk manager is already approved. For a risk manager to be
/// approved, a call to `finalizeRiskManagerApproval` must follow
/// (after a governance delay).
/// @param riskManager Risk manager that will be approved
function beginRiskManagerApproval(address riskManager) external onlyOwner {
require(
firstRiskManagerApproved,
"The first risk manager is not yet approved; Please use "
"approveFirstRiskManager instead"
);
require(
!approvedRiskManagers[riskManager],
"Risk manager already approved"
);
/* solhint-disable-next-line not-rely-on-time */
riskManagerApprovalTimestamps[riskManager] = block.timestamp;
/* solhint-disable-next-line not-rely-on-time */
emit RiskManagerApprovalStarted(riskManager, block.timestamp);
}
/// @notice Finalizes risk manager approval process.
/// @dev Can be called only by the contract owner. Must be preceded with a
/// call to beginRiskManagerApproval and a governance delay must elapse.
/// @param riskManager Risk manager that will be approved
function finalizeRiskManagerApproval(address riskManager)
external
onlyOwner
{
require(
riskManagerApprovalTimestamps[riskManager] > 0,
"Risk manager approval not initiated"
);
require(
/* solhint-disable-next-line not-rely-on-time */
block.timestamp - riskManagerApprovalTimestamps[riskManager] >=
assetPool.withdrawalGovernanceDelay(),
"Risk manager governance delay has not elapsed"
);
approvedRiskManagers[riskManager] = true;
/* solhint-disable-next-line not-rely-on-time */
emit RiskManagerApprovalCompleted(riskManager, block.timestamp);
delete riskManagerApprovalTimestamps[riskManager];
}
/// @notice Unapproves an already approved risk manager or cancels the
/// approval process of a risk manager (the latter happens if called
/// between `beginRiskManagerApproval` and `finalizeRiskManagerApproval`).
/// The change takes effect immediately.
/// @dev Can be called only by the contract owner.
/// @param riskManager Risk manager that will be unapproved
function unapproveRiskManager(address riskManager) external onlyOwner {
require(
riskManagerApprovalTimestamps[riskManager] > 0 ||
approvedRiskManagers[riskManager],
"Risk manager is neither approved nor with a pending approval"
);
delete riskManagerApprovalTimestamps[riskManager];
delete approvedRiskManagers[riskManager];
/* solhint-disable-next-line not-rely-on-time */
emit RiskManagerUnapproved(riskManager, block.timestamp);
}
/// @notice Approves upgradeability to the new asset pool.
/// Allows governance to set a new asset pool so the underwriters
/// can move their collateral tokens to a new asset pool without
/// having to wait for the withdrawal delay.
/// @param _newAssetPool New asset pool
function approveNewAssetPoolUpgrade(IAssetPoolUpgrade _newAssetPool)
external
onlyOwner
{
assetPool.approveNewAssetPoolUpgrade(_newAssetPool);
}
/// @notice Lets the governance to begin an update of withdrawal delay
/// parameter value. Withdrawal delay is the time it takes the
/// underwriter to withdraw their collateral and rewards from the
/// pool. This is the time that needs to pass between initiating and
/// completing the withdrawal. The change needs to be finalized with
/// a call to finalizeWithdrawalDelayUpdate after the required
/// governance delay passes. It is up to the governance to
/// decide what the withdrawal delay value should be but it should
/// be long enough so that the possibility of having free-riding
/// underwriters escaping from a potential coverage claim by
/// withdrawing their positions from the pool is negligible.
/// @param newWithdrawalDelay The new value of withdrawal delay
function beginWithdrawalDelayUpdate(uint256 newWithdrawalDelay)
external
onlyOwner
{
assetPool.beginWithdrawalDelayUpdate(newWithdrawalDelay);
}
/// @notice Lets the governance to finalize an update of withdrawal
/// delay parameter value. This call has to be preceded with
/// a call to beginWithdrawalDelayUpdate and the governance delay
/// has to pass.
function finalizeWithdrawalDelayUpdate() external onlyOwner {
assetPool.finalizeWithdrawalDelayUpdate();
}
/// @notice Lets the governance to begin an update of withdrawal timeout
/// parameter value. The withdrawal timeout is the time the
/// underwriter has - after the withdrawal delay passed - to
/// complete the withdrawal. The change needs to be finalized with
/// a call to finalizeWithdrawalTimeoutUpdate after the required
/// governance delay passes. It is up to the governance to
/// decide what the withdrawal timeout value should be but it should
/// be short enough so that the time of free-riding by being able to
/// immediately escape from the claim is minimal and long enough so
/// that honest underwriters have a possibility to finalize the
/// withdrawal. It is all about the right proportions with
/// a relation to withdrawal delay value.
/// @param newWithdrawalTimeout The new value of the withdrawal timeout
function beginWithdrawalTimeoutUpdate(uint256 newWithdrawalTimeout)
external
onlyOwner
{
assetPool.beginWithdrawalTimeoutUpdate(newWithdrawalTimeout);
}
/// @notice Lets the governance to finalize an update of withdrawal
/// timeout parameter value. This call has to be preceded with
/// a call to beginWithdrawalTimeoutUpdate and the governance delay
/// has to pass.
function finalizeWithdrawalTimeoutUpdate() external onlyOwner {
assetPool.finalizeWithdrawalTimeoutUpdate();
}
/// @notice Seizes funds from the coverage pool and puts them aside for the
/// recipient to withdraw.
/// @dev `portionToSeize` value was multiplied by `FLOATING_POINT_DIVISOR`
/// for calculation precision purposes. Further calculations in this
/// function will need to take this divisor into account.
/// @param recipient Address that will receive the pool's seized funds
/// @param portionToSeize Portion of the pool to seize in the range (0, 1]
/// multiplied by `FLOATING_POINT_DIVISOR`
function seizeFunds(address recipient, uint256 portionToSeize)
external
onlyApprovedRiskManager
{
require(
portionToSeize > 0 &&
portionToSeize <= CoveragePoolConstants.FLOATING_POINT_DIVISOR,
"Portion to seize is not within the range (0, 1]"
);
assetPool.claim(recipient, amountToSeize(portionToSeize));
}
/// @notice Grants asset pool shares by minting a given amount of the
/// underwriter tokens for the recipient address. In result, the
/// recipient obtains part of the pool ownership without depositing
/// any collateral tokens. Shares are usually granted for notifiers
/// reporting about various contract state changes.
/// @dev Can be called only by an approved risk manager.
/// @param recipient Address of the underwriter tokens recipient
/// @param covAmount Amount of the underwriter tokens which should be minted
function grantAssetPoolShares(address recipient, uint256 covAmount)
external
onlyApprovedRiskManager
{
assetPool.grantShares(recipient, covAmount);
}
/// @notice Returns the time remaining until the risk manager approval
/// process can be finalized
/// @param riskManager Risk manager in the process of approval
/// @return Remaining time in seconds.
function getRemainingRiskManagerApprovalTime(address riskManager)
external
view
returns (uint256)
{
return
GovernanceUtils.getRemainingChangeTime(
riskManagerApprovalTimestamps[riskManager],
assetPool.withdrawalGovernanceDelay()
);
}
/// @notice Calculates amount of tokens to be seized from the coverage pool.
/// @param portionToSeize Portion of the pool to seize in the range (0, 1]
/// multiplied by FLOATING_POINT_DIVISOR
function amountToSeize(uint256 portionToSeize)
public
view
returns (uint256)
{
return
(collateralToken.balanceOf(address(assetPool)) * portionToSeize) /
CoveragePoolConstants.FLOATING_POINT_DIVISOR;
}
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
library CoveragePoolConstants {
// This divisor is for precision purposes only. We use this divisor around
// auction related code to get the precise values without rounding it down
// when dealing with floating numbers.
uint256 public constant FLOATING_POINT_DIVISOR = 1e18;
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
library GovernanceUtils {
/// @notice Gets the time remaining until the governable parameter update
/// can be committed.
/// @param changeTimestamp Timestamp indicating the beginning of the change.
/// @param delay Governance delay.
/// @return Remaining time in seconds.
function getRemainingChangeTime(uint256 changeTimestamp, uint256 delay)
internal
view
returns (uint256)
{
require(changeTimestamp > 0, "Change not initiated");
/* solhint-disable-next-line not-rely-on-time */
uint256 elapsed = block.timestamp - changeTimestamp;
if (elapsed >= delay) {
return 0;
} else {
return delay - elapsed;
}
}
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Rewards Pool
/// @notice RewardsPool accepts a single reward token and releases it to the
/// AssetPool over time in one week reward intervals. The owner of this
/// contract is the reward distribution address funding it with reward
/// tokens.
contract RewardsPool is Ownable {
using SafeERC20 for IERC20;
uint256 public constant DURATION = 7 days;
IERC20 public immutable rewardToken;
address public immutable assetPool;
// timestamp of the current reward interval end or the timestamp of the
// last interval end in case a new reward interval has not been allocated
uint256 public intervalFinish = 0;
// rate per second with which reward tokens are unlocked
uint256 public rewardRate = 0;
// amount of rewards accumulated and not yet withdrawn from the previous
// reward interval(s)
uint256 public rewardAccumulated = 0;
// the last time information in this contract was updated
uint256 public lastUpdateTime = 0;
event RewardToppedUp(uint256 amount);
event RewardWithdrawn(uint256 amount);
constructor(
IERC20 _rewardToken,
address _assetPool,
address owner
) {
rewardToken = _rewardToken;
// slither-disable-next-line missing-zero-check
assetPool = _assetPool;
transferOwnership(owner);
}
/// @notice Transfers the provided reward amount into RewardsPool and
/// creates a new, one-week reward interval starting from now.
/// Reward tokens from the previous reward interval that unlocked
/// over the time will be available for withdrawal immediately.
/// Reward tokens from the previous interval that has not been yet
/// unlocked, are added to the new interval being created.
/// @dev This function can be called only by the owner given that it creates
/// a new interval with one week length, starting from now.
function topUpReward(uint256 reward) external onlyOwner {
rewardAccumulated = earned();
/* solhint-disable not-rely-on-time */
if (block.timestamp >= intervalFinish) {
// see https://github.com/crytic/slither/issues/844
// slither-disable-next-line divide-before-multiply
rewardRate = reward / DURATION;
} else {
uint256 remaining = intervalFinish - block.timestamp;
uint256 leftover = remaining * rewardRate;
rewardRate = (reward + leftover) / DURATION;
}
intervalFinish = block.timestamp + DURATION;
lastUpdateTime = block.timestamp;
/* solhint-enable avoid-low-level-calls */
emit RewardToppedUp(reward);
rewardToken.safeTransferFrom(msg.sender, address(this), reward);
}
/// @notice Withdraws all unlocked reward tokens to the AssetPool.
function withdraw() external {
uint256 amount = earned();
rewardAccumulated = 0;
lastUpdateTime = lastTimeRewardApplicable();
emit RewardWithdrawn(amount);
rewardToken.safeTransfer(assetPool, amount);
}
/// @notice Returns the amount of earned and not yet withdrawn reward
/// tokens.
function earned() public view returns (uint256) {
return
rewardAccumulated +
((lastTimeRewardApplicable() - lastUpdateTime) * rewardRate);
}
/// @notice Returns the timestamp at which a reward was last time applicable.
/// When reward interval is pending, returns current block's
/// timestamp. If the last reward interval ended and no other reward
/// interval had been allocated, returns the last reward interval's
/// end timestamp.
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, intervalFinish);
}
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
import "@thesis/solidity-contracts/contracts/token/ERC20WithPermit.sol";
/// @title UnderwriterToken
/// @notice Underwriter tokens represent an ownership share in the underlying
/// collateral of the asset-specific pool. Underwriter tokens are minted
/// when a user deposits ERC20 tokens into asset-specific pool and they
/// are burned when a user exits the position. Underwriter tokens
/// natively support meta transactions. Users can authorize a transfer
/// of their underwriter tokens with a signature conforming EIP712
/// standard instead of an on-chain transaction from their address.
/// Anyone can submit this signature on the user's behalf by calling the
/// permit function, as specified in EIP2612 standard, paying gas fees,
/// and possibly performing other actions in the same transaction.
contract UnderwriterToken is ERC20WithPermit {
constructor(string memory _name, string memory _symbol)
ERC20WithPermit(_name, _symbol)
{}
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
/// @title Asset Pool interface
/// @notice Asset Pool accepts a single ERC20 token as collateral, and returns
/// an underwriter token. For example, an asset pool might accept deposits
/// in KEEP in return for covKEEP underwriter tokens. Underwriter tokens
/// represent an ownership share in the underlying collateral of the
/// Asset Pool.
interface IAssetPool {
/// @notice Accepts the given amount of collateral token as a deposit and
/// mints underwriter tokens representing pool's ownership.
/// @dev Before calling this function, collateral token needs to have the
/// required amount accepted to transfer to the asset pool.
/// @return The amount of minted underwriter tokens
function deposit(uint256 amount) external returns (uint256);
/// @notice Accepts the given amount of collateral token as a deposit and
/// mints at least a minAmountToMint underwriter tokens representing
/// pool's ownership.
/// @dev Before calling this function, collateral token needs to have the
/// required amount accepted to transfer to the asset pool.
/// @return The amount of minted underwriter tokens
function depositWithMin(uint256 amountToDeposit, uint256 minAmountToMint)
external
returns (uint256);
/// @notice Initiates the withdrawal of collateral and rewards from the pool.
/// @dev Before calling this function, underwriter token needs to have the
/// required amount accepted to transfer to the asset pool.
function initiateWithdrawal(uint256 covAmount) external;
/// @notice Completes the previously initiated withdrawal for the
/// underwriter.
/// @return The amount of collateral withdrawn
function completeWithdrawal(address underwriter) external returns (uint256);
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
/// @title Asset Pool upgrade interface
/// @notice Interface that has to be implemented by an Asset Pool accepting
/// upgrades from another asset pool.
interface IAssetPoolUpgrade {
/// @notice Accepts the given underwriter with collateral tokens amount as a
/// deposit. In exchange new underwriter tokens will be calculated,
/// minted and then transferred back to the underwriter.
function depositFor(address underwriter, uint256 amount) external;
}
// ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀
// ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌
// ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
// ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓
//
// Trust math, not hardware.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.5;
/// @title Auction interface
/// @notice Auction runs a linear falling-price auction against a diverse
/// basket of assets held in a collateral pool. Auctions are taken using
/// a single asset. Over time, a larger and larger portion of the assets
/// are on offer, eventually hitting 100% of the backing collateral
interface IAuction {
/// @notice Takes an offer from an auction buyer. There are two possible
/// ways to take an offer from a buyer. The first one is to buy
/// entire auction with the amount desired for this auction.
/// The other way is to buy a portion of an auction. In this case an
/// auction depleting rate is increased.
/// @dev The implementation is not guaranteed to be protecting against
/// frontrunning. See `AuctionBidder` for an example protection.
function takeOffer(uint256 amount) external;
/// @notice How much of the collateral pool can currently be purchased at
/// auction, across all assets.
/// @return The ratio of the collateral pool currently on offer and divisor
/// for precision purposes.
function onOffer() external view returns (uint256, uint256);
}
|
Allows governance to cancel already approved new asset pool in case of some misconfiguration.
|
function cancelNewAssetPoolUpgrade() external onlyOwner {
emit CancelledAssetPoolUpgrade(address(newAssetPool));
newAssetPool = IAssetPoolUpgrade(address(0));
}
| 112,370 |
pragma solidity ^0.4.25;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
/**
* @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);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @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 Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Claimable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
/**
* @title JZMLock
* @author http://jzm.one
* @dev JZMLock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/
contract JZMLock {
using SafeERC20 for ERC20Basic;
// ERC20 basic token contract being held
ERC20Basic public token;
// beneficiary of tokens after they are released
address public beneficiary;
// timestamp when token release is enabled
uint256 public releaseTime;
constructor(
ERC20Basic _token,
address _beneficiary,
uint256 _releaseTime
)
public
{
// solium-disable-next-line security/no-block-members
require(_releaseTime > block.timestamp);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
/**
* @notice Transfers tokens held by JZMLock to beneficiary.
*/
function release() public {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= releaseTime);
uint256 amount = token.balanceOf(address(this));
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
function canRelease() public view returns (bool){
return block.timestamp >= releaseTime;
}
}
/**
* @title JZMToken
* @author http://jzm.one
* @dev JZMToken is a token that provide lock function
*/
contract JZMToken is PausableToken {
event TransferWithLock(address indexed from, address indexed to, address indexed locked, uint256 amount, uint256 releaseTime);
mapping (address => address[] ) public balancesLocked;
function transferWithLock(address _to, uint256 _amount, uint256 _releaseTime) public returns (bool) {
JZMLock lock = new JZMLock(this, _to, _releaseTime);
transfer(address(lock), _amount);
balancesLocked[_to].push(lock);
emit TransferWithLock(msg.sender, _to, address(lock), _amount, _releaseTime);
return true;
}
/**
* @dev Gets the locked balance of the specified address.
* @param _owner The address to query the locked balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOfLocked(address _owner) public view returns (uint256) {
address[] memory lockTokenAddrs = balancesLocked[_owner];
uint256 totalLockedBalance = 0;
for (uint i = 0; i < lockTokenAddrs.length; i++) {
totalLockedBalance = totalLockedBalance.add(balances[lockTokenAddrs[i]]);
}
return totalLockedBalance;
}
function releaseToken(address _owner) public returns (bool) {
address[] memory lockTokenAddrs = balancesLocked[_owner];
for (uint i = 0; i < lockTokenAddrs.length; i++) {
JZMLock lock = JZMLock(lockTokenAddrs[i]);
if (lock.canRelease() && balanceOf(lock)>0) {
lock.release();
}
}
return true;
}
}
/**
* @title TUToken
* @dev Trust Union Token Contract
*/
contract TUToken is JZMToken {
using SafeMath for uint256;
string public constant name = "Trust Union";
string public constant symbol = "TUT";
uint8 public constant decimals = 18;
uint256 private constant TOKEN_UNIT = 10 ** uint256(decimals);
uint256 private constant INITIAL_SUPPLY = (10 ** 9) * TOKEN_UNIT;
//init wallet address
address private constant ADDR_MARKET = 0xEd3998AA7F255Ade06236776f9FD429eECc91357;
address private constant ADDR_FOUNDTEAM = 0x1867812567f42e2Da3C572bE597996B1309593A7;
address private constant ADDR_ECO = 0xF7549be7449aA2b7D708d39481fCBB618C9Fb903;
address private constant ADDR_PRIVATE_SALE = 0x252c4f77f1cdCCEBaEBbce393804F4c8f3D5703D;
address private constant ADDR_SEED_INVESTOR = 0x03a59D08980A5327a958860e346d020ec8bb33dC;
address private constant ADDR_FOUNDATION = 0xC138d62b3E34391964852Cf712454492DC7eFF68;
//init supply for market = 5%
uint256 private constant S_MARKET_TOTAL = INITIAL_SUPPLY * 5 / 100;
uint256 private constant S_MARKET_20181030 = 5000000 * TOKEN_UNIT;
uint256 private constant S_MARKET_20190130 = 10000000 * TOKEN_UNIT;
uint256 private constant S_MARKET_20190430 = 15000000 * TOKEN_UNIT;
uint256 private constant S_MARKET_20190730 = 20000000 * TOKEN_UNIT;
//init supply for founding team = 15%
uint256 private constant S_FOUNDTEAM_TOTAL = INITIAL_SUPPLY * 15 / 100;
uint256 private constant S_FOUNDTEAM_20191030 = INITIAL_SUPPLY * 5 / 100;
uint256 private constant S_FOUNDTEAM_20200430 = INITIAL_SUPPLY * 5 / 100;
uint256 private constant S_FOUNDTEAM_20201030 = INITIAL_SUPPLY * 5 / 100;
//init supply for ecological incentive = 40%
uint256 private constant S_ECO_TOTAL = INITIAL_SUPPLY * 40 / 100;
uint256 private constant S_ECO_20190401 = 45000000 * TOKEN_UNIT;
uint256 private constant S_ECO_20191001 = 45000000 * TOKEN_UNIT;
uint256 private constant S_ECO_20200401 = 40000000 * TOKEN_UNIT;
uint256 private constant S_ECO_20201001 = 40000000 * TOKEN_UNIT;
uint256 private constant S_ECO_20210401 = 35000000 * TOKEN_UNIT;
uint256 private constant S_ECO_20211001 = 35000000 * TOKEN_UNIT;
uint256 private constant S_ECO_20220401 = 30000000 * TOKEN_UNIT;
uint256 private constant S_ECO_20221001 = 30000000 * TOKEN_UNIT;
uint256 private constant S_ECO_20230401 = 25000000 * TOKEN_UNIT;
uint256 private constant S_ECO_20231001 = 25000000 * TOKEN_UNIT;
uint256 private constant S_ECO_20240401 = 25000000 * TOKEN_UNIT;
uint256 private constant S_ECO_20241001 = 25000000 * TOKEN_UNIT;
//init supply for private sale = 10%
uint256 private constant S_PRIVATE_SALE = INITIAL_SUPPLY * 10 / 100;
//init supply for seed investor = 10%
uint256 private constant S_SEED_INVESTOR = INITIAL_SUPPLY * 10 / 100;
//init supply for foundation = 20%
uint256 private constant S_FOUNDATION = INITIAL_SUPPLY * 20 / 100;
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[owner] = totalSupply_;
_initWallet();
_invokeLockLogic();
}
/**
* @dev init the wallets
*/
function _initWallet() internal onlyOwner {
transfer(ADDR_PRIVATE_SALE, S_PRIVATE_SALE);
transfer(ADDR_SEED_INVESTOR, S_SEED_INVESTOR);
transfer(ADDR_FOUNDATION, S_FOUNDATION);
}
/**
* @dev invoke lock logic
*/
function _invokeLockLogic() internal onlyOwner {
//lock for market
//2018/10/30 0:00:00 UTC +8
transferWithLock(ADDR_MARKET, S_MARKET_20181030, 1540828800);
//2019/01/30 0:00:00 UTC +8
transferWithLock(ADDR_MARKET, S_MARKET_20190130, 1548777600);
//2019/04/30 0:00:00 UTC +8
transferWithLock(ADDR_MARKET, S_MARKET_20190430, 1556553600);
//2019/07/30 0:00:00 UTC +8
transferWithLock(ADDR_MARKET, S_MARKET_20190730, 1564416000);
//lock for found team
//2019/10/30 0:00:00 UTC +8
transferWithLock(ADDR_FOUNDTEAM, S_FOUNDTEAM_20191030, 1572364800);
//2020/04/30 0:00:00 UTC +8
transferWithLock(ADDR_FOUNDTEAM, S_FOUNDTEAM_20200430, 1588176000);
//2020/10/30 0:00:00 UTC +8
transferWithLock(ADDR_FOUNDTEAM, S_FOUNDTEAM_20201030, 1603987200);
//lock for eco
//2019/04/01 0:00:00 UTC +8
transferWithLock(ADDR_ECO, S_ECO_20190401, 1554048000);
//2019/10/01 0:00:00 UTC +8
transferWithLock(ADDR_ECO, S_ECO_20191001, 1569859200);
//2020/04/01 0:00:00 UTC +8
transferWithLock(ADDR_ECO, S_ECO_20200401, 1585670400);
//2020/10/01 0:00:00 UTC +8
transferWithLock(ADDR_ECO, S_ECO_20201001, 1601481600);
//2021/04/01 0:00:00 UTC +8
transferWithLock(ADDR_ECO, S_ECO_20210401, 1617206400);
//2021/10/01 0:00:00 UTC +8
transferWithLock(ADDR_ECO, S_ECO_20211001, 1633017600);
//2022/04/01 0:00:00 UTC +8
transferWithLock(ADDR_ECO, S_ECO_20220401, 1648742400);
//2022/10/01 0:00:00 UTC +8
transferWithLock(ADDR_ECO, S_ECO_20221001, 1664553600);
//2023/04/01 0:00:00 UTC +8
transferWithLock(ADDR_ECO, S_ECO_20230401, 1680278400);
//2023/10/01 0:00:00 UTC +8
transferWithLock(ADDR_ECO, S_ECO_20231001, 1696089600);
//2024/04/01 0:00:00 UTC +8
transferWithLock(ADDR_ECO, S_ECO_20240401, 1711900800);
//2024/10/01 0:00:00 UTC +8
transferWithLock(ADDR_ECO, S_ECO_20241001, 1727712000);
}
}
|
invoke lock logic/lock for market2018/10/30 0:00:00 UTC +82019/01/30 0:00:00 UTC +82019/04/30 0:00:00 UTC +82019/07/30 0:00:00 UTC +8lock for found team2019/10/30 0:00:00 UTC +82020/04/30 0:00:00 UTC +82020/10/30 0:00:00 UTC +8lock for eco2019/04/01 0:00:00 UTC +82019/10/01 0:00:00 UTC +82020/04/01 0:00:00 UTC +82020/10/01 0:00:00 UTC +82021/04/01 0:00:00 UTC +82021/10/01 0:00:00 UTC +82022/04/01 0:00:00 UTC +82022/10/01 0:00:00 UTC +82023/04/01 0:00:00 UTC +82023/10/01 0:00:00 UTC +82024/04/01 0:00:00 UTC +82024/10/01 0:00:00 UTC +8
|
function _invokeLockLogic() internal onlyOwner {
transferWithLock(ADDR_MARKET, S_MARKET_20181030, 1540828800);
transferWithLock(ADDR_MARKET, S_MARKET_20190130, 1548777600);
transferWithLock(ADDR_MARKET, S_MARKET_20190430, 1556553600);
transferWithLock(ADDR_MARKET, S_MARKET_20190730, 1564416000);
transferWithLock(ADDR_FOUNDTEAM, S_FOUNDTEAM_20191030, 1572364800);
transferWithLock(ADDR_FOUNDTEAM, S_FOUNDTEAM_20200430, 1588176000);
transferWithLock(ADDR_FOUNDTEAM, S_FOUNDTEAM_20201030, 1603987200);
transferWithLock(ADDR_ECO, S_ECO_20190401, 1554048000);
transferWithLock(ADDR_ECO, S_ECO_20191001, 1569859200);
transferWithLock(ADDR_ECO, S_ECO_20200401, 1585670400);
transferWithLock(ADDR_ECO, S_ECO_20201001, 1601481600);
transferWithLock(ADDR_ECO, S_ECO_20210401, 1617206400);
transferWithLock(ADDR_ECO, S_ECO_20211001, 1633017600);
transferWithLock(ADDR_ECO, S_ECO_20220401, 1648742400);
transferWithLock(ADDR_ECO, S_ECO_20221001, 1664553600);
transferWithLock(ADDR_ECO, S_ECO_20230401, 1680278400);
transferWithLock(ADDR_ECO, S_ECO_20231001, 1696089600);
transferWithLock(ADDR_ECO, S_ECO_20240401, 1711900800);
transferWithLock(ADDR_ECO, S_ECO_20241001, 1727712000);
}
| 999,288 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.